test.cc 899 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773
  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. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. }
  153. #if defined(__linux__) || \
  154. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  155. TEST_F(UnixSocketTest, PeerPid) {
  156. httplib::Server svr;
  157. std::string remote_port_val;
  158. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  159. res.set_content(content_, "text/plain");
  160. remote_port_val = std::to_string(req.remote_port);
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(pathname_);
  173. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  174. }
  175. #endif
  176. #ifdef __linux__
  177. TEST_F(UnixSocketTest, abstract) {
  178. constexpr char svr_path[]{"\x00httplib-server.sock"};
  179. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  180. httplib::Server svr;
  181. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. client_GET(abstract_addr);
  195. }
  196. #endif
  197. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  198. httplib::Server svr;
  199. std::string received_host_header;
  200. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  201. // Capture the Host header sent by the client
  202. auto host_iter = req.headers.find("Host");
  203. if (host_iter != req.headers.end()) {
  204. received_host_header = host_iter->second;
  205. }
  206. res.set_content(content_, "text/plain");
  207. });
  208. std::thread t{[&] {
  209. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  210. }};
  211. auto se = detail::scope_exit([&] {
  212. svr.stop();
  213. t.join();
  214. ASSERT_FALSE(svr.is_running());
  215. });
  216. svr.wait_until_ready();
  217. ASSERT_TRUE(svr.is_running());
  218. // Test that Host header is automatically set to "localhost" for Unix socket
  219. // connections
  220. httplib::Client cli{pathname_};
  221. cli.set_address_family(AF_UNIX);
  222. ASSERT_TRUE(cli.is_valid());
  223. const auto &result = cli.Get(pattern_);
  224. ASSERT_TRUE(result) << "error: " << result.error();
  225. const auto &resp = result.value();
  226. EXPECT_EQ(resp.status, StatusCode::OK_200);
  227. EXPECT_EQ(resp.body, content_);
  228. // Verify that Host header was automatically set to "localhost"
  229. EXPECT_EQ(received_host_header, "localhost");
  230. }
  231. #ifndef _WIN32
  232. TEST(SocketStream, wait_writable_UNIX) {
  233. int fds[2];
  234. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  235. const auto asSocketStream = [&](socket_t fd,
  236. std::function<bool(Stream &)> func) {
  237. return detail::process_client_socket(
  238. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  239. };
  240. asSocketStream(fds[0], [&](Stream &s0) {
  241. EXPECT_EQ(s0.socket(), fds[0]);
  242. EXPECT_TRUE(s0.wait_writable());
  243. EXPECT_TRUE(s0.is_peer_alive());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.is_peer_alive());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. // PORT + 1 is shared with the SSL redirect tests and with
  261. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  262. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  263. // because that happens on a worker thread the ASSERT does not stop the
  264. // test: it runs on and fails at the disconnected_svr_sock check instead.
  265. default_socket_options(s);
  266. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, listen(s, 1));
  268. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  269. ASSERT_EQ(0, close(s));
  270. }};
  271. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  272. std::thread cli{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, close(s));
  277. }};
  278. cli.join();
  279. svr.join();
  280. ASSERT_NE(disconnected_svr_sock, -1);
  281. const auto asSocketStream = [&](socket_t fd,
  282. std::function<bool(Stream &)> func) {
  283. return detail::process_client_socket(
  284. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  285. };
  286. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  287. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  288. // wait_writable() returns true because select_write() only checks if the
  289. // send buffer has space. Peer disconnection is detected later by send().
  290. EXPECT_TRUE(ss.wait_writable());
  291. return true;
  292. });
  293. ASSERT_EQ(0, close(disconnected_svr_sock));
  294. }
  295. #endif // #ifndef _WIN32
  296. TEST(SetSocketOptTest, TcpNoDelay) {
  297. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  298. ASSERT_NE(sock, INVALID_SOCKET);
  299. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  300. int val = 0;
  301. socklen_t len = sizeof(val);
  302. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  303. reinterpret_cast<char *>(&val), &len));
  304. EXPECT_NE(val, 0);
  305. detail::close_socket(sock);
  306. }
  307. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  308. // accept() reports failures through WSAGetLastError() on Windows and through
  309. // errno everywhere else. Asking the wrong one is what made the accept loop
  310. // treat every recoverable failure as fatal on Windows.
  311. struct Classification {
  312. bool resource;
  313. bool transient;
  314. };
  315. auto classify = [](int err) {
  316. #ifdef _WIN32
  317. WSASetLastError(err);
  318. #else
  319. errno = err;
  320. #endif
  321. // Read both before asserting: an assertion may clobber the error slot.
  322. Classification c;
  323. c.resource = detail::is_accept_resource_error();
  324. c.transient = detail::is_accept_transient_error();
  325. return c;
  326. };
  327. #ifdef _WIN32
  328. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  329. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  330. WSAECONNRESET, WSAECONNABORTED};
  331. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  332. #else
  333. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  334. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  335. ECONNABORTED};
  336. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  337. #endif
  338. for (auto err : resource_errors) {
  339. const auto c = classify(err);
  340. EXPECT_TRUE(c.resource) << "error " << err;
  341. EXPECT_FALSE(c.transient) << "error " << err;
  342. }
  343. for (auto err : transient_errors) {
  344. const auto c = classify(err);
  345. EXPECT_TRUE(c.transient) << "error " << err;
  346. EXPECT_FALSE(c.resource) << "error " << err;
  347. }
  348. for (auto err : fatal_errors) {
  349. const auto c = classify(err);
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. #ifdef _WIN32
  354. WSASetLastError(0);
  355. #else
  356. errno = 0;
  357. #endif
  358. }
  359. TEST(ClientTest, MoveConstructible) {
  360. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  361. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  362. }
  363. TEST(ClientTest, MoveAssignable) {
  364. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  366. }
  367. #ifdef _WIN32
  368. TEST(StartupTest, WSAStartup) {
  369. WSADATA wsaData;
  370. int ret = WSAStartup(0x0002, &wsaData);
  371. ASSERT_EQ(0, ret);
  372. }
  373. #endif
  374. TEST(DecodePathTest, PercentCharacter) {
  375. EXPECT_EQ(
  376. decode_path_component(
  377. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  378. U8("descrip=Gastos áéíóúñÑ 6"));
  379. }
  380. TEST(DecodePathTest, PercentCharacterNUL) {
  381. string expected;
  382. expected.push_back('x');
  383. expected.push_back('\0');
  384. expected.push_back('x');
  385. EXPECT_EQ(decode_path_component("x%00x"), expected);
  386. }
  387. TEST(DecodePathTest, UnicodeEncoding) {
  388. // %u0041 = 'A' (1-byte UTF-8)
  389. EXPECT_EQ("A", decode_path_component("%u0041"));
  390. // %u00E9 = 'é' (2-byte UTF-8)
  391. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  392. // %u3042 = 'あ' (3-byte UTF-8)
  393. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  394. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  395. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  396. // %uD800 = surrogate (invalid, silently dropped)
  397. EXPECT_EQ("", decode_path_component("%uD800"));
  398. }
  399. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  400. // A sign or whitespace inside the two-character escape window must not be
  401. // accepted as a valid percent-encoding; the sequence is passed through
  402. // literally, matching decode_uri_component / decode_path_component.
  403. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  404. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  405. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  406. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  407. // Well-formed escapes still decode.
  408. EXPECT_EQ("-", decode_query_component("%2D", false));
  409. EXPECT_EQ("A", decode_query_component("%41", false));
  410. }
  411. TEST(SanitizeFilenameTest, VariousPatterns) {
  412. // Path traversal
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  415. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  416. // Normal and edge cases
  417. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  418. EXPECT_EQ("filename.txt",
  419. httplib::sanitize_filename("/path/to/filename.txt"));
  420. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  421. EXPECT_EQ("", httplib::sanitize_filename(".."));
  422. EXPECT_EQ("", httplib::sanitize_filename(""));
  423. // Null bytes stripped
  424. EXPECT_EQ("safe.txt",
  425. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  426. // Whitespace-only rejected
  427. EXPECT_EQ("", httplib::sanitize_filename(" "));
  428. }
  429. // Forward declaration (see the base64_encode note below): split builds move the
  430. // definition into httplib.cc, so re-declaring it here lets the test link.
  431. namespace httplib {
  432. namespace detail {
  433. bool is_chunked_transfer_encoding(const Headers &headers);
  434. } // namespace detail
  435. } // namespace httplib
  436. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  437. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  438. auto make = [](std::initializer_list<const char *> lines) {
  439. Headers h;
  440. for (auto te : lines) {
  441. if (te) { h.emplace("Transfer-Encoding", te); }
  442. }
  443. return h;
  444. };
  445. // Sole coding, matched case-insensitively.
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  449. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  453. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  458. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  459. // were received, into one list. Headers preserves that order, so the answer
  460. // is decided by the last coding of the last line and the order the lines
  461. // arrived in is significant.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  465. // The split can fall anywhere in the list.
  466. EXPECT_TRUE(
  467. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  468. EXPECT_FALSE(
  469. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  470. // A trailing line naming no coding leaves the list ending in nothing, so it
  471. // must not inherit the chunked from the line before it.
  472. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  473. }
  474. // Forward declaration: in split builds split.py strips `inline` and moves the
  475. // definition into httplib.cc, so detail::base64_encode is not visible from the
  476. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  477. // in both header-only and split builds.
  478. namespace httplib {
  479. namespace detail {
  480. std::string base64_encode(const std::string &in);
  481. } // namespace detail
  482. } // namespace httplib
  483. TEST(Base64EncodeTest, KnownAnswers) {
  484. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  485. // where the accumulator's top bit is already set before the next shift.
  486. EXPECT_EQ("", detail::base64_encode(""));
  487. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  488. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  489. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  490. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  491. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  492. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  493. // High bytes keep the top bit set across several rounds.
  494. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  495. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  496. }
  497. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  498. string unescapedCharacters = "-_.!~*'()";
  499. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  500. }
  501. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  502. string reservedCharacters = ";,/?:@&=+$";
  503. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  504. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  505. }
  506. TEST(ClientQueryOrder, PreserveOrder) {
  507. // This test reproduces Issue #2259: client may reorder query parameters
  508. // when sending a GET request. The expected behavior is that the client
  509. // preserves the original query string order when the caller supplied it
  510. // as part of the path.
  511. Server svr;
  512. svr.Get("/", [&](const Request &req, Response &res) {
  513. // Echo back the raw target so the test can assert ordering
  514. res.set_content(req.target, "text/plain");
  515. });
  516. std::thread t{[&] { svr.listen(HOST, PORT); }};
  517. auto se = detail::scope_exit([&] {
  518. svr.stop();
  519. t.join();
  520. ASSERT_FALSE(svr.is_running());
  521. });
  522. svr.wait_until_ready();
  523. Client cli(HOST, PORT);
  524. ASSERT_TRUE(cli.is_valid());
  525. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  526. auto res = cli.Get(original);
  527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  528. // Expect the echoed target to exactly match the original path (order
  529. // preserved)
  530. EXPECT_EQ(res->body, original);
  531. }
  532. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  533. string chineseCharacters = U8("中国語");
  534. string russianCharacters = U8("дом");
  535. string brazilianCharacters = U8("óculos");
  536. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  537. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  538. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  539. "%D0%B4%D0%BE%D0%BC");
  540. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  541. }
  542. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  543. string unescapedCharacters = "-_.!~*'()";
  544. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  545. }
  546. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  547. string reservedCharacters = ";,/?:@&=+$";
  548. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  549. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  550. }
  551. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  552. string chineseCharacters = U8("中国語");
  553. string russianCharacters = U8("дом");
  554. string brazilianCharacters = U8("óculos");
  555. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  556. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  557. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  558. "%D0%B4%D0%BE%D0%BC");
  559. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  560. }
  561. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  562. // Issue #2082 use case: encoding path component with ampersand
  563. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  564. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  565. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  566. }
  567. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  568. string unescapedCharacters = "-_.!~*'()";
  569. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  570. }
  571. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  572. string reservedCharacters = ";,/?:@&=+$#";
  573. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  574. }
  575. TEST(EncodeUriTest, TestUTF8Characters) {
  576. string chineseCharacters = U8("中国語");
  577. string russianCharacters = U8("дом");
  578. string brazilianCharacters = U8("óculos");
  579. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  580. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  581. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  582. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  583. }
  584. TEST(EncodeUriTest, TestCompleteUri) {
  585. string uri =
  586. "https://example.com/path/to/resource?query=value&param=test#fragment";
  587. EXPECT_EQ(
  588. httplib::encode_uri(uri),
  589. "https://example.com/path/to/resource?query=value&param=test#fragment");
  590. }
  591. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  592. string uri =
  593. "https://example.com/path with spaces/file name.html?q=hello world";
  594. EXPECT_EQ(httplib::encode_uri(uri),
  595. "https://example.com/path%20with%20spaces/"
  596. "file%20name.html?q=hello%20world");
  597. }
  598. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  599. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  600. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  601. }
  602. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  603. string unescapedCharacters = "-_.!~*'()";
  604. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  605. }
  606. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  607. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  608. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  609. string encodedBrazilian = "%C3%B3culos";
  610. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  612. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  613. }
  614. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  615. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  616. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  617. "Piri Tommy Villiers - on & on");
  618. }
  619. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  620. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  621. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  622. }
  623. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  624. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  625. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  626. }
  627. TEST(DecodeUriTest, TestUTF8Characters) {
  628. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  629. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  630. string encodedBrazilian = "%C3%B3culos";
  631. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  632. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  633. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  634. }
  635. TEST(DecodeUriTest, TestCompleteUri) {
  636. string encodedUri = "https://example.com/path%20with%20spaces/"
  637. "file%20name.html?q=hello%20world";
  638. EXPECT_EQ(
  639. httplib::decode_uri(encodedUri),
  640. "https://example.com/path with spaces/file name.html?q=hello world");
  641. }
  642. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  643. string original =
  644. "https://example.com/path with spaces/file name.html?q=hello world";
  645. string encoded = httplib::encode_uri(original);
  646. string decoded = httplib::decode_uri(encoded);
  647. EXPECT_EQ(decoded, original);
  648. }
  649. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  650. // decode_uri is the inverse of encode_uri: an escaped reserved character
  651. // stays encoded so it is not promoted into a real delimiter, while
  652. // non-reserved escapes still decode (like JS decodeURI).
  653. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  654. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  655. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  656. "%3F%3A%40%26%3D%2B%24%2C%3B");
  657. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  658. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  659. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  660. "http://example.com/a%2Fb");
  661. // decode_uri_component still decodes the reserved character.
  662. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  663. }
  664. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  665. string original = "Piri Tommy Villiers - on & on";
  666. string encoded = httplib::encode_uri_component(original);
  667. string decoded = httplib::decode_uri_component(encoded);
  668. EXPECT_EQ(decoded, original);
  669. }
  670. TEST(TrimTests, TrimStringTests) {
  671. EXPECT_EQ("abc", detail::trim_copy("abc"));
  672. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  673. EXPECT_TRUE(detail::trim_copy("").empty());
  674. }
  675. TEST(AsciiTest, LocaleIndependentClassification) {
  676. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  677. // which consult the global C locale: std::isalnum(0xC5) can return true
  678. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  679. // helpers must classify every byte by the ASCII grammar alone.
  680. for (int i = 0; i < 256; i++) {
  681. auto c = static_cast<char>(i);
  682. auto is_digit = i >= '0' && i <= '9';
  683. auto is_upper = i >= 'A' && i <= 'Z';
  684. auto is_lower = i >= 'a' && i <= 'z';
  685. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  686. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  687. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  688. << "byte " << i;
  689. }
  690. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  691. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  692. // Non-ASCII bytes must be percent-encoded, never passed through as
  693. // alphanumeric.
  694. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  695. }
  696. TEST(FromCharsTest, Double) {
  697. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  698. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  699. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  700. auto parse = [](const std::string &s, double &v) {
  701. return detail::from_chars(s.data(), s.data() + s.size(), v);
  702. };
  703. double v = -1.0;
  704. // Representative quality values.
  705. EXPECT_EQ(parse("0", v).ec, std::errc{});
  706. EXPECT_DOUBLE_EQ(v, 0.0);
  707. EXPECT_EQ(parse("1", v).ec, std::errc{});
  708. EXPECT_DOUBLE_EQ(v, 1.0);
  709. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  710. EXPECT_DOUBLE_EQ(v, 0.8);
  711. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  712. EXPECT_DOUBLE_EQ(v, 0.001);
  713. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 1.0);
  715. // A missing integer or fractional part is tolerated.
  716. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  717. EXPECT_DOUBLE_EQ(v, 0.5);
  718. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 5.0);
  720. // Values outside [0, 1] still parse; the caller range-checks them.
  721. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  722. EXPECT_DOUBLE_EQ(v, 123.456);
  723. // Stops at the first byte that is not part of the number and reports where.
  724. std::string trailing = "0.9, text/html";
  725. auto r = parse(trailing, v);
  726. EXPECT_EQ(r.ec, std::errc{});
  727. EXPECT_DOUBLE_EQ(v, 0.9);
  728. EXPECT_EQ(*r.ptr, ',');
  729. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  730. // outright, and an 'e'/'E' simply ends the number.
  731. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  732. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  733. std::string exp_input = "1.5e3";
  734. r = parse(exp_input, v);
  735. EXPECT_EQ(r.ec, std::errc{});
  736. EXPECT_DOUBLE_EQ(v, 1.5);
  737. EXPECT_EQ(*r.ptr, 'e');
  738. // Invalid inputs.
  739. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  743. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  744. // Pathological but well-formed inputs must stay bounded (no overflow, no
  745. // out-of-bounds table access) and stay within [0, 1] for the caller.
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  747. std::errc{});
  748. EXPECT_DOUBLE_EQ(v, 0.0);
  749. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  750. std::errc{});
  751. EXPECT_GE(v, 0.0);
  752. EXPECT_LE(v, 1.0);
  753. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  754. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  755. }
  756. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  757. // Simple case without quality values
  758. std::vector<std::string> result1;
  759. EXPECT_TRUE(detail::parse_accept_header(
  760. "text/html,application/json,text/plain", result1));
  761. EXPECT_EQ(result1.size(), 3U);
  762. EXPECT_EQ(result1[0], "text/html");
  763. EXPECT_EQ(result1[1], "application/json");
  764. EXPECT_EQ(result1[2], "text/plain");
  765. // With quality values
  766. std::vector<std::string> result2;
  767. EXPECT_TRUE(detail::parse_accept_header(
  768. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  769. EXPECT_EQ(result2.size(), 3U);
  770. EXPECT_EQ(result2[0], "application/json"); // highest q value
  771. EXPECT_EQ(result2[1], "text/html");
  772. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  773. }
  774. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  775. // Mixed with and without quality values
  776. std::vector<std::string> result;
  777. EXPECT_TRUE(detail::parse_accept_header(
  778. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  779. EXPECT_EQ(result.size(), 3U);
  780. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  781. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  782. EXPECT_EQ(result[2], "application/json"); // q=0.5
  783. }
  784. TEST(ParseAcceptHeaderTest, EdgeCases) {
  785. // Empty header
  786. std::vector<std::string> empty_result;
  787. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  788. EXPECT_TRUE(empty_result.empty());
  789. // Single type
  790. std::vector<std::string> single_result;
  791. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  792. EXPECT_EQ(single_result.size(), 1U);
  793. EXPECT_EQ(single_result[0], "application/json");
  794. // Wildcard types
  795. std::vector<std::string> wildcard_result;
  796. EXPECT_TRUE(detail::parse_accept_header(
  797. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  798. EXPECT_EQ(wildcard_result.size(), 3U);
  799. EXPECT_EQ(wildcard_result[0], "application/json");
  800. EXPECT_EQ(wildcard_result[1], "text/*");
  801. EXPECT_EQ(wildcard_result[2], "*/*");
  802. }
  803. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  804. // Common browser Accept header
  805. std::vector<std::string> browser_result;
  806. EXPECT_TRUE(
  807. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  808. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  809. browser_result));
  810. EXPECT_EQ(browser_result.size(), 6U);
  811. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  815. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  816. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  817. // API client header
  818. std::vector<std::string> api_result;
  819. EXPECT_TRUE(detail::parse_accept_header(
  820. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  821. api_result));
  822. EXPECT_EQ(api_result.size(), 3U);
  823. EXPECT_EQ(api_result[0], "application/json");
  824. EXPECT_EQ(api_result[1], "application/xml");
  825. EXPECT_EQ(api_result[2], "text/plain");
  826. }
  827. TEST(ParseAcceptHeaderTest, SpecialCases) {
  828. // Quality value with 3 decimal places
  829. std::vector<std::string> decimal_result;
  830. EXPECT_TRUE(detail::parse_accept_header(
  831. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  832. EXPECT_EQ(decimal_result.size(), 2U);
  833. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  834. EXPECT_EQ(decimal_result[1], "text/html");
  835. // Zero quality (should still be included but with lowest priority)
  836. std::vector<std::string> zero_q_result;
  837. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  838. zero_q_result));
  839. EXPECT_EQ(zero_q_result.size(), 2U);
  840. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  841. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  842. // No spaces around commas
  843. std::vector<std::string> no_space_result;
  844. EXPECT_TRUE(detail::parse_accept_header(
  845. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  846. no_space_result));
  847. EXPECT_EQ(no_space_result.size(), 3U);
  848. EXPECT_EQ(no_space_result[0], "text/html");
  849. EXPECT_EQ(no_space_result[1], "application/json");
  850. EXPECT_EQ(no_space_result[2], "text/plain");
  851. }
  852. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  853. // Quality values always use '.' as the decimal separator, so parsing must
  854. // not depend on the process locale. An embedding application may have
  855. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  856. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  857. std::string saved = cur ? cur : "C";
  858. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  859. "fr_FR.UTF-8"};
  860. bool switched = false;
  861. for (const auto loc : comma_locales) {
  862. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  863. std::localeconv()->decimal_point[0] == ',') {
  864. switched = true;
  865. break;
  866. }
  867. }
  868. if (!switched) {
  869. std::setlocale(LC_NUMERIC, saved.c_str());
  870. GTEST_SKIP() << "no comma-decimal locale available on this host";
  871. }
  872. // The higher-weighted type appears later in the list, so a correct parse
  873. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  874. // sensitive parse reads both weights as 0 and leaves the original order.
  875. std::vector<std::string> result;
  876. EXPECT_TRUE(detail::parse_accept_header(
  877. "application/json;q=0.1,text/html;q=0.9", result));
  878. ASSERT_EQ(result.size(), 2U);
  879. EXPECT_EQ(result[0], "text/html");
  880. EXPECT_EQ(result[1], "application/json");
  881. std::setlocale(LC_NUMERIC, saved.c_str());
  882. }
  883. TEST(ParseAcceptHeaderTest, InvalidCases) {
  884. std::vector<std::string> result;
  885. // Invalid quality value (> 1.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  888. // Invalid quality value (< 0.0)
  889. EXPECT_FALSE(
  890. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  891. // Invalid quality value (not a number)
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=invalid,application/json", result));
  894. // A valid numeric prefix does not make the entire quality value valid.
  895. EXPECT_FALSE(detail::parse_accept_header(
  896. "text/html;q=0.5junk,application/json", result));
  897. // Empty quality value
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("text/html;q=,application/json", result));
  900. // Invalid media type format (no slash and not wildcard)
  901. EXPECT_FALSE(
  902. detail::parse_accept_header("invalidtype,application/json", result));
  903. // Valid cases should still work
  904. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*/*");
  907. EXPECT_TRUE(detail::parse_accept_header("*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "*");
  910. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  911. EXPECT_EQ(result.size(), 1U);
  912. EXPECT_EQ(result[0], "text/*");
  913. }
  914. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  915. // elements, so a leading, trailing or doubled comma is a legal Accept value
  916. // and must not be answered with 400 Bad Request.
  917. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  918. struct {
  919. const char *value;
  920. std::vector<std::string> expected;
  921. } cases[] = {
  922. {",application/json", {"application/json"}},
  923. {"text/html,", {"text/html"}},
  924. {"text/html,,*/*", {"text/html", "*/*"}},
  925. // An empty element may be spelled with whitespace in it
  926. {"text/html, , application/json", {"text/html", "application/json"}},
  927. // Nothing but empty elements is an empty list, which means the same
  928. // thing as no Accept header at all
  929. {",,,", {}},
  930. // Quality values still apply across ignored empty elements
  931. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  932. };
  933. for (const auto &c : cases) {
  934. std::vector<std::string> result;
  935. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  936. << "value: " << c.value;
  937. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  938. }
  939. // An invalid entry is still rejected when empty elements surround it
  940. std::vector<std::string> result;
  941. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  942. }
  943. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  944. // or ';' inside one does not end the list element or the parameter. Section
  945. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  946. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  947. struct {
  948. const char *value;
  949. std::vector<std::string> expected;
  950. } cases[] = {
  951. {"text/html;profile=\"a,b\",application/json",
  952. {"text/html", "application/json"}},
  953. // A "q=" inside a quoted value is not the weight
  954. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  955. {"text/html", "application/json"}},
  956. // The weight after a quoted value still applies
  957. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  958. {"application/json", "text/html"}},
  959. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  960. {"application/json", "text/html"}},
  961. {"text/html;profile=\"a\\\"b\",application/json",
  962. {"text/html", "application/json"}},
  963. // An escaped backslash does not escape the '"' after it
  964. {"text/html;profile=\"a\\\\\",application/json",
  965. {"text/html", "application/json"}},
  966. };
  967. for (const auto &c : cases) {
  968. std::vector<std::string> result;
  969. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  970. << "value: " << c.value;
  971. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  972. }
  973. }
  974. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  975. Server svr;
  976. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  977. EXPECT_EQ(req.accept_content_types.size(), 3U);
  978. EXPECT_EQ(req.accept_content_types[0], "application/json");
  979. EXPECT_EQ(req.accept_content_types[1], "text/html");
  980. EXPECT_EQ(req.accept_content_types[2], "*/*");
  981. res.set_content("ok", "text/plain");
  982. });
  983. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  984. EXPECT_TRUE(false);
  985. res.set_content("bad request", "text/plain");
  986. });
  987. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. listen_thread.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. Client cli("localhost", PORT);
  995. {
  996. auto res = cli.Get(
  997. "/accept_ok",
  998. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. }
  1002. {
  1003. auto res = cli.Get("/accept_bad_request",
  1004. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1006. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1007. }
  1008. }
  1009. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1010. Server svr;
  1011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1012. res.set_content("ok", "text/plain");
  1013. });
  1014. std::atomic<int> start_count{0};
  1015. std::atomic<bool> running_when_called{false};
  1016. svr.set_start_handler([&]() {
  1017. running_when_called = svr.is_running();
  1018. start_count++;
  1019. });
  1020. auto port = svr.bind_to_any_port(HOST);
  1021. std::thread t([&]() { svr.listen_after_bind(); });
  1022. auto se = detail::scope_exit([&] {
  1023. svr.stop();
  1024. t.join();
  1025. ASSERT_FALSE(svr.is_running());
  1026. });
  1027. svr.wait_until_ready();
  1028. // A successful request proves the accept loop is running, which the start
  1029. // handler precedes; so by now the handler must have run exactly once.
  1030. Client cli(HOST, port);
  1031. cli.set_connection_timeout(std::chrono::seconds(5));
  1032. auto res = cli.Get("/");
  1033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1034. EXPECT_EQ(StatusCode::OK_200, res->status);
  1035. EXPECT_EQ(1, start_count.load());
  1036. EXPECT_TRUE(running_when_called.load());
  1037. }
  1038. TEST(DivideTest, DivideStringTests) {
  1039. auto divide = [](const std::string &str, char d) {
  1040. std::string lhs;
  1041. std::string rhs;
  1042. detail::divide(str, d,
  1043. [&](const char *lhs_data, std::size_t lhs_size,
  1044. const char *rhs_data, std::size_t rhs_size) {
  1045. lhs.assign(lhs_data, lhs_size);
  1046. rhs.assign(rhs_data, rhs_size);
  1047. });
  1048. return std::make_pair(std::move(lhs), std::move(rhs));
  1049. };
  1050. {
  1051. const auto res = divide("", '=');
  1052. EXPECT_EQ(res.first, "");
  1053. EXPECT_EQ(res.second, "");
  1054. }
  1055. {
  1056. const auto res = divide("=", '=');
  1057. EXPECT_EQ(res.first, "");
  1058. EXPECT_EQ(res.second, "");
  1059. }
  1060. {
  1061. const auto res = divide(" ", '=');
  1062. EXPECT_EQ(res.first, " ");
  1063. EXPECT_EQ(res.second, "");
  1064. }
  1065. {
  1066. const auto res = divide("a", '=');
  1067. EXPECT_EQ(res.first, "a");
  1068. EXPECT_EQ(res.second, "");
  1069. }
  1070. {
  1071. const auto res = divide("a=", '=');
  1072. EXPECT_EQ(res.first, "a");
  1073. EXPECT_EQ(res.second, "");
  1074. }
  1075. {
  1076. const auto res = divide("=b", '=');
  1077. EXPECT_EQ(res.first, "");
  1078. EXPECT_EQ(res.second, "b");
  1079. }
  1080. {
  1081. const auto res = divide("a=b", '=');
  1082. EXPECT_EQ(res.first, "a");
  1083. EXPECT_EQ(res.second, "b");
  1084. }
  1085. {
  1086. const auto res = divide("a=b=", '=');
  1087. EXPECT_EQ(res.first, "a");
  1088. EXPECT_EQ(res.second, "b=");
  1089. }
  1090. {
  1091. const auto res = divide("a=b=c", '=');
  1092. EXPECT_EQ(res.first, "a");
  1093. EXPECT_EQ(res.second, "b=c");
  1094. }
  1095. }
  1096. TEST(SplitTest, ParseQueryString) {
  1097. string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1100. [&](const char *b, const char *e) {
  1101. string key, val;
  1102. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1103. if (key.empty()) {
  1104. key.assign(b2, e2);
  1105. } else {
  1106. val.assign(b2, e2);
  1107. }
  1108. });
  1109. dic.emplace(key, val);
  1110. });
  1111. EXPECT_EQ("val1", dic.find("key1")->second);
  1112. EXPECT_EQ("val2", dic.find("key2")->second);
  1113. EXPECT_EQ("val3", dic.find("key3")->second);
  1114. }
  1115. TEST(SplitTest, ParseInvalidQueryTests) {
  1116. {
  1117. string s = " ";
  1118. Params dict;
  1119. detail::parse_query_text(s, dict);
  1120. EXPECT_TRUE(dict.empty());
  1121. }
  1122. {
  1123. string s = " = =";
  1124. Params dict;
  1125. detail::parse_query_text(s, dict);
  1126. EXPECT_TRUE(dict.empty());
  1127. }
  1128. }
  1129. TEST(ParseQueryTest, ParseQueryString) {
  1130. {
  1131. std::string s = "key1=val1&key2=val2&key3=val3";
  1132. Params dic;
  1133. detail::parse_query_text(s, dic);
  1134. EXPECT_EQ("val1", dic.find("key1")->second);
  1135. EXPECT_EQ("val2", dic.find("key2")->second);
  1136. EXPECT_EQ("val3", dic.find("key3")->second);
  1137. }
  1138. {
  1139. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1140. Params dic;
  1141. detail::parse_query_text(s, dic);
  1142. EXPECT_EQ("", dic.find("key1")->second);
  1143. EXPECT_EQ("val1", dic.find("key2")->second);
  1144. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1145. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1146. }
  1147. }
  1148. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1149. Params dic;
  1150. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1151. dic.emplace("key1", "val1");
  1152. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1153. dic.emplace("key2", "val2");
  1154. dic.emplace("key3", "val3");
  1155. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1156. }
  1157. // Joins every entry of a Headers or Params into "key=value " so a whole
  1158. // traversal can be compared in one assertion. Both are instantiations of the
  1159. // same insertion-ordered container, so one helper serves both.
  1160. template <typename Map> static std::string entries_to_string(const Map &m) {
  1161. std::string s;
  1162. for (const auto &entry : m) {
  1163. s += entry.first + "=" + entry.second + " ";
  1164. }
  1165. return s;
  1166. }
  1167. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1168. // Params used to be a std::multimap, which sorted by name and handed the
  1169. // caller's query back alphabetised. A client signing its query string could
  1170. // not reproduce the order it asked for.
  1171. Params dic;
  1172. dic.emplace("zulu", "1");
  1173. dic.emplace("alpha", "2");
  1174. dic.emplace("mike", "3");
  1175. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1176. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1177. }
  1178. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1179. Params dic;
  1180. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1181. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1182. }
  1183. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1184. Request req;
  1185. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1186. req.params);
  1187. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1188. EXPECT_EQ("first", req.get_param_value("tag"));
  1189. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1190. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1191. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1192. EXPECT_EQ("", req.get_param_value("tag", 3));
  1193. }
  1194. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1195. // Params shares its container with Headers, which matches field names
  1196. // case-insensitively. Parameter names must not pick that up.
  1197. Params dic;
  1198. dic.emplace("Key", "upper");
  1199. dic.emplace("key", "lower");
  1200. EXPECT_EQ(2U, dic.size());
  1201. EXPECT_EQ(1U, dic.count("Key"));
  1202. EXPECT_EQ(1U, dic.count("key"));
  1203. EXPECT_EQ("upper", dic.find("Key")->second);
  1204. EXPECT_EQ("lower", dic.find("key")->second);
  1205. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1206. }
  1207. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1208. Server svr;
  1209. std::string order;
  1210. svr.Get("/order", [&](const Request &req, Response &res) {
  1211. order = entries_to_string(req.params);
  1212. res.set_content("ok", "text/plain");
  1213. });
  1214. auto port = svr.bind_to_any_port(HOST);
  1215. thread t = thread([&] { svr.listen_after_bind(); });
  1216. auto se = detail::scope_exit([&] {
  1217. svr.stop();
  1218. t.join();
  1219. ASSERT_FALSE(svr.is_running());
  1220. });
  1221. svr.wait_until_ready();
  1222. Client cli(HOST, port);
  1223. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1226. }
  1227. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1228. Server svr;
  1229. std::string field_order, file_order;
  1230. svr.Post("/order", [&](const Request &req, Response &res) {
  1231. for (const auto &field : req.form.fields) {
  1232. field_order += field.first + "=" + field.second.content + " ";
  1233. }
  1234. for (const auto &file : req.form.files) {
  1235. file_order += file.first + "=" + file.second.filename + " ";
  1236. }
  1237. res.set_content("ok", "text/plain");
  1238. });
  1239. auto port = svr.bind_to_any_port(HOST);
  1240. thread t = thread([&] { svr.listen_after_bind(); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. t.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. UploadFormDataItems items = {
  1248. {"zulu", "1", "", ""},
  1249. {"alpha", "2", "", ""},
  1250. {"mike", "3", "", ""},
  1251. {"zebra", "z", "z.txt", "text/plain"},
  1252. {"apple", "a", "a.txt", "text/plain"},
  1253. };
  1254. Client cli(HOST, port);
  1255. auto res = cli.Post("/order", items);
  1256. ASSERT_TRUE(res);
  1257. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1258. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1259. }
  1260. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1261. Server svr;
  1262. std::vector<std::string> values;
  1263. std::string first, second, out_of_range, order;
  1264. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1265. values = req.form.get_fields("tag");
  1266. first = req.form.get_field("tag", 0);
  1267. second = req.form.get_field("tag", 1);
  1268. out_of_range = req.form.get_field("tag", 2);
  1269. for (const auto &field : req.form.fields) {
  1270. order += field.first + "=" + field.second.content + " ";
  1271. }
  1272. res.set_content("ok", "text/plain");
  1273. });
  1274. auto port = svr.bind_to_any_port(HOST);
  1275. thread t = thread([&] { svr.listen_after_bind(); });
  1276. auto se = detail::scope_exit([&] {
  1277. svr.stop();
  1278. t.join();
  1279. ASSERT_FALSE(svr.is_running());
  1280. });
  1281. svr.wait_until_ready();
  1282. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1283. // not adjacent in the container.
  1284. UploadFormDataItems items = {
  1285. {"tag", "first", "", ""},
  1286. {"other", "x", "", ""},
  1287. {"tag", "second", "", ""},
  1288. };
  1289. Client cli(HOST, port);
  1290. auto res = cli.Post("/repeated", items);
  1291. ASSERT_TRUE(res);
  1292. ASSERT_EQ(2U, values.size());
  1293. EXPECT_EQ("first", values[0]);
  1294. EXPECT_EQ("second", values[1]);
  1295. EXPECT_EQ("first", first);
  1296. EXPECT_EQ("second", second);
  1297. // std::multimap already kept entries sharing a name in insertion order, so
  1298. // everything above passes without this change too. The whole traversal is
  1299. // what tells the two apart: sorting by name would hoist "other" to the front
  1300. // and the two "tag" parts would end up adjacent.
  1301. EXPECT_EQ("tag=first other=x tag=second ", order);
  1302. // Advancing past the last entry of a name used to run off the container;
  1303. // the container's saturating increment makes it return the default instead.
  1304. EXPECT_EQ("", out_of_range);
  1305. }
  1306. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1307. // Server::read_content() keeps a FormFields::iterator alive across the
  1308. // content callbacks that fill the part it points at. The container is
  1309. // vector-backed, so a later emplace can reallocate and invalidate an older
  1310. // iterator; 64 parts grow the vector through seven reallocations, which
  1311. // checks that every part's content still lands in its own entry.
  1312. const size_t part_count = 64;
  1313. // One formula for both the parts sent and the values expected back, so the
  1314. // two cannot drift apart.
  1315. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1316. auto content_of = [](size_t i) {
  1317. return std::string(64, static_cast<char>('a' + (i % 26)));
  1318. };
  1319. Server svr;
  1320. std::vector<std::pair<std::string, std::string>> received;
  1321. svr.Post("/many", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. received.emplace_back(field.first, field.second.content);
  1324. }
  1325. res.set_content("ok", "text/plain");
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. thread t = thread([&] { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. UploadFormDataItems items;
  1336. for (size_t i = 0; i < part_count; i++) {
  1337. items.push_back({name_of(i), content_of(i), "", ""});
  1338. }
  1339. Client cli(HOST, port);
  1340. auto res = cli.Post("/many", items);
  1341. ASSERT_TRUE(res);
  1342. ASSERT_EQ(part_count, received.size());
  1343. for (size_t i = 0; i < part_count; i++) {
  1344. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1345. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1346. }
  1347. }
  1348. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1349. string content_type = "multipart/form-data; boundary=something";
  1350. string boundary;
  1351. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1352. EXPECT_TRUE(ret);
  1353. EXPECT_EQ(boundary, "something");
  1354. }
  1355. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1356. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1357. string boundary;
  1358. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1359. EXPECT_TRUE(ret);
  1360. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1361. }
  1362. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1363. string content_type =
  1364. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1365. string boundary;
  1366. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1367. EXPECT_TRUE(ret);
  1368. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1369. }
  1370. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1373. string boundary;
  1374. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1375. EXPECT_TRUE(ret);
  1376. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1379. const string boundary(70, 'a');
  1380. string content_type = "multipart/form-data; boundary=" + boundary;
  1381. string parsed;
  1382. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1383. EXPECT_TRUE(ret);
  1384. EXPECT_EQ(parsed, boundary);
  1385. }
  1386. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1387. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1388. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1389. string parsed;
  1390. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1391. EXPECT_FALSE(ret);
  1392. }
  1393. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1394. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1395. // is 72 characters on the wire and still valid.
  1396. const string boundary(70, 'a');
  1397. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1398. string parsed;
  1399. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1400. EXPECT_EQ(parsed, boundary);
  1401. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1402. parsed.clear();
  1403. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1404. }
  1405. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1406. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1407. // The parameter parser must not treat that '=' as the key/value separator.
  1408. string content_type =
  1409. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1410. "charset=UTF-8";
  1411. string parsed;
  1412. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1413. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1414. }
  1415. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1416. // A ';' inside the quoted-string is part of the value, not a parameter
  1417. // separator, so it must not truncate the boundary.
  1418. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1419. string parsed;
  1420. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1421. EXPECT_EQ(parsed, "a;b");
  1422. }
  1423. TEST(ParseDispositionParamsTest, QuotedValues) {
  1424. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1425. // ';' and '=' are ordinary characters inside one.
  1426. struct {
  1427. const char *value;
  1428. std::vector<std::pair<const char *, const char *>> expected;
  1429. } cases[] = {
  1430. {"name=\"file1\"; filename=\"a.txt\"",
  1431. {{"name", "file1"}, {"filename", "a.txt"}}},
  1432. // Whitespace around '=' and ';' is still trimmed
  1433. {"name=\"file2\" ;filename = \"a.html\"",
  1434. {{"name", "file2"}, {"filename", "a.html"}}},
  1435. // '=' inside the value used to leave only the text after the last one
  1436. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1437. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1438. {"name=\"x=y\"", {{"name", "x=y"}}},
  1439. // ';' inside the value used to truncate the pair and leave a bogus one
  1440. {"name=\"file3\"; filename=\"a;b.txt\"",
  1441. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1442. // An unquoted value keeps working, and so does filename*
  1443. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1444. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1445. // A parameter with no key is dropped rather than turned into one whose
  1446. // key is the value
  1447. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1448. };
  1449. for (const auto &c : cases) {
  1450. Params params;
  1451. detail::parse_disposition_params(c.value, params);
  1452. for (const auto &kv : c.expected) {
  1453. auto it = params.find(kv.first);
  1454. ASSERT_NE(it, params.end())
  1455. << "value: " << c.value << ", key: " << kv.first;
  1456. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1457. }
  1458. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1459. }
  1460. }
  1461. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1462. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1463. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1464. Server svr;
  1465. std::string field_value, file_name, file_filename;
  1466. bool has_field = false, has_file = false;
  1467. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1468. has_field = req.form.has_field("x=y");
  1469. field_value = req.form.get_field("x=y");
  1470. has_file = req.form.has_file("file1");
  1471. const auto &file = req.form.get_file("file1");
  1472. file_name = file.name;
  1473. file_filename = file.filename;
  1474. res.set_content("ok", "text/plain");
  1475. });
  1476. auto port = svr.bind_to_any_port(HOST);
  1477. thread t = thread([&] { svr.listen_after_bind(); });
  1478. auto se = detail::scope_exit([&] {
  1479. svr.stop();
  1480. t.join();
  1481. ASSERT_FALSE(svr.is_running());
  1482. });
  1483. svr.wait_until_ready();
  1484. UploadFormDataItems items = {
  1485. {"x=y", "field-value", "", ""},
  1486. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1487. };
  1488. Client cli(HOST, port);
  1489. auto res = cli.Post("/quoted", items);
  1490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1491. ASSERT_EQ(StatusCode::OK_200, res->status);
  1492. EXPECT_TRUE(has_field);
  1493. EXPECT_EQ("field-value", field_value);
  1494. EXPECT_TRUE(has_file);
  1495. EXPECT_EQ("file1", file_name);
  1496. EXPECT_EQ("a;b=report.pdf", file_filename);
  1497. }
  1498. TEST(GetHeaderValueTest, DefaultValue) {
  1499. Headers headers = {{"Dummy", "Dummy"}};
  1500. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1501. EXPECT_STREQ("text/plain", val);
  1502. }
  1503. TEST(GetHeaderValueTest, DefaultValueInt) {
  1504. Headers headers = {{"Dummy", "Dummy"}};
  1505. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1506. EXPECT_EQ(100ull, val);
  1507. }
  1508. TEST(GetHeaderValueTest, RegularValue) {
  1509. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1510. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1511. EXPECT_STREQ("text/html", val);
  1512. }
  1513. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1514. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1515. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1516. EXPECT_STREQ("text/html", val);
  1517. }
  1518. TEST(GetHeaderValueTest, SetContent) {
  1519. Response res;
  1520. res.set_content("html", "text/html");
  1521. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1522. res.set_content("text", "text/plain");
  1523. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1524. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1525. }
  1526. TEST(GetHeaderValueTest, RegularValueInt) {
  1527. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1528. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1529. EXPECT_EQ(100ull, val);
  1530. }
  1531. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1532. Headers headers = {{"Content-Length", "x"}};
  1533. auto is_invalid_value = false;
  1534. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1535. is_invalid_value);
  1536. EXPECT_EQ(0ull, val);
  1537. EXPECT_TRUE(is_invalid_value);
  1538. }
  1539. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1540. // An all-digit value that overflows size_t must be reported as invalid, not
  1541. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1542. // a large length to a small one on 32-bit builds, leaving the framing length
  1543. // wrong while is_invalid_value stayed false.
  1544. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1545. auto is_invalid_value = false;
  1546. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1547. is_invalid_value);
  1548. EXPECT_TRUE(is_invalid_value);
  1549. // A well-formed length is unaffected.
  1550. Headers ok = {{"Content-Length", "1234"}};
  1551. is_invalid_value = false;
  1552. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1553. is_invalid_value);
  1554. EXPECT_EQ(1234ull, val);
  1555. EXPECT_FALSE(is_invalid_value);
  1556. }
  1557. TEST(GetHeaderValueTest, Range) {
  1558. {
  1559. Headers headers = {make_range_header({{1, -1}})};
  1560. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1561. EXPECT_STREQ("bytes=1-", val);
  1562. }
  1563. {
  1564. Headers headers = {make_range_header({{-1, 1}})};
  1565. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1566. EXPECT_STREQ("bytes=-1", val);
  1567. }
  1568. {
  1569. Headers headers = {make_range_header({{1, 10}})};
  1570. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1571. EXPECT_STREQ("bytes=1-10", val);
  1572. }
  1573. {
  1574. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1575. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1576. EXPECT_STREQ("bytes=1-10, 100-", val);
  1577. }
  1578. {
  1579. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1580. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1581. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1582. }
  1583. {
  1584. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1585. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1586. EXPECT_STREQ("bytes=0-0, -1", val);
  1587. }
  1588. }
  1589. TEST(BearerTokenAuthTest, SchemeValidation) {
  1590. // A value shorter than "Bearer " must not throw from the fixed-length
  1591. // substr, and a non-Bearer scheme must not be reported as a token.
  1592. struct {
  1593. const char *value;
  1594. const char *expected;
  1595. } cases[] = {
  1596. {"x", ""},
  1597. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1598. {"Bearer abc123", "abc123"},
  1599. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1600. };
  1601. for (const auto &c : cases) {
  1602. Request req;
  1603. req.set_header("Authorization", c.value);
  1604. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1605. }
  1606. }
  1607. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1608. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1609. // to depend on the standard library (libstdc++ handed back duplicates in
  1610. // reverse insertion order, libc++ in insertion order).
  1611. Request req;
  1612. req.set_header("Accept-Encoding", "gzip");
  1613. req.set_header("Accept-Encoding", "deflate");
  1614. req.set_header("Accept-Encoding", "br");
  1615. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1616. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1617. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1618. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1619. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1620. }
  1621. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1622. Request req;
  1623. req.set_header("X-Test", "only");
  1624. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1625. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1626. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1627. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1628. }
  1629. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1630. Request req;
  1631. req.set_header("X-First", "1");
  1632. req.set_header("X-Test", "2");
  1633. req.params.emplace("first", "1");
  1634. req.params.emplace("test", "2");
  1635. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1636. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1637. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1638. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1639. // The second one is negative when read as a signed value
  1640. const auto max_id = (std::numeric_limits<size_t>::max)();
  1641. for (auto id : {max_id / 2, max_id}) {
  1642. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1643. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1644. EXPECT_EQ("", req.get_param_value("test", id));
  1645. EXPECT_EQ("", req.form.get_field("test", id));
  1646. EXPECT_EQ("", req.form.get_file("test", id).content);
  1647. }
  1648. }
  1649. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1650. Headers headers;
  1651. headers.emplace("Host", "example.com");
  1652. headers.emplace("Accept-Encoding", "gzip");
  1653. headers.emplace("User-Agent", "test");
  1654. headers.emplace("Accept-Encoding", "deflate");
  1655. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1656. "Accept-Encoding=deflate ",
  1657. entries_to_string(headers));
  1658. }
  1659. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1660. Headers headers = {{"Content-Type", "text/html"},
  1661. {"CONTENT-TYPE", "text/xml"}};
  1662. EXPECT_EQ(2U, headers.count("content-type"));
  1663. auto it = headers.find("content-type");
  1664. ASSERT_TRUE(it != headers.end());
  1665. EXPECT_EQ("text/html", it->second);
  1666. }
  1667. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1668. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1669. // drop only those fields and leave everything positioned between them.
  1670. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1671. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1672. auto rng = headers.equal_range("a");
  1673. headers.erase(rng.first, rng.second);
  1674. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1675. }
  1676. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1677. Headers headers = {
  1678. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1679. EXPECT_EQ(3U, headers.erase("A"));
  1680. EXPECT_EQ(0U, headers.count("A"));
  1681. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1682. }
  1683. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1684. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1685. headers.emplace_front("Host", "example.com");
  1686. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1687. entries_to_string(headers));
  1688. }
  1689. TEST(ParseHeaderValueTest, Range) {
  1690. {
  1691. Ranges ranges;
  1692. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1693. EXPECT_TRUE(ret);
  1694. EXPECT_EQ(1u, ranges.size());
  1695. EXPECT_EQ(1u, ranges[0].first);
  1696. EXPECT_EQ(-1, ranges[0].second);
  1697. }
  1698. {
  1699. Ranges ranges;
  1700. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1701. EXPECT_TRUE(ret);
  1702. EXPECT_EQ(1u, ranges.size());
  1703. EXPECT_EQ(-1, ranges[0].first);
  1704. EXPECT_EQ(1u, ranges[0].second);
  1705. }
  1706. {
  1707. Ranges ranges;
  1708. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1709. EXPECT_TRUE(ret);
  1710. EXPECT_EQ(1u, ranges.size());
  1711. EXPECT_EQ(1u, ranges[0].first);
  1712. EXPECT_EQ(10u, ranges[0].second);
  1713. }
  1714. {
  1715. Ranges ranges;
  1716. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1717. EXPECT_FALSE(ret);
  1718. }
  1719. {
  1720. Ranges ranges;
  1721. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1722. EXPECT_TRUE(ret);
  1723. EXPECT_EQ(2u, ranges.size());
  1724. EXPECT_EQ(1u, ranges[0].first);
  1725. EXPECT_EQ(10u, ranges[0].second);
  1726. EXPECT_EQ(100u, ranges[1].first);
  1727. EXPECT_EQ(-1, ranges[1].second);
  1728. }
  1729. {
  1730. Ranges ranges;
  1731. auto ret =
  1732. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1733. EXPECT_TRUE(ret);
  1734. EXPECT_EQ(3u, ranges.size());
  1735. EXPECT_EQ(1u, ranges[0].first);
  1736. EXPECT_EQ(10u, ranges[0].second);
  1737. EXPECT_EQ(100u, ranges[1].first);
  1738. EXPECT_EQ(200u, ranges[1].second);
  1739. EXPECT_EQ(300u, ranges[2].first);
  1740. EXPECT_EQ(400u, ranges[2].second);
  1741. }
  1742. {
  1743. Ranges ranges;
  1744. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1745. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1746. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1747. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1748. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1749. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1750. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1751. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1752. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1753. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1754. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1755. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1756. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1757. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1758. EXPECT_FALSE(
  1759. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1760. EXPECT_TRUE(ranges.empty());
  1761. }
  1762. {
  1763. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1764. // remainder of the representation, so it stays accepted.
  1765. Ranges ranges;
  1766. auto ret =
  1767. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1768. EXPECT_TRUE(ret);
  1769. ASSERT_EQ(1u, ranges.size());
  1770. EXPECT_EQ(0, ranges[0].first);
  1771. EXPECT_EQ(-1, ranges[0].second);
  1772. }
  1773. // RFC 9110 14.1: range unit names are case-insensitive.
  1774. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1775. Ranges ranges;
  1776. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1777. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1778. }
  1779. }
  1780. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1781. Request req;
  1782. req.set_header("Accept-Encoding", "gzip");
  1783. Response res;
  1784. res.set_header("Content-Type", "text/plain");
  1785. auto ret = detail::encoding_type(req, res);
  1786. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1793. Request req;
  1794. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1795. Response res;
  1796. res.set_header("Content-Type", "text/plain");
  1797. auto ret = detail::encoding_type(req, res);
  1798. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1800. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1801. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1802. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1803. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1804. #else
  1805. EXPECT_TRUE(ret == detail::EncodingType::None);
  1806. #endif
  1807. }
  1808. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1809. Request req;
  1810. req.set_header("Accept-Encoding",
  1811. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1812. Response res;
  1813. res.set_header("Content-Type", "text/plain");
  1814. auto ret = detail::encoding_type(req, res);
  1815. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1816. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1817. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1818. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1819. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1820. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1821. #else
  1822. EXPECT_TRUE(ret == detail::EncodingType::None);
  1823. #endif
  1824. }
  1825. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1826. // All supported encodings rejected with q=0 should return None
  1827. Request req;
  1828. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1829. Response res;
  1830. res.set_header("Content-Type", "text/plain");
  1831. auto ret = detail::encoding_type(req, res);
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. }
  1834. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1835. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1836. Request req;
  1837. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1838. Response res;
  1839. res.set_header("Content-Type", "text/plain");
  1840. auto ret = detail::encoding_type(req, res);
  1841. EXPECT_TRUE(ret == detail::EncodingType::None);
  1842. }
  1843. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1844. Request req;
  1845. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1846. Response res;
  1847. res.set_header("Content-Type", "text/plain");
  1848. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1849. }
  1850. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1851. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1852. Request req;
  1853. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1854. Response res;
  1855. res.set_header("Content-Type", "text/plain");
  1856. auto ret = detail::encoding_type(req, res);
  1857. EXPECT_TRUE(ret == detail::EncodingType::None);
  1858. }
  1859. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1860. // RFC 7231: Accept-Encoding values are case-insensitive
  1861. Request req;
  1862. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1863. Response res;
  1864. res.set_header("Content-Type", "text/plain");
  1865. auto ret = detail::encoding_type(req, res);
  1866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1867. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1868. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1869. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1870. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1871. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1872. #else
  1873. EXPECT_TRUE(ret == detail::EncodingType::None);
  1874. #endif
  1875. }
  1876. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1877. // q value should determine priority, not hardcoded order
  1878. Request req;
  1879. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1880. Response res;
  1881. res.set_header("Content-Type", "text/plain");
  1882. auto ret = detail::encoding_type(req, res);
  1883. // gzip has highest q=1.0, so it should be selected even though
  1884. // br and zstd are also supported
  1885. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1886. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1887. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1888. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1889. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #else
  1892. EXPECT_TRUE(ret == detail::EncodingType::None);
  1893. #endif
  1894. }
  1895. TEST(BufferStreamTest, read) {
  1896. detail::BufferStream strm1;
  1897. Stream &strm = strm1;
  1898. EXPECT_EQ(5, strm.write("hello"));
  1899. char buf[512];
  1900. EXPECT_EQ(2, strm.read(buf, 2));
  1901. EXPECT_EQ('h', buf[0]);
  1902. EXPECT_EQ('e', buf[1]);
  1903. EXPECT_EQ(2, strm.read(buf, 2));
  1904. EXPECT_EQ('l', buf[0]);
  1905. EXPECT_EQ('l', buf[1]);
  1906. EXPECT_EQ(1, strm.read(buf, 1));
  1907. EXPECT_EQ('o', buf[0]);
  1908. EXPECT_EQ(0, strm.read(buf, 1));
  1909. }
  1910. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1911. auto host = "www.httpwatch.com";
  1912. auto ip = hosted_at(host);
  1913. EXPECT_EQ("23.96.13.243", ip);
  1914. std::vector<std::string> addrs;
  1915. hosted_at(host, addrs);
  1916. EXPECT_EQ(1u, addrs.size());
  1917. }
  1918. #if 0 // It depends on each test environment...
  1919. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1920. auto host = "www.youtube.com";
  1921. std::vector<std::string> addrs;
  1922. hosted_at(host, addrs);
  1923. EXPECT_EQ(20u, addrs.size());
  1924. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1925. EXPECT_TRUE(it != addrs.end());
  1926. }
  1927. #endif
  1928. class ChunkedEncodingTest : public ::testing::Test {
  1929. protected:
  1930. ChunkedEncodingTest()
  1931. : cli_(HOST, PORT)
  1932. #ifdef CPPHTTPLIB_SSL_ENABLED
  1933. ,
  1934. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1935. #endif
  1936. {
  1937. cli_.set_connection_timeout(2);
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. cli_.enable_server_certificate_verification(false);
  1940. #endif
  1941. }
  1942. virtual void SetUp() {
  1943. read_file("./image.jpg", image_data_);
  1944. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1945. res.set_content("Hello World!", "text/plain");
  1946. });
  1947. svr_.Get(
  1948. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1949. res.set_chunked_content_provider(
  1950. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1951. size_t remaining = image_data_.size() - offset;
  1952. if (remaining == 0) {
  1953. sink.done();
  1954. } else {
  1955. constexpr size_t CHUNK_SIZE = 1024;
  1956. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1957. sink.write(&image_data_[offset], send_size);
  1958. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1959. }
  1960. return true;
  1961. });
  1962. });
  1963. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1964. svr_.wait_until_ready();
  1965. }
  1966. virtual void TearDown() {
  1967. svr_.stop();
  1968. if (!request_threads_.empty()) {
  1969. std::this_thread::sleep_for(std::chrono::seconds(1));
  1970. for (auto &t : request_threads_) {
  1971. t.join();
  1972. }
  1973. }
  1974. t_.join();
  1975. }
  1976. #ifdef CPPHTTPLIB_SSL_ENABLED
  1977. SSLClient cli_;
  1978. SSLServer svr_;
  1979. #else
  1980. Client cli_;
  1981. Server svr_;
  1982. #endif
  1983. thread t_;
  1984. std::vector<thread> request_threads_;
  1985. std::string image_data_;
  1986. };
  1987. TEST_F(ChunkedEncodingTest, NormalGet) {
  1988. auto res = cli_.Get("/chunked");
  1989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1990. std::string out;
  1991. read_file("./image.jpg", out);
  1992. EXPECT_EQ(StatusCode::OK_200, res->status);
  1993. EXPECT_EQ(out, res->body);
  1994. }
  1995. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1996. std::string body;
  1997. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1998. body.append(data, data_length);
  1999. return true;
  2000. });
  2001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2002. std::string out;
  2003. read_file("./image.jpg", out);
  2004. EXPECT_EQ(StatusCode::OK_200, res->status);
  2005. EXPECT_EQ(out, body);
  2006. }
  2007. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2008. std::string body;
  2009. auto res = cli_.Get(
  2010. "/chunked",
  2011. [&](const Response &response) {
  2012. EXPECT_EQ(StatusCode::OK_200, response.status);
  2013. return true;
  2014. },
  2015. [&](const char *data, size_t data_length) {
  2016. body.append(data, data_length);
  2017. return true;
  2018. });
  2019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2020. std::string out;
  2021. read_file("./image.jpg", out);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. EXPECT_EQ(out, body);
  2024. }
  2025. TEST(RangeTest, FromHTTPBin_Online) {
  2026. auto host = "httpbingo.org";
  2027. auto path = std::string{"/range/32"};
  2028. #ifdef CPPHTTPLIB_SSL_ENABLED
  2029. auto port = 443;
  2030. SSLClient cli(host, port);
  2031. #else
  2032. auto port = 80;
  2033. Client cli(host, port);
  2034. #endif
  2035. cli.set_connection_timeout(5);
  2036. {
  2037. auto res = cli.Get(path);
  2038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2039. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2040. EXPECT_EQ(StatusCode::OK_200, res->status);
  2041. }
  2042. {
  2043. Headers headers = {make_range_header({{1, -1}})};
  2044. auto res = cli.Get(path, headers);
  2045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2046. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2048. }
  2049. {
  2050. Headers headers = {make_range_header({{1, 10}})};
  2051. auto res = cli.Get(path, headers);
  2052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2053. EXPECT_EQ("bcdefghijk", res->body);
  2054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2055. }
  2056. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2057. // entire resource, while the original httpbin returned 200. Both are
  2058. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2059. {
  2060. Headers headers = {make_range_header({{0, 31}})};
  2061. auto res = cli.Get(path, headers);
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2064. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2065. res->status == StatusCode::PartialContent_206);
  2066. }
  2067. {
  2068. Headers headers = {make_range_header({{0, -1}})};
  2069. auto res = cli.Get(path, headers);
  2070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2071. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2072. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2073. res->status == StatusCode::PartialContent_206);
  2074. }
  2075. // go-httpbin returns 206 with clamped range for over-range requests,
  2076. // while the original httpbin returned 416. Both behaviors are observed
  2077. // in real servers, so we only verify the request succeeds.
  2078. {
  2079. Headers headers = {make_range_header({{0, 32}})};
  2080. auto res = cli.Get(path, headers);
  2081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2082. }
  2083. }
  2084. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2085. auto host = "unresolvableaddress.local";
  2086. auto path = std::string{"/"};
  2087. #ifdef CPPHTTPLIB_SSL_ENABLED
  2088. auto port = 443;
  2089. SSLClient cli(host, port);
  2090. #else
  2091. auto port = 80;
  2092. Client cli(host, port);
  2093. #endif
  2094. cli.set_connection_timeout(1);
  2095. {
  2096. auto res = cli.Get(path);
  2097. ASSERT_FALSE(res);
  2098. }
  2099. std::this_thread::sleep_for(std::chrono::seconds(8));
  2100. }
  2101. #if defined(__linux__) && defined(__GLIBC__) && \
  2102. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2103. // Forward declaration: in split builds split.py strips `inline` and moves the
  2104. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2105. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2106. // against the symbol in both header-only and split builds.
  2107. namespace httplib {
  2108. namespace detail {
  2109. int getaddrinfo_with_timeout(const char *node, const char *service,
  2110. const struct addrinfo *hints,
  2111. struct addrinfo **res, time_t timeout_sec);
  2112. } // namespace detail
  2113. } // namespace httplib
  2114. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2115. //
  2116. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2117. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2118. // gai_suspend() call hits the connection timeout the function calls
  2119. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2120. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2121. // still alive and still references the now-destroyed stack frame.
  2122. //
  2123. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2124. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2125. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2126. // and runs them in a container.
  2127. namespace {
  2128. bool should_run_issue_2431_tests() {
  2129. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2130. return v && *v && std::string(v) != "0";
  2131. }
  2132. std::string unique_unresolvable_host(int n) {
  2133. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2134. // glibc still asks the configured nameserver — which is exactly the path
  2135. // we want to exercise. A unique label per call avoids the resolver cache.
  2136. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2137. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2138. std::to_string(n) + ".invalid";
  2139. }
  2140. } // namespace
  2141. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2142. if (!should_run_issue_2431_tests()) {
  2143. GTEST_SKIP()
  2144. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2145. }
  2146. for (int i = 0; i < 8; ++i) {
  2147. struct addrinfo hints;
  2148. memset(&hints, 0, sizeof(hints));
  2149. hints.ai_family = AF_UNSPEC;
  2150. hints.ai_socktype = SOCK_STREAM;
  2151. auto host = unique_unresolvable_host(i);
  2152. struct addrinfo *result = nullptr;
  2153. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2154. &result, /*timeout_sec=*/1);
  2155. if (rc == 0 && result) { freeaddrinfo(result); }
  2156. }
  2157. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2158. // stack region they still believe holds their gaicb.
  2159. std::this_thread::sleep_for(std::chrono::seconds(3));
  2160. }
  2161. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2162. if (!should_run_issue_2431_tests()) {
  2163. GTEST_SKIP()
  2164. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2165. }
  2166. std::atomic<bool> stop{false};
  2167. std::vector<std::thread> threads;
  2168. for (int t = 0; t < 8; ++t) {
  2169. threads.emplace_back([t, &stop] {
  2170. int i = 0;
  2171. while (!stop.load(std::memory_order_relaxed)) {
  2172. struct addrinfo hints;
  2173. memset(&hints, 0, sizeof(hints));
  2174. hints.ai_family = AF_UNSPEC;
  2175. hints.ai_socktype = SOCK_STREAM;
  2176. auto host = unique_unresolvable_host(t * 100000 + i++);
  2177. struct addrinfo *result = nullptr;
  2178. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2179. &result, /*timeout_sec=*/1);
  2180. if (rc == 0 && result) { freeaddrinfo(result); }
  2181. }
  2182. });
  2183. }
  2184. std::this_thread::sleep_for(std::chrono::seconds(8));
  2185. stop.store(true, std::memory_order_relaxed);
  2186. for (auto &th : threads) {
  2187. th.join();
  2188. }
  2189. std::this_thread::sleep_for(std::chrono::seconds(3));
  2190. }
  2191. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2192. if (!should_run_issue_2431_tests()) {
  2193. GTEST_SKIP()
  2194. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2195. }
  2196. std::atomic<bool> stop{false};
  2197. std::vector<std::thread> threads;
  2198. for (int t = 0; t < 8; ++t) {
  2199. threads.emplace_back([t, &stop] {
  2200. int i = 0;
  2201. while (!stop.load(std::memory_order_relaxed)) {
  2202. auto host = unique_unresolvable_host(t * 100000 + i++);
  2203. Client cli(host, 80);
  2204. cli.set_connection_timeout(1, 0);
  2205. cli.set_read_timeout(1, 0);
  2206. cli.set_write_timeout(1, 0);
  2207. (void)cli.Get("/");
  2208. }
  2209. });
  2210. }
  2211. std::this_thread::sleep_for(std::chrono::seconds(8));
  2212. stop.store(true, std::memory_order_relaxed);
  2213. for (auto &th : threads) {
  2214. th.join();
  2215. }
  2216. std::this_thread::sleep_for(std::chrono::seconds(3));
  2217. }
  2218. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2219. TEST(ConnectionErrorTest, InvalidHost) {
  2220. auto host = "-abcde.com";
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. auto port = 443;
  2223. SSLClient cli(host, port);
  2224. #else
  2225. auto port = 80;
  2226. Client cli(host, port);
  2227. #endif
  2228. cli.set_connection_timeout(std::chrono::seconds(2));
  2229. auto res = cli.Get("/");
  2230. ASSERT_TRUE(!res);
  2231. EXPECT_EQ(Error::Connection, res.error());
  2232. }
  2233. TEST(ConnectionErrorTest, InvalidHost2) {
  2234. auto host = "httpcan.org/";
  2235. #ifdef CPPHTTPLIB_SSL_ENABLED
  2236. SSLClient cli(host);
  2237. #else
  2238. Client cli(host);
  2239. #endif
  2240. cli.set_connection_timeout(std::chrono::seconds(2));
  2241. auto res = cli.Get("/");
  2242. ASSERT_TRUE(!res);
  2243. EXPECT_EQ(Error::Connection, res.error());
  2244. }
  2245. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2246. auto host = "httpcan.org/";
  2247. #ifdef CPPHTTPLIB_SSL_ENABLED
  2248. SSLClient cli(host);
  2249. #else
  2250. Client cli(host);
  2251. #endif
  2252. cli.set_connection_timeout(std::chrono::seconds(2));
  2253. auto res = cli.Get("/");
  2254. ASSERT_TRUE(!res);
  2255. stringstream s;
  2256. s << "error code: " << res.error();
  2257. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2258. }
  2259. TEST(ConnectionErrorTest, InvalidPort) {
  2260. auto host = "localhost";
  2261. auto port = 44380;
  2262. #ifdef CPPHTTPLIB_SSL_ENABLED
  2263. SSLClient cli(host, port);
  2264. #else
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(std::chrono::seconds(2));
  2268. auto res = cli.Get("/");
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_TRUE(Error::Connection == res.error() ||
  2271. Error::ConnectionTimeout == res.error());
  2272. }
  2273. TEST(ConnectionErrorTest, Timeout_Online) {
  2274. auto host = "google.com";
  2275. #ifdef CPPHTTPLIB_SSL_ENABLED
  2276. auto port = 44380;
  2277. SSLClient cli(host, port);
  2278. #else
  2279. auto port = 8080;
  2280. Client cli(host, port);
  2281. #endif
  2282. cli.set_connection_timeout(std::chrono::seconds(2));
  2283. // only probe one address type so that the error reason
  2284. // correlates to the timed-out IPv4, not the unsupported
  2285. // IPv6 connection attempt
  2286. cli.set_address_family(AF_INET);
  2287. auto res = cli.Get("/");
  2288. ASSERT_TRUE(!res);
  2289. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2290. }
  2291. TEST(CancelTest, NoCancel_Online) {
  2292. auto host = "httpbingo.org";
  2293. auto path = std::string{"/range/32"};
  2294. #ifdef CPPHTTPLIB_SSL_ENABLED
  2295. auto port = 443;
  2296. SSLClient cli(host, port);
  2297. #else
  2298. auto port = 80;
  2299. Client cli(host, port);
  2300. #endif
  2301. cli.set_connection_timeout(std::chrono::seconds(5));
  2302. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_EQ(StatusCode::OK_200, res->status);
  2306. }
  2307. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2308. // Use /bytes with a large payload so that the DownloadProgress callback
  2309. // (which only fires for Content-Length responses) is invoked before the
  2310. // entire body is received, giving cancellation a chance to fire.
  2311. auto host = "httpbingo.org";
  2312. auto path = std::string{"/bytes/524288"};
  2313. #ifdef CPPHTTPLIB_SSL_ENABLED
  2314. auto port = 443;
  2315. SSLClient cli(host, port);
  2316. #else
  2317. auto port = 80;
  2318. Client cli(host, port);
  2319. #endif
  2320. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2321. cli.set_connection_timeout(std::chrono::seconds(5));
  2322. ASSERT_TRUE(!res);
  2323. EXPECT_EQ(Error::Canceled, res.error());
  2324. }
  2325. TEST(CancelTest, WithCancelLargePayload_Online) {
  2326. auto host = "httpbingo.org";
  2327. auto path = std::string{"/bytes/524288"};
  2328. #ifdef CPPHTTPLIB_SSL_ENABLED
  2329. auto port = 443;
  2330. SSLClient cli(host, port);
  2331. #else
  2332. auto port = 80;
  2333. Client cli(host, port);
  2334. #endif
  2335. cli.set_connection_timeout(std::chrono::seconds(5));
  2336. uint32_t count = 0;
  2337. auto res =
  2338. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2339. ASSERT_TRUE(!res);
  2340. EXPECT_EQ(Error::Canceled, res.error());
  2341. }
  2342. TEST(CancelTest, NoCancelPost) {
  2343. Server svr;
  2344. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return true; });
  2359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2360. EXPECT_EQ("Hello World!", res->body);
  2361. EXPECT_EQ(StatusCode::OK_200, res->status);
  2362. }
  2363. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2364. Server svr;
  2365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content("Hello World!", "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_connection_timeout(std::chrono::seconds(5));
  2377. auto res =
  2378. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2379. "application/json", [](uint64_t, uint64_t) { return false; });
  2380. ASSERT_TRUE(!res);
  2381. EXPECT_EQ(Error::Canceled, res.error());
  2382. }
  2383. TEST(CancelTest, WithCancelLargePayloadPost) {
  2384. Server svr;
  2385. svr.set_payload_max_length(200 * 1024 * 1024);
  2386. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content(LARGE_DATA, "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_payload_max_length(200 * 1024 * 1024);
  2398. cli.set_connection_timeout(std::chrono::seconds(5));
  2399. auto res =
  2400. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2401. "application/json", [](uint64_t, uint64_t) { return false; });
  2402. ASSERT_TRUE(!res);
  2403. EXPECT_EQ(Error::Canceled, res.error());
  2404. }
  2405. TEST(CancelTest, NoCancelPut) {
  2406. Server svr;
  2407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return true; });
  2422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2423. EXPECT_EQ("Hello World!", res->body);
  2424. EXPECT_EQ(StatusCode::OK_200, res->status);
  2425. }
  2426. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2427. Server svr;
  2428. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content("Hello World!", "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_connection_timeout(std::chrono::seconds(5));
  2440. auto res =
  2441. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2442. "application/json", [](uint64_t, uint64_t) { return false; });
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_EQ(Error::Canceled, res.error());
  2445. }
  2446. TEST(CancelTest, WithCancelLargePayloadPut) {
  2447. Server svr;
  2448. svr.set_payload_max_length(200 * 1024 * 1024);
  2449. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content(LARGE_DATA, "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_payload_max_length(200 * 1024 * 1024);
  2461. cli.set_connection_timeout(std::chrono::seconds(5));
  2462. auto res =
  2463. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2464. "application/json", [](uint64_t, uint64_t) { return false; });
  2465. ASSERT_TRUE(!res);
  2466. EXPECT_EQ(Error::Canceled, res.error());
  2467. }
  2468. TEST(CancelTest, NoCancelPatch) {
  2469. Server svr;
  2470. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return true; });
  2485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2486. EXPECT_EQ("Hello World!", res->body);
  2487. EXPECT_EQ(StatusCode::OK_200, res->status);
  2488. }
  2489. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2490. Server svr;
  2491. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content("Hello World!", "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_connection_timeout(std::chrono::seconds(5));
  2503. auto res =
  2504. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2505. "application/json", [](uint64_t, uint64_t) { return false; });
  2506. ASSERT_TRUE(!res);
  2507. EXPECT_EQ(Error::Canceled, res.error());
  2508. }
  2509. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2510. Server svr;
  2511. svr.set_payload_max_length(200 * 1024 * 1024);
  2512. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2513. res.set_content(LARGE_DATA, "text/plain");
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. cli.set_payload_max_length(200 * 1024 * 1024);
  2524. cli.set_connection_timeout(std::chrono::seconds(5));
  2525. auto res =
  2526. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2527. "application/json", [](uint64_t, uint64_t) { return false; });
  2528. ASSERT_TRUE(!res);
  2529. EXPECT_EQ(Error::Canceled, res.error());
  2530. }
  2531. TEST(CancelTest, NoCancelDelete) {
  2532. Server svr;
  2533. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2534. res.set_content("Hello World!", "text/plain");
  2535. });
  2536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2537. auto se = detail::scope_exit([&] {
  2538. svr.stop();
  2539. thread.join();
  2540. ASSERT_FALSE(svr.is_running());
  2541. });
  2542. svr.wait_until_ready();
  2543. Client cli(HOST, PORT);
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. auto res =
  2546. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2547. "application/json", [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("Hello World!", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2553. Server svr;
  2554. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2555. res.set_content("Hello World!", "text/plain");
  2556. });
  2557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2558. auto se = detail::scope_exit([&] {
  2559. svr.stop();
  2560. thread.join();
  2561. ASSERT_FALSE(svr.is_running());
  2562. });
  2563. svr.wait_until_ready();
  2564. Client cli(HOST, PORT);
  2565. cli.set_connection_timeout(std::chrono::seconds(5));
  2566. auto res =
  2567. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2568. "application/json", [](uint64_t, uint64_t) { return false; });
  2569. ASSERT_TRUE(!res);
  2570. EXPECT_EQ(Error::Canceled, res.error());
  2571. }
  2572. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2573. Server svr;
  2574. svr.set_payload_max_length(200 * 1024 * 1024);
  2575. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2576. res.set_content(LARGE_DATA, "text/plain");
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. Client cli(HOST, PORT);
  2586. cli.set_payload_max_length(200 * 1024 * 1024);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return false; });
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::Canceled, res.error());
  2593. }
  2594. static std::string remove_whitespace(const std::string &input) {
  2595. std::string output;
  2596. output.reserve(input.size());
  2597. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2598. [](unsigned char c) { return !std::isspace(c); });
  2599. return output;
  2600. }
  2601. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2602. auto host = "httpbingo.org";
  2603. auto path = std::string{"/basic-auth/hello/world"};
  2604. #ifdef CPPHTTPLIB_SSL_ENABLED
  2605. auto port = 443;
  2606. SSLClient cli(host, port);
  2607. #else
  2608. auto port = 80;
  2609. Client cli(host, port);
  2610. #endif
  2611. {
  2612. auto res = cli.Get(path);
  2613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2615. }
  2616. {
  2617. auto res = cli.Get(
  2618. path, Headers{make_basic_authentication_header("hello", "world")});
  2619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2620. auto body = remove_whitespace(res->body);
  2621. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2622. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. }
  2625. {
  2626. cli.set_basic_auth("hello", "world");
  2627. auto res = cli.Get(path);
  2628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2629. auto body = remove_whitespace(res->body);
  2630. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2631. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2632. EXPECT_EQ(StatusCode::OK_200, res->status);
  2633. }
  2634. {
  2635. cli.set_basic_auth("hello", "bad");
  2636. auto res = cli.Get(path);
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2639. }
  2640. {
  2641. cli.set_basic_auth("bad", "world");
  2642. auto res = cli.Get(path);
  2643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2645. }
  2646. }
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2649. auto host = "httpbingo.org";
  2650. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2651. auto paths = std::vector<std::string>{
  2652. "/digest-auth/auth/hello/world/MD5",
  2653. "/digest-auth/auth/hello/world/SHA-256",
  2654. };
  2655. auto port = 443;
  2656. SSLClient cli(host, port);
  2657. {
  2658. auto res = cli.Get(unauth_path);
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2661. }
  2662. {
  2663. cli.set_digest_auth("hello", "world");
  2664. for (const auto &path : paths) {
  2665. auto res = cli.Get(path.c_str());
  2666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2667. auto body = remove_whitespace(res->body);
  2668. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2669. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. }
  2672. cli.set_digest_auth("hello", "bad");
  2673. for (const auto &path : paths) {
  2674. auto res = cli.Get(path.c_str());
  2675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2676. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2677. }
  2678. }
  2679. }
  2680. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2681. // comma-separated list of challenges, and each challenge may itself carry a
  2682. // comma-separated auth-param list, so a server can legally offer Basic
  2683. // before Digest, either as two field lines or packed into one. Runs one 401
  2684. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2685. // value() joins them in receipt order) and checks that the retry carries a
  2686. // well-formed Digest Authorization header naming expected_realm.
  2687. static void
  2688. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2689. const std::string &expected_realm) {
  2690. std::atomic<int> hits{0};
  2691. Server svr;
  2692. svr.Get("/x", [&](const Request &req, Response &res) {
  2693. if (++hits == 1) {
  2694. res.status = StatusCode::Unauthorized_401;
  2695. for (const auto &challenge : challenges) {
  2696. res.set_header("WWW-Authenticate", challenge);
  2697. }
  2698. } else {
  2699. auto authorization = req.get_header_value("Authorization");
  2700. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2701. EXPECT_NE(std::string::npos,
  2702. authorization.find("realm=\"" + expected_realm + "\""));
  2703. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2704. res.set_content("ok", "text/plain");
  2705. }
  2706. });
  2707. auto port = svr.bind_to_any_port(HOST);
  2708. std::thread t([&]() { svr.listen_after_bind(); });
  2709. auto se = detail::scope_exit([&] {
  2710. svr.stop();
  2711. t.join();
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, port);
  2715. cli.set_digest_auth("hello", "world");
  2716. auto res = cli.Get("/x");
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ(2, hits.load());
  2719. }
  2720. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2721. static const char *kDigestChallenge =
  2722. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2723. "algorithm=MD5";
  2724. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2725. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2726. "testrealm");
  2727. }
  2728. // Same challenge list with the schemes in the opposite order, to make sure
  2729. // the fix above didn't just special-case "Basic first".
  2730. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2731. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2732. "testrealm");
  2733. }
  2734. // A comma inside a quoted auth-param value must not be mistaken for the
  2735. // separator between two challenges (or two auth-params).
  2736. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2737. run_digest_challenge_list_test(
  2738. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2739. "algorithm=MD5"},
  2740. "test,realm");
  2741. }
  2742. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2743. // make_digest_authentication_header() dereferences both unconditionally, so
  2744. // a server sending a challenge missing either one must not be treated as
  2745. // usable -- doing so used to crash the client with std::out_of_range.
  2746. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2747. Server svr;
  2748. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2749. res.status = StatusCode::Unauthorized_401;
  2750. res.set_header("WWW-Authenticate", challenge);
  2751. });
  2752. auto port = svr.bind_to_any_port(HOST);
  2753. std::thread t([&]() { svr.listen_after_bind(); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. t.join();
  2757. });
  2758. svr.wait_until_ready();
  2759. Client cli(HOST, port);
  2760. cli.set_digest_auth("hello", "world");
  2761. auto res = cli.Get("/x");
  2762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2763. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2764. }
  2765. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2766. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2767. }
  2768. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2769. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2770. }
  2771. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2772. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2773. }
  2774. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2775. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2776. // when storing the values, so the header builder has to re-escape them (and
  2777. // keep algorithm a bare token); otherwise the value breaks out of its
  2778. // quoted-string and injects extra auth-params into the client's Authorization.
  2779. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2780. std::atomic<int> hits{0};
  2781. std::string authorization;
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. // On the wire the quotes embedded in the values are backslash-escaped.
  2787. res.set_header("WWW-Authenticate",
  2788. "Digest realm=\"testrealm\", "
  2789. "nonce=\"n\\\"; injected=\\\"x\", "
  2790. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2791. } else {
  2792. authorization = req.get_header_value("Authorization");
  2793. res.set_content("ok", "text/plain");
  2794. }
  2795. });
  2796. auto port = svr.bind_to_any_port(HOST);
  2797. std::thread t([&]() { svr.listen_after_bind(); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. t.join();
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(HOST, port);
  2804. cli.set_digest_auth("hello", "world");
  2805. auto res = cli.Get("/x");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(2, hits.load());
  2808. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2809. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2810. // inside its quoted-string rather than starting an "injected" auth-param.
  2811. EXPECT_NE(std::string::npos,
  2812. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2813. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2814. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2815. }
  2816. #endif
  2817. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2818. auto host = "google.com";
  2819. auto another_host = "example.com";
  2820. auto wrong_ip = "0.0.0.0";
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. SSLClient cli(host);
  2823. #else
  2824. Client cli(host);
  2825. #endif
  2826. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2827. auto res = cli.Get("/");
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2830. }
  2831. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2832. auto host = "google.com";
  2833. auto wrong_ip = "0.0.0.0";
  2834. #ifdef CPPHTTPLIB_SSL_ENABLED
  2835. SSLClient cli(host);
  2836. #else
  2837. Client cli(host);
  2838. #endif
  2839. cli.set_hostname_addr_map({{host, wrong_ip}});
  2840. auto res = cli.Get("/");
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::Connection, res.error());
  2843. }
  2844. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2845. // A mapped value that is not an IP literal must be resolved. "localhost"
  2846. // resolves from the hosts file, so this test needs no external DNS.
  2847. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2848. auto host = "target.invalid";
  2849. Server svr;
  2850. std::string received_host;
  2851. svr.Get("/hi", [&](const Request &req, Response &res) {
  2852. received_host = req.get_header_value("Host");
  2853. res.set_content("Hello World!", "text/plain");
  2854. });
  2855. auto port = svr.bind_to_any_port(HOST);
  2856. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2857. auto se = detail::scope_exit([&] {
  2858. svr.stop();
  2859. thread.join();
  2860. ASSERT_FALSE(svr.is_running());
  2861. });
  2862. svr.wait_until_ready();
  2863. Client cli(host, port);
  2864. cli.set_hostname_addr_map({{host, HOST}});
  2865. auto res = cli.Get("/hi");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::OK_200, res->status);
  2868. // The mapping only redirects the connection; the identity stays host_.
  2869. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2870. }
  2871. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2872. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2873. auto host = "target.invalid";
  2874. Server svr;
  2875. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2876. res.set_content("Hello World!", "text/plain");
  2877. });
  2878. auto port = svr.bind_to_any_port("127.0.0.1");
  2879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2880. auto se = detail::scope_exit([&] {
  2881. svr.stop();
  2882. thread.join();
  2883. ASSERT_FALSE(svr.is_running());
  2884. });
  2885. svr.wait_until_ready();
  2886. Client cli(host, port);
  2887. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2888. auto res = cli.Get("/hi");
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::OK_200, res->status);
  2891. }
  2892. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2893. // An empty mapped value must leave host_ as the connection target. Without
  2894. // that guard the empty value would become the host argument, getaddrinfo
  2895. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2896. // loopback - silently connecting somewhere the caller never asked for.
  2897. // The server listens on loopback, so such a fallback would succeed and is
  2898. // therefore observable as a failure of this test.
  2899. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2900. Server svr;
  2901. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2902. res.set_content("Hello World!", "text/plain");
  2903. });
  2904. auto port = svr.bind_to_any_port(HOST);
  2905. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. Client cli(blackhole, port);
  2913. cli.set_hostname_addr_map({{blackhole, ""}});
  2914. cli.set_connection_timeout(1);
  2915. auto res = cli.Get("/hi");
  2916. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2917. }
  2918. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2919. auto host = "httpbingo.org";
  2920. auto path = std::string{"/absolute-redirect/3"};
  2921. #ifdef CPPHTTPLIB_SSL_ENABLED
  2922. SSLClient cli(host);
  2923. #else
  2924. Client cli(host);
  2925. #endif
  2926. cli.set_follow_location(true);
  2927. auto res = cli.Get(path);
  2928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2929. EXPECT_EQ(StatusCode::OK_200, res->status);
  2930. }
  2931. TEST(RedirectTest, Redirect_Online) {
  2932. auto host = "httpbingo.org";
  2933. auto path = std::string{"/redirect/3"};
  2934. #ifdef CPPHTTPLIB_SSL_ENABLED
  2935. SSLClient cli(host);
  2936. #else
  2937. Client cli(host);
  2938. #endif
  2939. cli.set_follow_location(true);
  2940. auto res = cli.Get(path);
  2941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST(RelativeRedirectTest, Redirect_Online) {
  2945. auto host = "httpbingo.org";
  2946. auto path = std::string{"/relative-redirect/3"};
  2947. #ifdef CPPHTTPLIB_SSL_ENABLED
  2948. SSLClient cli(host);
  2949. #else
  2950. Client cli(host);
  2951. #endif
  2952. cli.set_follow_location(true);
  2953. auto res = cli.Get(path);
  2954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2955. EXPECT_EQ(StatusCode::OK_200, res->status);
  2956. }
  2957. TEST(TooManyRedirectTest, Redirect_Online) {
  2958. auto host = "httpbingo.org";
  2959. auto path = std::string{"/redirect/21"};
  2960. #ifdef CPPHTTPLIB_SSL_ENABLED
  2961. SSLClient cli(host);
  2962. #else
  2963. Client cli(host);
  2964. #endif
  2965. cli.set_follow_location(true);
  2966. auto res = cli.Get(path);
  2967. ASSERT_TRUE(!res);
  2968. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2969. }
  2970. #ifdef CPPHTTPLIB_SSL_ENABLED
  2971. TEST(YahooRedirectTest, Redirect_Online) {
  2972. Client cli("yahoo.com");
  2973. auto res = cli.Get("/");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2976. cli.set_follow_location(true);
  2977. res = cli.Get("/");
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(StatusCode::OK_200, res->status);
  2980. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2981. }
  2982. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2983. #define REDIR_HOST "httpbingo.org"
  2984. #define REDIR_PATH "/redirect-to"
  2985. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2986. SSLClient cli(REDIR_HOST);
  2987. cli.set_follow_location(true);
  2988. auto res =
  2989. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2991. EXPECT_EQ(StatusCode::OK_200, res->status);
  2992. }
  2993. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2994. SSLClient cli(REDIR_HOST);
  2995. cli.set_follow_location(true);
  2996. Params params;
  2997. params.emplace("url", "http://example.com");
  2998. params.emplace("status_code", "302");
  2999. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. }
  3003. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3004. SSLClient cli(REDIR_HOST);
  3005. cli.set_follow_location(true);
  3006. Params params;
  3007. params.emplace("url", "http://example.com");
  3008. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. EXPECT_EQ(StatusCode::OK_200, res->status);
  3011. }
  3012. TEST(UrlWithSpace, Redirect_Online) {
  3013. SSLClient cli("edge.forgecdn.net");
  3014. cli.set_follow_location(true);
  3015. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3017. EXPECT_EQ(StatusCode::OK_200, res->status);
  3018. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3019. }
  3020. #endif
  3021. #if !defined(_WIN32) && !defined(_WIN64)
  3022. TEST(ReceiveSignals, Signal) {
  3023. auto setupSignalHandlers = []() {
  3024. struct sigaction act;
  3025. sigemptyset(&act.sa_mask);
  3026. act.sa_flags = SA_SIGINFO;
  3027. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3028. switch (sig) {
  3029. case SIGINT:
  3030. default: break;
  3031. }
  3032. };
  3033. ::sigaction(SIGINT, &act, nullptr);
  3034. };
  3035. Server svr;
  3036. int port = 0;
  3037. auto thread = std::thread([&]() {
  3038. setupSignalHandlers();
  3039. port = svr.bind_to_any_port(HOST);
  3040. svr.listen_after_bind();
  3041. });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. ASSERT_TRUE(svr.is_running());
  3049. pthread_kill(thread.native_handle(), SIGINT);
  3050. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3051. ASSERT_TRUE(svr.is_running());
  3052. }
  3053. #endif
  3054. TEST(RedirectToDifferentPort, Redirect) {
  3055. Server svr1;
  3056. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3057. res.set_content("Hello World!", "text/plain");
  3058. });
  3059. int svr1_port = 0;
  3060. auto thread1 = std::thread([&]() {
  3061. svr1_port = svr1.bind_to_any_port(HOST);
  3062. svr1.listen_after_bind();
  3063. });
  3064. Server svr2;
  3065. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3066. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3067. });
  3068. int svr2_port = 0;
  3069. auto thread2 = std::thread([&]() {
  3070. svr2_port = svr2.bind_to_any_port(HOST);
  3071. svr2.listen_after_bind();
  3072. });
  3073. auto se = detail::scope_exit([&] {
  3074. svr2.stop();
  3075. thread2.join();
  3076. svr1.stop();
  3077. thread1.join();
  3078. ASSERT_FALSE(svr2.is_running());
  3079. ASSERT_FALSE(svr1.is_running());
  3080. });
  3081. svr1.wait_until_ready();
  3082. svr2.wait_until_ready();
  3083. Client cli("localhost", svr2_port);
  3084. cli.set_follow_location(true);
  3085. auto res = cli.Get("/2");
  3086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. EXPECT_EQ("Hello World!", res->body);
  3089. }
  3090. static void
  3091. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3092. Server svr1;
  3093. std::string captured_authorization;
  3094. svr1.Get("/target", [&](const Request &req, Response &res) {
  3095. captured_authorization = req.get_header_value("Authorization");
  3096. res.set_content("OK", "text/plain");
  3097. });
  3098. int svr1_port = 0;
  3099. auto thread1 = std::thread([&]() {
  3100. svr1_port = svr1.bind_to_any_port(HOST);
  3101. svr1.listen_after_bind();
  3102. });
  3103. Server svr2;
  3104. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3105. res.set_redirect(
  3106. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3107. });
  3108. int svr2_port = 0;
  3109. auto thread2 = std::thread([&]() {
  3110. svr2_port = svr2.bind_to_any_port(HOST);
  3111. svr2.listen_after_bind();
  3112. });
  3113. auto se = detail::scope_exit([&] {
  3114. svr2.stop();
  3115. thread2.join();
  3116. svr1.stop();
  3117. thread1.join();
  3118. ASSERT_FALSE(svr2.is_running());
  3119. ASSERT_FALSE(svr1.is_running());
  3120. });
  3121. svr1.wait_until_ready();
  3122. svr2.wait_until_ready();
  3123. Client cli("localhost", svr2_port);
  3124. cli.set_follow_location(true);
  3125. set_auth(cli);
  3126. auto res = cli.Get("/redir");
  3127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3128. EXPECT_EQ(StatusCode::OK_200, res->status);
  3129. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3130. EXPECT_TRUE(captured_authorization.empty());
  3131. }
  3132. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3133. TestDoNotForwardCredentialsOnRedirect(
  3134. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3135. }
  3136. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3137. TestDoNotForwardCredentialsOnRedirect(
  3138. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3139. }
  3140. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3141. Server svr1;
  3142. std::string captured_cookie;
  3143. bool target_hit = false;
  3144. svr1.Get("/target", [&](const Request &req, Response &res) {
  3145. captured_cookie = req.get_header_value("Cookie");
  3146. target_hit = true;
  3147. res.set_content("OK", "text/plain");
  3148. });
  3149. int svr1_port = 0;
  3150. auto thread1 = std::thread([&]() {
  3151. svr1_port = svr1.bind_to_any_port(HOST);
  3152. svr1.listen_after_bind();
  3153. });
  3154. Server svr2;
  3155. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3156. res.set_redirect(
  3157. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3177. auto res = cli.Get("/redir", headers);
  3178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3179. EXPECT_EQ(StatusCode::OK_200, res->status);
  3180. EXPECT_TRUE(target_hit);
  3181. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3182. EXPECT_TRUE(captured_cookie.empty());
  3183. }
  3184. TEST(RedirectToSamePort, ForwardCookie) {
  3185. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3186. // header so that ordinary session flows keep working.
  3187. Server svr;
  3188. std::string captured_cookie;
  3189. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3190. res.set_redirect("/target", 302);
  3191. });
  3192. svr.Get("/target", [&](const Request &req, Response &res) {
  3193. captured_cookie = req.get_header_value("Cookie");
  3194. res.set_content("OK", "text/plain");
  3195. });
  3196. auto port = svr.bind_to_any_port(HOST);
  3197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3198. auto se = detail::scope_exit([&] {
  3199. svr.stop();
  3200. thread.join();
  3201. ASSERT_FALSE(svr.is_running());
  3202. });
  3203. svr.wait_until_ready();
  3204. Client cli(HOST, port);
  3205. cli.set_follow_location(true);
  3206. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3207. auto res = cli.Get("/redir", headers);
  3208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3209. EXPECT_EQ(StatusCode::OK_200, res->status);
  3210. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3211. }
  3212. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3213. Server svr;
  3214. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3215. // Port number that overflows int — should not crash
  3216. res.set_redirect("http://localhost:99999999999999999999/target");
  3217. });
  3218. auto port = svr.bind_to_any_port(HOST);
  3219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3220. auto se = detail::scope_exit([&] {
  3221. svr.stop();
  3222. thread.join();
  3223. ASSERT_FALSE(svr.is_running());
  3224. });
  3225. svr.wait_until_ready();
  3226. Client cli(HOST, port);
  3227. cli.set_follow_location(true);
  3228. auto res = cli.Get("/redir");
  3229. // Should fail gracefully, not crash (no valid response due to bad port)
  3230. EXPECT_FALSE(res);
  3231. }
  3232. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3233. Server svr;
  3234. auto port = svr.bind_to_any_port(HOST);
  3235. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3236. // The server's own port followed by junk must not be followed
  3237. res.set_redirect("http://" + std::string(HOST) + ":" +
  3238. std::to_string(port) + "junk/target");
  3239. });
  3240. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("target", "text/plain");
  3242. });
  3243. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3244. auto se = detail::scope_exit([&] {
  3245. svr.stop();
  3246. thread.join();
  3247. ASSERT_FALSE(svr.is_running());
  3248. });
  3249. svr.wait_until_ready();
  3250. Client cli(HOST, port);
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get("/redir");
  3253. EXPECT_FALSE(res);
  3254. }
  3255. TEST(RedirectFromPageWithContent, Redirect) {
  3256. Server svr;
  3257. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3258. res.set_content("___", "text/plain");
  3259. res.set_redirect("/2");
  3260. });
  3261. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!", "text/plain");
  3263. });
  3264. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3265. auto se = detail::scope_exit([&] {
  3266. svr.stop();
  3267. th.join();
  3268. ASSERT_FALSE(svr.is_running());
  3269. });
  3270. svr.wait_until_ready();
  3271. {
  3272. Client cli("localhost", PORT);
  3273. cli.set_follow_location(true);
  3274. std::string body;
  3275. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3276. body.append(data, data_length);
  3277. return true;
  3278. });
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ("Hello World!", body);
  3282. }
  3283. {
  3284. Client cli("localhost", PORT);
  3285. std::string body;
  3286. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3287. body.append(data, data_length);
  3288. return true;
  3289. });
  3290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3291. EXPECT_EQ(StatusCode::Found_302, res->status);
  3292. EXPECT_EQ("___", body);
  3293. }
  3294. }
  3295. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3296. Server svr;
  3297. auto port_str = std::to_string(PORT);
  3298. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3299. auto expected_host = "[::1]:" + port_str;
  3300. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("___", "text/plain");
  3302. // res.set_redirect("/2");
  3303. res.set_redirect(redirect_url);
  3304. });
  3305. svr.Get("/2", [&](const Request &req, Response &res) {
  3306. auto host_header = req.headers.find("Host");
  3307. ASSERT_TRUE(host_header != req.headers.end());
  3308. EXPECT_EQ(expected_host, host_header->second);
  3309. res.set_content("Hello World!", "text/plain");
  3310. });
  3311. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3312. auto se = detail::scope_exit([&] {
  3313. svr.stop();
  3314. th.join();
  3315. ASSERT_FALSE(svr.is_running());
  3316. });
  3317. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3318. // actually starts anything, so the condition !svr.is_running() will
  3319. // always remain true, and the loop never stops.
  3320. // This basically counts how many milliseconds have passed since the
  3321. // call to svr.listen(), and if after 5 seconds nothing started yet
  3322. // aborts the test.
  3323. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3324. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3325. ASSERT_LT(milliseconds, 5000U);
  3326. }
  3327. {
  3328. Client cli("::1", PORT);
  3329. cli.set_follow_location(true);
  3330. std::string body;
  3331. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3332. body.append(data, data_length);
  3333. return true;
  3334. });
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. EXPECT_EQ(StatusCode::OK_200, res->status);
  3337. EXPECT_EQ("Hello World!", body);
  3338. }
  3339. {
  3340. Client cli("::1", PORT);
  3341. std::string body;
  3342. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3343. body.append(data, data_length);
  3344. return true;
  3345. });
  3346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3347. EXPECT_EQ(StatusCode::Found_302, res->status);
  3348. EXPECT_EQ("___", body);
  3349. }
  3350. }
  3351. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3352. Server svr;
  3353. svr.Get("/foo", [](const Request &req, Response &res) {
  3354. auto a = req.params.find("a");
  3355. if (a != req.params.end()) {
  3356. res.set_content((*a).second, "text/plain");
  3357. res.status = StatusCode::OK_200;
  3358. } else {
  3359. res.status = StatusCode::BadRequest_400;
  3360. }
  3361. });
  3362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3363. auto se = detail::scope_exit([&] {
  3364. svr.stop();
  3365. thread.join();
  3366. ASSERT_FALSE(svr.is_running());
  3367. });
  3368. svr.wait_until_ready();
  3369. {
  3370. Client cli(HOST, PORT);
  3371. cli.set_path_encode(false);
  3372. auto res = cli.Get("/foo?a=explicitly+encoded");
  3373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. // This expects it back with a space, as the `+` won't have been
  3376. // url-encoded, and server-side the params get decoded turning `+`
  3377. // into spaces.
  3378. EXPECT_EQ("explicitly encoded", res->body);
  3379. }
  3380. }
  3381. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3382. // When path encoding is disabled the client must transmit the supplied
  3383. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3384. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3385. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3386. // than a space (0x20). Assert on the raw wire target to catch this.
  3387. Server svr;
  3388. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3389. svr.Get("/foo", [&](const Request &req, Response &res) {
  3390. EXPECT_EQ(expected_target, req.target);
  3391. res.status = StatusCode::OK_200;
  3392. });
  3393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3394. auto se = detail::scope_exit([&] {
  3395. svr.stop();
  3396. thread.join();
  3397. ASSERT_FALSE(svr.is_running());
  3398. });
  3399. svr.wait_until_ready();
  3400. {
  3401. Client cli(HOST, PORT);
  3402. cli.set_path_encode(false);
  3403. auto res = cli.Get(expected_target.c_str());
  3404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3405. EXPECT_EQ(StatusCode::OK_200, res->status);
  3406. }
  3407. }
  3408. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3409. // `open_stream()` used to skip the path encoding that the buffered send
  3410. // path applies, so the same `path` produced different bytes in the request
  3411. // line depending on which API was used. Assert the two agree.
  3412. Server svr;
  3413. std::string target;
  3414. svr.Get(".*", [&](const Request &req, Response &res) {
  3415. target = req.target;
  3416. res.status = StatusCode::OK_200;
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. struct {
  3427. const char *path;
  3428. const char *expected;
  3429. } cases[] = {
  3430. {"/a b?x=1", "/a%20b?x=1"},
  3431. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3432. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3433. };
  3434. for (const auto &c : cases) {
  3435. Client cli(HOST, port);
  3436. target.clear();
  3437. auto res = cli.Get(c.path);
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3440. auto buffered_target = target;
  3441. target.clear();
  3442. auto handle = cli.open_stream("GET", c.path);
  3443. EXPECT_TRUE(handle.is_valid())
  3444. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3445. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3446. }
  3447. }
  3448. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3449. // The `set_path_encode(false)` contract — transmit the supplied target
  3450. // verbatim — must hold for the streaming API too.
  3451. Server svr;
  3452. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3453. std::string target;
  3454. svr.Get("/foo", [&](const Request &req, Response &res) {
  3455. target = req.target;
  3456. res.status = StatusCode::OK_200;
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. {
  3467. Client cli(HOST, port);
  3468. cli.set_path_encode(false);
  3469. auto handle = cli.open_stream("GET", expected_target);
  3470. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3471. EXPECT_EQ(expected_target, target);
  3472. }
  3473. }
  3474. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3475. // With path encoding enabled a CR/LF in the target is percent-encoded
  3476. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3477. // write_request_line still backstops `set_path_encode(false)`, which is
  3478. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3479. Server svr;
  3480. // Captured before routing: the decoded path contains a newline, which a
  3481. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3482. std::string target;
  3483. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3484. target = req.target;
  3485. res.status = StatusCode::OK_200;
  3486. return Server::HandlerResponse::Handled;
  3487. });
  3488. auto port = svr.bind_to_any_port(HOST);
  3489. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3490. auto se = detail::scope_exit([&] {
  3491. svr.stop();
  3492. thread.join();
  3493. ASSERT_FALSE(svr.is_running());
  3494. });
  3495. svr.wait_until_ready();
  3496. {
  3497. Client cli(HOST, port);
  3498. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3499. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3500. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3504. // Every control character is percent-encoded, not just CR/LF, so the target
  3505. // passes the request-target check in write_request_line.
  3506. Server svr;
  3507. std::string target;
  3508. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3509. target = req.target;
  3510. res.status = StatusCode::OK_200;
  3511. return Server::HandlerResponse::Handled;
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. {
  3522. Client cli(HOST, port);
  3523. auto res = cli.Get("/a\tb\x1b\x7f");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ("/a%09b%1B%7F", target);
  3526. }
  3527. }
  3528. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3529. // Nothing may reach the wire: a raw CR/LF target would split the request
  3530. // line and inject headers.
  3531. Server svr;
  3532. // Pre-routing so that "not called" means nothing reached the server at all,
  3533. // rather than merely failing to match a handler pattern.
  3534. auto handler_called = false;
  3535. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3536. handler_called = true;
  3537. res.status = StatusCode::OK_200;
  3538. return Server::HandlerResponse::Handled;
  3539. });
  3540. auto port = svr.bind_to_any_port(HOST);
  3541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. {
  3549. Client cli(HOST, port);
  3550. cli.set_path_encode(false);
  3551. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3552. EXPECT_FALSE(handle.is_valid());
  3553. EXPECT_EQ(Error::Write, handle.error);
  3554. EXPECT_FALSE(handler_called);
  3555. }
  3556. }
  3557. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3558. // Which of the two branches runs is decided by whether the query component
  3559. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3560. // an empty query and must still fall back to building one from
  3561. // `req.params`, while a non-empty query must win over `req.params`.
  3562. Server svr;
  3563. std::string target;
  3564. svr.Get("/foo", [&](const Request &req, Response &res) {
  3565. target = req.target;
  3566. res.status = StatusCode::OK_200;
  3567. });
  3568. auto port = svr.bind_to_any_port(HOST);
  3569. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. // Trailing `?` -> empty query component -> `req.params` is used.
  3578. Client cli(HOST, port);
  3579. Request req;
  3580. req.method = "GET";
  3581. req.path = "/foo?";
  3582. req.params.emplace("a", "1");
  3583. target.clear();
  3584. auto res = cli.send(req);
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ("/foo?a=1", target);
  3587. }
  3588. {
  3589. // Non-empty query in `req.path` -> `req.params` is not appended.
  3590. Client cli(HOST, port);
  3591. Request req;
  3592. req.method = "GET";
  3593. req.path = "/foo?b=2";
  3594. req.params.emplace("a", "1");
  3595. target.clear();
  3596. auto res = cli.send(req);
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ("/foo?b=2", target);
  3599. }
  3600. }
  3601. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3602. Server svr;
  3603. svr.Get("/", [](const Request &req, Response &) {
  3604. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3605. });
  3606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. thread.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. svr.wait_until_ready();
  3613. {
  3614. Client cli(HOST, PORT);
  3615. cli.set_path_encode(false);
  3616. auto res = cli.Get("/?something=%0A");
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. }
  3620. }
  3621. TEST(BindServerTest, BindDualStack) {
  3622. Server svr;
  3623. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. {
  3634. Client cli("127.0.0.1", PORT);
  3635. auto res = cli.Get("/1");
  3636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. EXPECT_EQ("Hello World!", res->body);
  3639. }
  3640. {
  3641. Client cli("::1", PORT);
  3642. auto res = cli.Get("/1");
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("Hello World!", res->body);
  3646. }
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparately) {
  3649. Server svr;
  3650. int port = svr.bind_to_any_port("0.0.0.0");
  3651. ASSERT_TRUE(svr.is_valid());
  3652. ASSERT_TRUE(port > 0);
  3653. svr.stop();
  3654. }
  3655. // Reports whether anything is still listening on a loopback port. A plain
  3656. // connect() is used instead of a Client request because a socket left bound by
  3657. // mistake accepts the connection into its backlog and never answers, which
  3658. // would hang the test instead of failing it.
  3659. static bool is_loopback_port_accepting(int port) {
  3660. sockaddr_in addr{};
  3661. addr.sin_family = AF_INET;
  3662. addr.sin_port = htons(static_cast<uint16_t>(port));
  3663. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3664. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3665. EXPECT_NE(sock, INVALID_SOCKET);
  3666. if (sock == INVALID_SOCKET) { return false; }
  3667. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3668. static_cast<socklen_t>(sizeof(addr)));
  3669. detail::close_socket(sock);
  3670. return ret == 0;
  3671. }
  3672. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3673. Server svr;
  3674. auto port = svr.bind_to_any_port("127.0.0.1");
  3675. ASSERT_TRUE(port > 0);
  3676. svr.stop();
  3677. // bind_to_any_port() already called listen(2), so until stop() closed the
  3678. // descriptor the port kept accepting connections into the backlog. ASSERT
  3679. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3680. // below blocks forever in the accept loop.
  3681. ASSERT_FALSE(is_loopback_port_accepting(port));
  3682. // Nothing is left to accept on, so listen_after_bind() must report failure
  3683. // instead of returning success without ever serving.
  3684. EXPECT_FALSE(svr.listen_after_bind());
  3685. // The failed listen marks the server decommissioned, so a waiter returns
  3686. // instead of spinning forever.
  3687. svr.wait_until_ready();
  3688. }
  3689. #ifdef CPPHTTPLIB_SSL_ENABLED
  3690. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3692. CLIENT_CA_CERT_DIR);
  3693. int port = svr.bind_to_any_port("0.0.0.0");
  3694. ASSERT_TRUE(svr.is_valid());
  3695. ASSERT_TRUE(port > 0);
  3696. svr.stop();
  3697. }
  3698. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3699. // or a rejected CustomRoute() registration would not stop the server binding.
  3700. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3702. CLIENT_CA_CERT_DIR);
  3703. ASSERT_TRUE(svr.is_valid());
  3704. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3705. EXPECT_FALSE(svr.is_valid());
  3706. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3707. }
  3708. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3709. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3710. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3711. int port = svr.bind_to_any_port("0.0.0.0");
  3712. ASSERT_TRUE(svr.is_valid());
  3713. ASSERT_TRUE(port > 0);
  3714. svr.stop();
  3715. }
  3716. TEST(BindServerTest, UpdateCertsPem) {
  3717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3718. int port = svr.bind_to_any_port("0.0.0.0");
  3719. ASSERT_TRUE(svr.is_valid());
  3720. ASSERT_TRUE(port > 0);
  3721. // Read PEM files
  3722. std::string cert_pem, key_pem, ca_pem;
  3723. read_file(SERVER_CERT_FILE, cert_pem);
  3724. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3725. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3726. // Update server certificates using PEM API
  3727. ASSERT_TRUE(
  3728. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3729. ASSERT_TRUE(svr.is_valid());
  3730. svr.stop();
  3731. }
  3732. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3733. // Start server with client CA (enables client auth)
  3734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3735. ASSERT_TRUE(svr.is_valid());
  3736. bool handler_called = false;
  3737. svr.Get("/test", [&](const Request &req, Response &res) {
  3738. handler_called = true;
  3739. // Verify client certificate is present
  3740. auto cert = req.peer_cert();
  3741. EXPECT_TRUE(static_cast<bool>(cert));
  3742. res.set_content("ok", "text/plain");
  3743. });
  3744. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3745. auto se = detail::scope_exit([&] {
  3746. svr.stop();
  3747. t.join();
  3748. ASSERT_FALSE(svr.is_running());
  3749. });
  3750. svr.wait_until_ready();
  3751. // Read PEM files
  3752. std::string cert_pem, key_pem, ca_pem;
  3753. read_file(SERVER_CERT_FILE, cert_pem);
  3754. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3755. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3756. // Update server certificates and client CA using PEM API while server running
  3757. ASSERT_TRUE(
  3758. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3759. // Connect with client certificate
  3760. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3761. cli.enable_server_certificate_verification(false);
  3762. cli.set_connection_timeout(30);
  3763. auto res = cli.Get("/test");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. ASSERT_EQ(StatusCode::OK_200, res->status);
  3766. ASSERT_TRUE(handler_called);
  3767. EXPECT_EQ("ok", res->body);
  3768. }
  3769. #endif
  3770. TEST(ErrorHandlerTest, ContentLength) {
  3771. Server svr;
  3772. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3773. res.status = StatusCode::OK_200;
  3774. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3775. "text/html"); // <= Content-Length still 13
  3776. });
  3777. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3778. res.set_content("Hello World!\n", "text/plain");
  3779. res.status = 524;
  3780. });
  3781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, PORT);
  3790. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3792. EXPECT_EQ(StatusCode::OK_200, res->status);
  3793. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3794. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3795. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3796. }
  3797. }
  3798. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3799. TEST(ExceptionTest, WithoutExceptionHandler) {
  3800. Server svr;
  3801. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3802. throw std::runtime_error("exception...");
  3803. });
  3804. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3805. throw std::runtime_error("exception\r\n...");
  3806. });
  3807. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3808. auto se = detail::scope_exit([&] {
  3809. svr.stop();
  3810. listen_thread.join();
  3811. ASSERT_FALSE(svr.is_running());
  3812. });
  3813. svr.wait_until_ready();
  3814. Client cli("localhost", PORT);
  3815. {
  3816. auto res = cli.Get("/exception");
  3817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3818. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3819. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3820. }
  3821. {
  3822. auto res = cli.Get("/unknown");
  3823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3824. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3825. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3826. }
  3827. }
  3828. TEST(ExceptionTest, WithExceptionHandler) {
  3829. Server svr;
  3830. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3831. std::exception_ptr ep) {
  3832. EXPECT_FALSE(ep == nullptr);
  3833. try {
  3834. std::rethrow_exception(ep);
  3835. } catch (std::exception &e) {
  3836. EXPECT_EQ("abc", std::string(e.what()));
  3837. } catch (...) {}
  3838. res.status = StatusCode::InternalServerError_500;
  3839. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3840. "text/html"); // <= Content-Length still 13 at this point
  3841. });
  3842. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3843. res.set_content("Hello World!\n", "text/plain");
  3844. throw std::runtime_error("abc");
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. for (size_t i = 0; i < 10; i++) {
  3854. Client cli(HOST, PORT);
  3855. for (size_t j = 0; j < 100; j++) {
  3856. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3859. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3860. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3861. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3862. }
  3863. cli.set_keep_alive(true);
  3864. for (size_t j = 0; j < 100; j++) {
  3865. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3867. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3868. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3869. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3870. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3871. }
  3872. }
  3873. }
  3874. TEST(ExceptionTest, AndErrorHandler) {
  3875. Server svr;
  3876. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3877. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3878. });
  3879. svr.set_exception_handler(
  3880. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3881. EXPECT_FALSE(ep == nullptr);
  3882. try {
  3883. std::rethrow_exception(ep);
  3884. } catch (std::exception &e) {
  3885. res.set_content(e.what(), "text/html");
  3886. } catch (...) {}
  3887. res.status = StatusCode::InternalServerError_500;
  3888. });
  3889. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3890. throw std::runtime_error("EXCEPTION");
  3891. });
  3892. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3893. res.set_content("ERROR", "text/html");
  3894. res.status = StatusCode::InternalServerError_500;
  3895. });
  3896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3897. auto se = detail::scope_exit([&] {
  3898. svr.stop();
  3899. thread.join();
  3900. ASSERT_FALSE(svr.is_running());
  3901. });
  3902. svr.wait_until_ready();
  3903. Client cli(HOST, PORT);
  3904. {
  3905. auto res = cli.Get("/exception");
  3906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3907. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3908. EXPECT_EQ("EXCEPTION", res->body);
  3909. }
  3910. {
  3911. auto res = cli.Get("/error");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3914. EXPECT_EQ("ERROR", res->body);
  3915. }
  3916. {
  3917. auto res = cli.Get("/invalid");
  3918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3920. EXPECT_EQ("NOT_FOUND", res->body);
  3921. }
  3922. }
  3923. #endif
  3924. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3925. // process_request() wraps only routing() in a try/catch, so an exception from
  3926. // any other user callback used to unwind into the task queue - which does not
  3927. // catch - and terminate the process. Each test below runs the server on a
  3928. // single worker thread: a guard that catches the exception but still loses the
  3929. // thread would otherwise be hidden by a spare worker serving the follow-up
  3930. // request. Note that a regression here aborts the whole test binary rather
  3931. // than failing one test.
  3932. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3933. Server svr;
  3934. svr.new_task_queue = [] { return new ThreadPool(1); };
  3935. std::atomic<int> reported{0};
  3936. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3937. if (err == Error::UserCallbackException) { reported++; }
  3938. });
  3939. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3940. res.set_content_provider(
  3941. 1024, "text/plain",
  3942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3943. sink.write("hello", 5);
  3944. throw std::runtime_error("from the content provider");
  3945. });
  3946. });
  3947. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3948. res.set_content("ok", "text/plain");
  3949. });
  3950. auto port = svr.bind_to_any_port(HOST);
  3951. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3952. auto se = detail::scope_exit([&] {
  3953. svr.stop();
  3954. listen_thread.join();
  3955. ASSERT_FALSE(svr.is_running());
  3956. });
  3957. svr.wait_until_ready();
  3958. {
  3959. Client cli(HOST, port);
  3960. cli.set_read_timeout(5, 0);
  3961. EXPECT_FALSE(cli.Get("/throw"));
  3962. }
  3963. EXPECT_TRUE(svr.is_running());
  3964. EXPECT_EQ(1, reported.load());
  3965. // A request on a fresh connection is still served.
  3966. {
  3967. Client cli(HOST, port);
  3968. auto res = cli.Get("/ok");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("ok", res->body);
  3972. }
  3973. }
  3974. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3975. Server svr;
  3976. svr.new_task_queue = [] { return new ThreadPool(1); };
  3977. std::atomic<bool> should_throw{true};
  3978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3979. res.set_content("hi", "text/plain");
  3980. });
  3981. svr.set_post_routing_handler(
  3982. [&](const Request & /*req*/, Response & /*res*/) {
  3983. if (should_throw) {
  3984. throw std::runtime_error("from the post-routing handler");
  3985. }
  3986. });
  3987. auto port = svr.bind_to_any_port(HOST);
  3988. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3989. auto se = detail::scope_exit([&] {
  3990. svr.stop();
  3991. listen_thread.join();
  3992. ASSERT_FALSE(svr.is_running());
  3993. });
  3994. svr.wait_until_ready();
  3995. {
  3996. Client cli(HOST, port);
  3997. cli.set_read_timeout(5, 0);
  3998. EXPECT_FALSE(cli.Get("/hi"));
  3999. }
  4000. EXPECT_TRUE(svr.is_running());
  4001. should_throw = false;
  4002. {
  4003. Client cli(HOST, port);
  4004. auto res = cli.Get("/hi");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::OK_200, res->status);
  4007. EXPECT_EQ("hi", res->body);
  4008. }
  4009. }
  4010. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4011. // The guard reports the caught exception through the error logger, which is
  4012. // a user callback too. A logger that throws has to be contained as well, or
  4013. // the process would terminate from inside the catch.
  4014. Server svr;
  4015. svr.new_task_queue = [] { return new ThreadPool(1); };
  4016. std::atomic<int> reported{0};
  4017. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4018. if (err == Error::UserCallbackException) {
  4019. reported++;
  4020. throw std::runtime_error("from the error logger");
  4021. }
  4022. });
  4023. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4024. res.set_content_provider(
  4025. 1024, "text/plain",
  4026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4027. sink.write("hello", 5);
  4028. throw std::runtime_error("from the content provider");
  4029. });
  4030. });
  4031. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4032. res.set_content("ok", "text/plain");
  4033. });
  4034. auto port = svr.bind_to_any_port(HOST);
  4035. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4036. auto se = detail::scope_exit([&] {
  4037. svr.stop();
  4038. listen_thread.join();
  4039. ASSERT_FALSE(svr.is_running());
  4040. });
  4041. svr.wait_until_ready();
  4042. {
  4043. Client cli(HOST, port);
  4044. cli.set_read_timeout(5, 0);
  4045. EXPECT_FALSE(cli.Get("/throw"));
  4046. }
  4047. EXPECT_TRUE(svr.is_running());
  4048. EXPECT_EQ(1, reported.load());
  4049. {
  4050. Client cli(HOST, port);
  4051. auto res = cli.Get("/ok");
  4052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4053. EXPECT_EQ(StatusCode::OK_200, res->status);
  4054. EXPECT_EQ("ok", res->body);
  4055. }
  4056. }
  4057. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4058. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4059. // so the exception unwinds through the ws::WebSocket object on its way to
  4060. // the guard. None of the HTTP cases above cross that.
  4061. Server svr;
  4062. svr.new_task_queue = [] { return new ThreadPool(1); };
  4063. std::atomic<int> reported{0};
  4064. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4065. if (err == Error::UserCallbackException) { reported++; }
  4066. });
  4067. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4068. throw std::runtime_error("from the WebSocket handler");
  4069. });
  4070. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4071. res.set_content("ok", "text/plain");
  4072. });
  4073. auto port = svr.bind_to_any_port(HOST);
  4074. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4075. auto se = detail::scope_exit([&] {
  4076. svr.stop();
  4077. listen_thread.join();
  4078. ASSERT_FALSE(svr.is_running());
  4079. });
  4080. svr.wait_until_ready();
  4081. {
  4082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4083. "/ws");
  4084. auto res = client.connect();
  4085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4086. // The server dropped the connection instead of dying.
  4087. std::string msg;
  4088. EXPECT_FALSE(client.read(msg));
  4089. client.close();
  4090. }
  4091. EXPECT_TRUE(svr.is_running());
  4092. EXPECT_EQ(1, reported.load());
  4093. {
  4094. Client cli(HOST, port);
  4095. auto res = cli.Get("/ok");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("ok", res->body);
  4099. }
  4100. }
  4101. #ifdef CPPHTTPLIB_SSL_ENABLED
  4102. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4103. // SSLServer::process_and_close_socket() is a separate overload with its own
  4104. // guard, so it is exercised on its own.
  4105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4106. ASSERT_TRUE(svr.is_valid());
  4107. svr.new_task_queue = [] { return new ThreadPool(1); };
  4108. std::atomic<int> reported{0};
  4109. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4110. if (err == Error::UserCallbackException) { reported++; }
  4111. });
  4112. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4113. res.set_content_provider(
  4114. 1024, "text/plain",
  4115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4116. sink.write("hello", 5);
  4117. throw std::runtime_error("from the content provider");
  4118. });
  4119. });
  4120. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4121. res.set_content("ok", "text/plain");
  4122. });
  4123. auto port = svr.bind_to_any_port(HOST);
  4124. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4125. auto se = detail::scope_exit([&] {
  4126. svr.stop();
  4127. listen_thread.join();
  4128. ASSERT_FALSE(svr.is_running());
  4129. });
  4130. svr.wait_until_ready();
  4131. {
  4132. SSLClient cli(HOST, port);
  4133. cli.enable_server_certificate_verification(false);
  4134. cli.set_read_timeout(5, 0);
  4135. EXPECT_FALSE(cli.Get("/throw"));
  4136. }
  4137. EXPECT_TRUE(svr.is_running());
  4138. EXPECT_EQ(1, reported.load());
  4139. {
  4140. SSLClient cli(HOST, port);
  4141. cli.enable_server_certificate_verification(false);
  4142. auto res = cli.Get("/ok");
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. EXPECT_EQ("ok", res->body);
  4146. }
  4147. }
  4148. #endif
  4149. #endif
  4150. TEST(NoContentTest, ContentLength) {
  4151. Server svr;
  4152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4153. res.status = StatusCode::NoContent_204;
  4154. });
  4155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. thread.join();
  4159. ASSERT_FALSE(svr.is_running());
  4160. });
  4161. svr.wait_until_ready();
  4162. {
  4163. Client cli(HOST, PORT);
  4164. auto res = cli.Get("/hi");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4167. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4168. }
  4169. }
  4170. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4171. #ifdef CPPHTTPLIB_SSL_ENABLED
  4172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4173. ASSERT_TRUE(svr.is_valid());
  4174. #else
  4175. Server svr;
  4176. #endif
  4177. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4178. if (req.path == "/routing_handler") {
  4179. res.set_header("PRE_ROUTING", "on");
  4180. res.set_content("Routing Handler", "text/plain");
  4181. return httplib::Server::HandlerResponse::Handled;
  4182. }
  4183. return httplib::Server::HandlerResponse::Unhandled;
  4184. });
  4185. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4186. res.set_content("Error", "text/html");
  4187. });
  4188. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4189. if (req.path == "/routing_handler") {
  4190. res.set_header("POST_ROUTING", "on");
  4191. }
  4192. });
  4193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4194. res.set_content("Hello World!\n", "text/plain");
  4195. });
  4196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. #ifdef CPPHTTPLIB_SSL_ENABLED
  4205. SSLClient cli(HOST, PORT);
  4206. cli.enable_server_certificate_verification(false);
  4207. #else
  4208. Client cli(HOST, PORT);
  4209. #endif
  4210. auto res = cli.Get("/routing_handler");
  4211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4212. EXPECT_EQ(StatusCode::OK_200, res->status);
  4213. EXPECT_EQ("Routing Handler", res->body);
  4214. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4215. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4216. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4217. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4218. }
  4219. {
  4220. #ifdef CPPHTTPLIB_SSL_ENABLED
  4221. SSLClient cli(HOST, PORT);
  4222. cli.enable_server_certificate_verification(false);
  4223. #else
  4224. Client cli(HOST, PORT);
  4225. #endif
  4226. auto res = cli.Get("/hi");
  4227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. EXPECT_EQ("Hello World!\n", res->body);
  4230. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4231. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4232. }
  4233. {
  4234. #ifdef CPPHTTPLIB_SSL_ENABLED
  4235. SSLClient cli(HOST, PORT);
  4236. cli.enable_server_certificate_verification(false);
  4237. #else
  4238. Client cli(HOST, PORT);
  4239. #endif
  4240. auto res = cli.Get("/aaa");
  4241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4243. EXPECT_EQ("Error", res->body);
  4244. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4245. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4246. }
  4247. }
  4248. TEST(RequestHandlerTest, PreRequestHandler) {
  4249. auto route_path = "/user/:user";
  4250. Server svr;
  4251. svr.Get("/hi", [](const Request &, Response &res) {
  4252. res.set_content("hi", "text/plain");
  4253. });
  4254. svr.Get(route_path, [](const Request &req, Response &res) {
  4255. res.set_content(req.path_params.at("user"), "text/plain");
  4256. });
  4257. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4258. if (req.matched_route == route_path) {
  4259. auto user = req.path_params.at("user");
  4260. if (user != "john") {
  4261. res.status = StatusCode::Forbidden_403;
  4262. res.set_content("error", "text/html");
  4263. return Server::HandlerResponse::Handled;
  4264. }
  4265. }
  4266. return Server::HandlerResponse::Unhandled;
  4267. });
  4268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4269. auto se = detail::scope_exit([&] {
  4270. svr.stop();
  4271. thread.join();
  4272. ASSERT_FALSE(svr.is_running());
  4273. });
  4274. svr.wait_until_ready();
  4275. Client cli(HOST, PORT);
  4276. {
  4277. auto res = cli.Get("/hi");
  4278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4279. EXPECT_EQ(StatusCode::OK_200, res->status);
  4280. EXPECT_EQ("hi", res->body);
  4281. }
  4282. {
  4283. auto res = cli.Get("/user/john");
  4284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4285. EXPECT_EQ(StatusCode::OK_200, res->status);
  4286. EXPECT_EQ("john", res->body);
  4287. }
  4288. {
  4289. auto res = cli.Get("/user/invalid-user");
  4290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4291. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4292. EXPECT_EQ("error", res->body);
  4293. }
  4294. }
  4295. // The pre-request handler must run before the request body is read, so a
  4296. // rejected request never forces the server to buffer a (potentially large)
  4297. // body. Here the posted body is larger than the payload limit: if the body
  4298. // were read first the server would answer 413, but because the pre-request
  4299. // handler runs first it answers 403 and the body is never read.
  4300. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4301. Server svr;
  4302. svr.set_payload_max_length(8);
  4303. auto handler_ran = false;
  4304. svr.Post("/reject", [&](const Request &req, Response &res) {
  4305. handler_ran = true;
  4306. res.set_content(req.body, "text/plain");
  4307. });
  4308. svr.Post("/accept", [](const Request &req, Response &res) {
  4309. res.set_content(req.body, "text/plain");
  4310. });
  4311. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4312. if (req.matched_route == "/reject") {
  4313. res.status = StatusCode::Forbidden_403;
  4314. res.set_content("denied", "text/plain");
  4315. return Server::HandlerResponse::Handled;
  4316. }
  4317. return Server::HandlerResponse::Unhandled;
  4318. });
  4319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. Client cli(HOST, PORT);
  4327. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4328. // rejects with 403 before the body is read, so 413 is never reached.
  4329. {
  4330. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4332. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4333. EXPECT_EQ("denied", res->body);
  4334. EXPECT_FALSE(handler_ran);
  4335. }
  4336. // An approved route still reads the body and enforces the payload limit.
  4337. {
  4338. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4341. }
  4342. }
  4343. TEST(UserDataTest, BasicOperations) {
  4344. httplib::UserData ud;
  4345. // Initially empty
  4346. EXPECT_FALSE(ud.has("key"));
  4347. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4348. // set and get
  4349. ud.set("key", 42);
  4350. EXPECT_TRUE(ud.has("key"));
  4351. auto *p = ud.get<int>("key");
  4352. ASSERT_NE(nullptr, p);
  4353. EXPECT_EQ(42, *p);
  4354. // Type mismatch → nullptr
  4355. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4356. // Overwrite with different type
  4357. ud.set("key", std::string("hello"));
  4358. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4359. auto *s = ud.get<std::string>("key");
  4360. ASSERT_NE(nullptr, s);
  4361. EXPECT_EQ("hello", *s);
  4362. // erase
  4363. ud.erase("key");
  4364. EXPECT_FALSE(ud.has("key"));
  4365. // clear
  4366. ud.set("a", 1);
  4367. ud.set("b", 2);
  4368. ud.clear();
  4369. EXPECT_FALSE(ud.has("a"));
  4370. EXPECT_FALSE(ud.has("b"));
  4371. }
  4372. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4373. struct AuthCtx {
  4374. std::string user_id;
  4375. };
  4376. Server svr;
  4377. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4378. res.user_data.set("auth", AuthCtx{"alice"});
  4379. return Server::HandlerResponse::Unhandled;
  4380. });
  4381. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4382. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4383. ASSERT_NE(nullptr, ctx);
  4384. res.set_content("Hello " + ctx->user_id, "text/plain");
  4385. });
  4386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4387. auto se = detail::scope_exit([&] {
  4388. svr.stop();
  4389. thread.join();
  4390. ASSERT_FALSE(svr.is_running());
  4391. });
  4392. svr.wait_until_ready();
  4393. Client cli(HOST, PORT);
  4394. auto res = cli.Get("/me");
  4395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("Hello alice", res->body);
  4398. }
  4399. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4400. struct RoleCtx {
  4401. std::string role;
  4402. };
  4403. Server svr;
  4404. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4405. res.user_data.set("role", RoleCtx{"admin"});
  4406. return Server::HandlerResponse::Unhandled;
  4407. });
  4408. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4409. auto *ctx = res.user_data.get<RoleCtx>("role");
  4410. ASSERT_NE(nullptr, ctx);
  4411. res.set_content(ctx->role, "text/plain");
  4412. });
  4413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4414. auto se = detail::scope_exit([&] {
  4415. svr.stop();
  4416. thread.join();
  4417. ASSERT_FALSE(svr.is_running());
  4418. });
  4419. svr.wait_until_ready();
  4420. Client cli(HOST, PORT);
  4421. auto res = cli.Get("/role");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ("admin", res->body);
  4425. }
  4426. TEST(InvalidFormatTest, StatusCode) {
  4427. Server svr;
  4428. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4429. res.set_content("Hello World!\n", "text/plain");
  4430. res.status = 9999; // Status should be a three-digit code...
  4431. });
  4432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4433. auto se = detail::scope_exit([&] {
  4434. svr.stop();
  4435. thread.join();
  4436. ASSERT_FALSE(svr.is_running());
  4437. });
  4438. svr.wait_until_ready();
  4439. {
  4440. Client cli(HOST, PORT);
  4441. auto res = cli.Get("/hi");
  4442. ASSERT_FALSE(res);
  4443. }
  4444. }
  4445. TEST(URLFragmentTest, WithFragment) {
  4446. Server svr;
  4447. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4448. EXPECT_TRUE(req.target == "/hi");
  4449. });
  4450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4451. auto se = detail::scope_exit([&] {
  4452. svr.stop();
  4453. thread.join();
  4454. ASSERT_FALSE(svr.is_running());
  4455. });
  4456. svr.wait_until_ready();
  4457. {
  4458. Client cli(HOST, PORT);
  4459. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4460. EXPECT_TRUE(res);
  4461. EXPECT_EQ(StatusCode::OK_200, res->status);
  4462. res = cli.Get("/hi%23key1=val1=key2=val2");
  4463. EXPECT_TRUE(res);
  4464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4465. }
  4466. }
  4467. TEST(HeaderWriter, SetHeaderWriter) {
  4468. Server svr;
  4469. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4470. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4471. return detail::write_headers(strm, hdrs);
  4472. });
  4473. svr.Get("/hi", [](const Request &req, Response &res) {
  4474. auto it = req.headers.find("CustomClientHeader");
  4475. EXPECT_TRUE(it != req.headers.end());
  4476. EXPECT_EQ(it->second, "CustomClientValue");
  4477. res.set_content("Hello World!\n", "text/plain");
  4478. });
  4479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4480. auto se = detail::scope_exit([&] {
  4481. svr.stop();
  4482. thread.join();
  4483. ASSERT_FALSE(svr.is_running());
  4484. });
  4485. svr.wait_until_ready();
  4486. {
  4487. Client cli(HOST, PORT);
  4488. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4489. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4490. return detail::write_headers(strm, hdrs);
  4491. });
  4492. auto res = cli.Get("/hi");
  4493. EXPECT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. auto it = res->headers.find("CustomServerHeader");
  4496. EXPECT_TRUE(it != res->headers.end());
  4497. EXPECT_EQ(it->second, "CustomServerValue");
  4498. }
  4499. }
  4500. class ServerTest : public ::testing::Test {
  4501. protected:
  4502. ServerTest()
  4503. : cli_(HOST, PORT)
  4504. #ifdef CPPHTTPLIB_SSL_ENABLED
  4505. ,
  4506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4507. #endif
  4508. {
  4509. #ifdef CPPHTTPLIB_SSL_ENABLED
  4510. cli_.enable_server_certificate_verification(false);
  4511. #endif
  4512. // Allow LARGE_DATA (100MB) responses
  4513. cli_.set_payload_max_length(200 * 1024 * 1024);
  4514. }
  4515. virtual void SetUp() {
  4516. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4517. svr_.set_payload_max_length(200 * 1024 * 1024);
  4518. svr_.set_mount_point("/", "./www");
  4519. svr_.set_mount_point("/mount", "./www2");
  4520. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4521. svr_.Get("/hi",
  4522. [&](const Request & /*req*/, Response &res) {
  4523. res.set_content("Hello World!", "text/plain");
  4524. })
  4525. .Get("/file_content",
  4526. [&](const Request & /*req*/, Response &res) {
  4527. res.set_file_content("./www/dir/test.html");
  4528. })
  4529. .Get("/file_content_with_content_type",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. res.set_file_content("./www/file", "text/plain");
  4532. })
  4533. .Get("/invalid_file_content",
  4534. [&](const Request & /*req*/, Response &res) {
  4535. res.set_file_content("./www/dir/invalid_file_path");
  4536. })
  4537. .Get("/http_response_splitting",
  4538. [&](const Request & /*req*/, Response &res) {
  4539. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4540. EXPECT_EQ(0U, res.headers.size());
  4541. EXPECT_FALSE(res.has_header("a"));
  4542. res.set_header("a", "1\nSet-Cookie: a=1");
  4543. EXPECT_EQ(0U, res.headers.size());
  4544. EXPECT_FALSE(res.has_header("a"));
  4545. res.set_header("a", "1\rSet-Cookie: a=1");
  4546. EXPECT_EQ(0U, res.headers.size());
  4547. EXPECT_FALSE(res.has_header("a"));
  4548. res.set_header("a\r\nb", "0");
  4549. EXPECT_EQ(0U, res.headers.size());
  4550. EXPECT_FALSE(res.has_header("a"));
  4551. res.set_header("a\rb", "0");
  4552. EXPECT_EQ(0U, res.headers.size());
  4553. EXPECT_FALSE(res.has_header("a"));
  4554. res.set_header("a\nb", "0");
  4555. EXPECT_EQ(0U, res.headers.size());
  4556. EXPECT_FALSE(res.has_header("a"));
  4557. res.set_redirect("1\r\nSet-Cookie: a=1");
  4558. EXPECT_EQ(0U, res.headers.size());
  4559. EXPECT_FALSE(res.has_header("Location"));
  4560. })
  4561. .Get("/slow",
  4562. [&](const Request & /*req*/, Response &res) {
  4563. std::this_thread::sleep_for(std::chrono::seconds(4));
  4564. res.set_content("slow", "text/plain");
  4565. })
  4566. #if 0
  4567. .Post("/slowpost",
  4568. [&](const Request & /*req*/, Response &res) {
  4569. std::this_thread::sleep_for(std::chrono::seconds(2));
  4570. res.set_content("slow", "text/plain");
  4571. })
  4572. #endif
  4573. .Get("/remote_addr",
  4574. [&](const Request &req, Response &res) {
  4575. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4576. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4577. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4579. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4580. #endif
  4581. res.set_content(req.remote_addr, "text/plain");
  4582. })
  4583. .Get("/local_addr",
  4584. [&](const Request &req, Response &res) {
  4585. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4586. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4587. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4589. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4590. #endif
  4591. auto local_addr = req.local_addr;
  4592. auto local_port = std::to_string(req.local_port);
  4593. res.set_content(local_addr.append(":").append(local_port),
  4594. "text/plain");
  4595. })
  4596. .Get("/endwith%",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. res.set_content("Hello World!", "text/plain");
  4599. })
  4600. .Get("/a\\+\\+b",
  4601. [&](const Request &req, Response &res) {
  4602. ASSERT_TRUE(req.has_param("a +b"));
  4603. auto val = req.get_param_value("a +b");
  4604. res.set_content(val, "text/plain");
  4605. })
  4606. .Get("/", [&](const Request & /*req*/,
  4607. Response &res) { res.set_redirect("/hi"); })
  4608. .Post("/1",
  4609. [](const Request & /*req*/, Response &res) {
  4610. res.set_redirect("/2", StatusCode::SeeOther_303);
  4611. })
  4612. .Get("/2",
  4613. [](const Request & /*req*/, Response &res) {
  4614. res.set_content("redirected.", "text/plain");
  4615. res.status = StatusCode::OK_200;
  4616. })
  4617. .Post("/person",
  4618. [&](const Request &req, Response &res) {
  4619. if (req.has_param("name") && req.has_param("note")) {
  4620. persons_[req.get_param_value("name")] =
  4621. req.get_param_value("note");
  4622. } else {
  4623. res.status = StatusCode::BadRequest_400;
  4624. }
  4625. })
  4626. .Put("/person",
  4627. [&](const Request &req, Response &res) {
  4628. if (req.has_param("name") && req.has_param("note")) {
  4629. persons_[req.get_param_value("name")] =
  4630. req.get_param_value("note");
  4631. } else {
  4632. res.status = StatusCode::BadRequest_400;
  4633. }
  4634. })
  4635. .Get("/person/(.*)",
  4636. [&](const Request &req, Response &res) {
  4637. string name = req.matches[1];
  4638. if (persons_.find(name) != persons_.end()) {
  4639. auto note = persons_[name];
  4640. res.set_content(note, "text/plain");
  4641. } else {
  4642. res.status = StatusCode::NotFound_404;
  4643. }
  4644. })
  4645. .Delete("/person",
  4646. [&](const Request &req, Response &res) {
  4647. if (req.has_param("name")) {
  4648. string name = req.get_param_value("name");
  4649. if (persons_.find(name) != persons_.end()) {
  4650. persons_.erase(name);
  4651. res.set_content("DELETED", "text/plain");
  4652. } else {
  4653. res.status = StatusCode::NotFound_404;
  4654. }
  4655. } else {
  4656. res.status = StatusCode::BadRequest_400;
  4657. }
  4658. })
  4659. .Post("/x-www-form-urlencoded-json",
  4660. [&](const Request &req, Response &res) {
  4661. auto json = req.get_param_value("json");
  4662. ASSERT_EQ(JSON_DATA, json);
  4663. res.set_content(json, "appliation/json");
  4664. res.status = StatusCode::OK_200;
  4665. })
  4666. .Get("/streamed-chunked",
  4667. [&](const Request & /*req*/, Response &res) {
  4668. res.set_chunked_content_provider(
  4669. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4670. sink.os << "123";
  4671. sink.os << "456";
  4672. sink.os << "789";
  4673. sink.done();
  4674. return true;
  4675. });
  4676. })
  4677. .Get("/streamed-chunked-with-prohibited-trailer",
  4678. [&](const Request & /*req*/, Response &res) {
  4679. auto i = new int(0);
  4680. // Declare both a prohibited trailer (Content-Length) and an
  4681. // allowed one
  4682. res.set_header("Trailer", "Content-Length, X-Allowed");
  4683. res.set_chunked_content_provider(
  4684. "text/plain",
  4685. [i](size_t /*offset*/, DataSink &sink) {
  4686. switch (*i) {
  4687. case 0: sink.os << "123"; break;
  4688. case 1: sink.os << "456"; break;
  4689. case 2: sink.os << "789"; break;
  4690. case 3: {
  4691. sink.done_with_trailer(
  4692. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4693. } break;
  4694. }
  4695. (*i)++;
  4696. return true;
  4697. },
  4698. [i](bool success) {
  4699. EXPECT_TRUE(success);
  4700. delete i;
  4701. });
  4702. })
  4703. .Get("/streamed-chunked2",
  4704. [&](const Request & /*req*/, Response &res) {
  4705. auto i = new int(0);
  4706. res.set_chunked_content_provider(
  4707. "text/plain",
  4708. [i](size_t /*offset*/, DataSink &sink) {
  4709. switch (*i) {
  4710. case 0: sink.os << "123"; break;
  4711. case 1: sink.os << "456"; break;
  4712. case 2: sink.os << "789"; break;
  4713. case 3: sink.done(); break;
  4714. }
  4715. (*i)++;
  4716. return true;
  4717. },
  4718. [i](bool success) {
  4719. EXPECT_TRUE(success);
  4720. delete i;
  4721. });
  4722. })
  4723. .Get("/streamed-chunked-with-trailer",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. auto i = new int(0);
  4726. res.set_header("Trailer", "Dummy1, Dummy2");
  4727. res.set_chunked_content_provider(
  4728. "text/plain",
  4729. [i](size_t /*offset*/, DataSink &sink) {
  4730. switch (*i) {
  4731. case 0: sink.os << "123"; break;
  4732. case 1: sink.os << "456"; break;
  4733. case 2: sink.os << "789"; break;
  4734. case 3: {
  4735. sink.done_with_trailer(
  4736. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4737. } break;
  4738. }
  4739. (*i)++;
  4740. return true;
  4741. },
  4742. [i](bool success) {
  4743. EXPECT_TRUE(success);
  4744. delete i;
  4745. });
  4746. })
  4747. .Get("/streamed",
  4748. [&](const Request & /*req*/, Response &res) {
  4749. res.set_content_provider(
  4750. 6, "text/plain",
  4751. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4752. sink.os << (offset < 3 ? "a" : "b");
  4753. return true;
  4754. });
  4755. })
  4756. .Get("/streamed-without-length",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. auto data = new std::string("abcdefg");
  4759. res.set_content_provider(
  4760. "text/plain",
  4761. [data](size_t offset, DataSink &sink) {
  4762. if (offset < data->size()) {
  4763. sink.os << data->substr(offset);
  4764. }
  4765. sink.done();
  4766. return true;
  4767. },
  4768. [data](bool success) {
  4769. EXPECT_TRUE(success);
  4770. delete data;
  4771. });
  4772. })
  4773. .Get("/streamed-with-range",
  4774. [&](const Request &req, Response &res) {
  4775. auto data = new std::string("abcdefg");
  4776. // An explicit status keeps the server from picking the 206 it
  4777. // would otherwise choose for a ranged request, so the response
  4778. // is not a partial representation.
  4779. auto status = req.get_param_value("status");
  4780. if (status == "200") {
  4781. res.status = StatusCode::OK_200;
  4782. } else if (status == "403") {
  4783. res.status = StatusCode::Forbidden_403;
  4784. }
  4785. res.set_content_provider(
  4786. data->size(), "text/plain",
  4787. [data](size_t offset, size_t length, DataSink &sink) {
  4788. size_t DATA_CHUNK_SIZE = 4;
  4789. const auto &d = *data;
  4790. auto out_len =
  4791. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4792. auto ret =
  4793. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4794. EXPECT_TRUE(ret);
  4795. return true;
  4796. },
  4797. [data, &req](bool success) {
  4798. EXPECT_EQ(success, !req.has_param("error"));
  4799. delete data;
  4800. });
  4801. })
  4802. .Get("/streamed-cancel",
  4803. [&](const Request & /*req*/, Response &res) {
  4804. res.set_content_provider(
  4805. size_t(-1), "text/plain",
  4806. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4807. sink.os << "data_chunk";
  4808. return true;
  4809. });
  4810. })
  4811. .Get("/regex-with-delimiter",
  4812. [&](const Request &req, Response & /*res*/) {
  4813. ASSERT_TRUE(req.has_param("key"));
  4814. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4815. })
  4816. .Get("/with-range",
  4817. [&](const Request & /*req*/, Response &res) {
  4818. res.set_content("abcdefg", "text/plain");
  4819. })
  4820. .Get("/test-start-time",
  4821. [&](const Request &req, Response & /*res*/) {
  4822. EXPECT_NE(req.start_time_,
  4823. std::chrono::steady_clock::time_point::min());
  4824. })
  4825. .Get("/with-range-customized-response",
  4826. [&](const Request & /*req*/, Response &res) {
  4827. res.status = StatusCode::BadRequest_400;
  4828. res.set_content(JSON_DATA, "application/json");
  4829. })
  4830. .Post("/chunked",
  4831. [&](const Request &req, Response & /*res*/) {
  4832. EXPECT_EQ(req.body, "dechunked post body");
  4833. })
  4834. .Post("/large-chunked",
  4835. [&](const Request &req, Response & /*res*/) {
  4836. std::string expected(6 * 30 * 1024u, 'a');
  4837. EXPECT_EQ(req.body, expected);
  4838. })
  4839. .Post("/multipart",
  4840. [&](const Request &req, Response & /*res*/) {
  4841. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4842. req.form.get_field_count("text2") +
  4843. req.form.get_field_count("file3") +
  4844. req.form.get_field_count("file4"));
  4845. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4846. req.form.get_file_count("file2"));
  4847. ASSERT_TRUE(!req.form.has_file("???"));
  4848. ASSERT_TRUE(!req.form.has_field("???"));
  4849. ASSERT_TRUE(req.body.empty());
  4850. {
  4851. const auto &text = req.form.get_field("text1");
  4852. EXPECT_EQ("text default", text);
  4853. }
  4854. {
  4855. const auto &text = req.form.get_field("text2");
  4856. EXPECT_EQ("aωb", text);
  4857. }
  4858. {
  4859. const auto &file = req.form.get_file("file1");
  4860. EXPECT_EQ("hello.txt", file.filename);
  4861. EXPECT_EQ("text/plain", file.content_type);
  4862. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4863. }
  4864. {
  4865. const auto &file = req.form.get_file("file2");
  4866. EXPECT_EQ("world.json", file.filename);
  4867. EXPECT_EQ("application/json", file.content_type);
  4868. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4869. }
  4870. {
  4871. const auto &text = req.form.get_field("file3");
  4872. EXPECT_EQ(0u, text.size());
  4873. }
  4874. {
  4875. const auto &text = req.form.get_field("file4");
  4876. EXPECT_EQ(0u, text.size());
  4877. }
  4878. })
  4879. .Post("/multipart/multi_file_values",
  4880. [&](const Request &req, Response & /*res*/) {
  4881. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4882. req.form.get_field_count("multi_text1"));
  4883. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4884. ASSERT_TRUE(!req.form.has_file("???"));
  4885. ASSERT_TRUE(!req.form.has_field("???"));
  4886. ASSERT_TRUE(req.body.empty());
  4887. {
  4888. const auto &text = req.form.get_field("text");
  4889. EXPECT_EQ("default text", text);
  4890. }
  4891. {
  4892. const auto &text1_values = req.form.get_fields("multi_text1");
  4893. EXPECT_EQ(2u, text1_values.size());
  4894. EXPECT_EQ("aaaaa", text1_values[0]);
  4895. EXPECT_EQ("bbbbb", text1_values[1]);
  4896. }
  4897. {
  4898. const auto &file1_values = req.form.get_files("multi_file1");
  4899. EXPECT_EQ(2u, file1_values.size());
  4900. auto file1 = file1_values[0];
  4901. EXPECT_EQ(file1.filename, "hello.txt");
  4902. EXPECT_EQ(file1.content_type, "text/plain");
  4903. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4904. auto file2 = file1_values[1];
  4905. EXPECT_EQ(file2.filename, "world.json");
  4906. EXPECT_EQ(file2.content_type, "application/json");
  4907. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4908. }
  4909. })
  4910. .Post("/empty",
  4911. [&](const Request &req, Response &res) {
  4912. EXPECT_EQ(req.body, "");
  4913. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4915. res.set_content("empty", "text/plain");
  4916. })
  4917. .Post("/empty-no-content-type",
  4918. [&](const Request &req, Response &res) {
  4919. EXPECT_EQ(req.body, "");
  4920. EXPECT_FALSE(req.has_header("Content-Type"));
  4921. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4922. res.set_content("empty-no-content-type", "text/plain");
  4923. })
  4924. .Post("/path-only",
  4925. [&](const Request &req, Response &res) {
  4926. EXPECT_EQ(req.body, "");
  4927. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4928. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4929. res.set_content("path-only", "text/plain");
  4930. })
  4931. .Post("/path-headers-only",
  4932. [&](const Request &req, Response &res) {
  4933. EXPECT_EQ(req.body, "");
  4934. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4935. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4936. EXPECT_EQ("world", req.get_header_value("hello"));
  4937. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4938. res.set_content("path-headers-only", "text/plain");
  4939. })
  4940. .Post("/post-large",
  4941. [&](const Request &req, Response &res) {
  4942. EXPECT_EQ(req.body, LARGE_DATA);
  4943. res.set_content(req.body, "text/plain");
  4944. })
  4945. .Post("/post-loopback",
  4946. [&](const Request &, Response &res,
  4947. ContentReader const &content_reader) {
  4948. std::string body;
  4949. content_reader([&](const char *data, size_t data_length) {
  4950. body.append(data, data_length);
  4951. return true;
  4952. });
  4953. res.set_content(body, "text/plain");
  4954. })
  4955. .Put("/put-loopback",
  4956. [&](const Request &, Response &res,
  4957. ContentReader const &content_reader) {
  4958. std::string body;
  4959. content_reader([&](const char *data, size_t data_length) {
  4960. body.append(data, data_length);
  4961. return true;
  4962. });
  4963. res.set_content(body, "text/plain");
  4964. })
  4965. .Patch("/patch-loopback",
  4966. [&](const Request &, Response &res,
  4967. ContentReader const &content_reader) {
  4968. std::string body;
  4969. content_reader([&](const char *data, size_t data_length) {
  4970. body.append(data, data_length);
  4971. return true;
  4972. });
  4973. res.set_content(body, "text/plain");
  4974. })
  4975. .Put("/empty-no-content-type",
  4976. [&](const Request &req, Response &res) {
  4977. EXPECT_EQ(req.body, "");
  4978. EXPECT_FALSE(req.has_header("Content-Type"));
  4979. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4980. res.set_content("empty-no-content-type", "text/plain");
  4981. })
  4982. .Put("/put",
  4983. [&](const Request &req, Response &res) {
  4984. EXPECT_EQ(req.body, "PUT");
  4985. res.set_content(req.body, "text/plain");
  4986. })
  4987. .Put("/put-large",
  4988. [&](const Request &req, Response &res) {
  4989. EXPECT_EQ(req.body, LARGE_DATA);
  4990. res.set_content(req.body, "text/plain");
  4991. })
  4992. .Patch("/patch",
  4993. [&](const Request &req, Response &res) {
  4994. EXPECT_EQ(req.body, "PATCH");
  4995. res.set_content(req.body, "text/plain");
  4996. })
  4997. .Delete("/delete",
  4998. [&](const Request & /*req*/, Response &res) {
  4999. res.set_content("DELETE", "text/plain");
  5000. })
  5001. .Delete("/delete-body",
  5002. [&](const Request &req, Response &res) {
  5003. EXPECT_EQ(req.body, "content");
  5004. res.set_content(req.body, "text/plain");
  5005. })
  5006. .Options(R"(\*)",
  5007. [&](const Request & /*req*/, Response &res) {
  5008. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5009. })
  5010. .CustomRoute("PROPFIND", "/dav/:id",
  5011. [&](const Request &req, Response &res) {
  5012. res.set_header("x-body-size",
  5013. std::to_string(req.body.size()));
  5014. res.set_header("x-matched-route", req.matched_route);
  5015. res.set_header("x-dav-id", req.path_params.at("id"));
  5016. res.status = StatusCode::MultiStatus_207;
  5017. res.set_content(req.body, "application/xml");
  5018. })
  5019. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5020. [&](const Request &req, Response &res) {
  5021. res.set_header("x-dav-match", req.matches[1]);
  5022. res.status = StatusCode::MultiStatus_207;
  5023. })
  5024. .CustomRoute("MKCOL", "/dav-mkcol",
  5025. [&](const Request &req, Response &res) {
  5026. EXPECT_TRUE(req.body.empty());
  5027. res.status = StatusCode::Created_201;
  5028. })
  5029. .CustomRoute(
  5030. "REPORT", "/dav-report",
  5031. [&](const Request & /*req*/, Response &res,
  5032. const ContentReader &content_reader) {
  5033. std::string body;
  5034. content_reader([&](const char *data, size_t data_length) {
  5035. body.append(data, data_length);
  5036. return true;
  5037. });
  5038. res.set_header("x-body-size", std::to_string(body.size()));
  5039. res.status = StatusCode::MultiStatus_207;
  5040. res.set_content(body, "application/xml");
  5041. })
  5042. .Get("/request-target",
  5043. [&](const Request &req, Response & /*res*/) {
  5044. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5045. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5046. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5047. })
  5048. .Get("/long-query-value",
  5049. [&](const Request &req, Response & /*res*/) {
  5050. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5051. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5052. })
  5053. .Get("/too-long-query-value",
  5054. [&](const Request &req, Response & /*res*/) {
  5055. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5056. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5057. })
  5058. .Get("/array-param",
  5059. [&](const Request &req, Response & /*res*/) {
  5060. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5061. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5062. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5063. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5064. })
  5065. .Get("/array-param-values",
  5066. [&](const Request &req, Response & /*res*/) {
  5067. auto values = req.get_param_values("array");
  5068. EXPECT_EQ(3u, values.size());
  5069. EXPECT_EQ("value1", values[0]);
  5070. EXPECT_EQ("value2", values[1]);
  5071. EXPECT_EQ("value3", values[2]);
  5072. auto empty = req.get_param_values("nonexistent");
  5073. EXPECT_TRUE(empty.empty());
  5074. })
  5075. .Post("/validate-no-multiple-headers",
  5076. [&](const Request &req, Response & /*res*/) {
  5077. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5078. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5079. })
  5080. .Post("/content_receiver",
  5081. [&](const Request &req, Response &res,
  5082. const ContentReader &content_reader) {
  5083. if (req.is_multipart_form_data()) {
  5084. std::vector<FormData> items;
  5085. content_reader(
  5086. [&](const FormData &file) {
  5087. items.push_back(file);
  5088. return true;
  5089. },
  5090. [&](const char *data, size_t data_length) {
  5091. items.back().content.append(data, data_length);
  5092. return true;
  5093. });
  5094. EXPECT_EQ(5u, items.size());
  5095. {
  5096. const auto &file = get_file_value(items, "text1");
  5097. EXPECT_TRUE(file.filename.empty());
  5098. EXPECT_EQ("text default", file.content);
  5099. }
  5100. {
  5101. const auto &file = get_file_value(items, "text2");
  5102. EXPECT_TRUE(file.filename.empty());
  5103. EXPECT_EQ("aωb", file.content);
  5104. }
  5105. {
  5106. const auto &file = get_file_value(items, "file1");
  5107. EXPECT_EQ("hello.txt", file.filename);
  5108. EXPECT_EQ("text/plain", file.content_type);
  5109. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5110. }
  5111. {
  5112. const auto &file = get_file_value(items, "file2");
  5113. EXPECT_EQ("world.json", file.filename);
  5114. EXPECT_EQ("application/json", file.content_type);
  5115. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5116. }
  5117. {
  5118. const auto &file = get_file_value(items, "file3");
  5119. EXPECT_TRUE(file.filename.empty());
  5120. EXPECT_EQ("application/octet-stream", file.content_type);
  5121. EXPECT_EQ(0u, file.content.size());
  5122. }
  5123. } else {
  5124. std::string body;
  5125. content_reader([&](const char *data, size_t data_length) {
  5126. EXPECT_EQ(7U, data_length);
  5127. body.append(data, data_length);
  5128. return true;
  5129. });
  5130. EXPECT_EQ(body, "content");
  5131. res.set_content(body, "text/plain");
  5132. }
  5133. })
  5134. .Put("/content_receiver",
  5135. [&](const Request & /*req*/, Response &res,
  5136. const ContentReader &content_reader) {
  5137. std::string body;
  5138. content_reader([&](const char *data, size_t data_length) {
  5139. body.append(data, data_length);
  5140. return true;
  5141. });
  5142. EXPECT_EQ(body, "content");
  5143. res.set_content(body, "text/plain");
  5144. })
  5145. .Patch("/content_receiver",
  5146. [&](const Request & /*req*/, Response &res,
  5147. const ContentReader &content_reader) {
  5148. std::string body;
  5149. content_reader([&](const char *data, size_t data_length) {
  5150. body.append(data, data_length);
  5151. return true;
  5152. });
  5153. EXPECT_EQ(body, "content");
  5154. res.set_content(body, "text/plain");
  5155. })
  5156. .Post("/query-string-and-body",
  5157. [&](const Request &req, Response & /*res*/) {
  5158. ASSERT_TRUE(req.has_param("key"));
  5159. EXPECT_EQ(req.get_param_value("key"), "value");
  5160. EXPECT_EQ(req.body, "content");
  5161. })
  5162. .Get("/last-request",
  5163. [&](const Request &req, Response & /*res*/) {
  5164. EXPECT_EQ("close", req.get_header_value("Connection"));
  5165. })
  5166. .Get(R"(/redirect/(\d+))",
  5167. [&](const Request &req, Response &res) {
  5168. auto num = std::stoi(req.matches[1]) + 1;
  5169. std::string url = "/redirect/" + std::to_string(num);
  5170. res.set_redirect(url);
  5171. })
  5172. .Post("/binary",
  5173. [&](const Request &req, Response &res) {
  5174. EXPECT_EQ(4U, req.body.size());
  5175. EXPECT_EQ("application/octet-stream",
  5176. req.get_header_value("Content-Type"));
  5177. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5178. res.set_content(req.body, "application/octet-stream");
  5179. })
  5180. .Put("/binary",
  5181. [&](const Request &req, Response &res) {
  5182. EXPECT_EQ(4U, req.body.size());
  5183. EXPECT_EQ("application/octet-stream",
  5184. req.get_header_value("Content-Type"));
  5185. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5186. res.set_content(req.body, "application/octet-stream");
  5187. })
  5188. .Patch("/binary",
  5189. [&](const Request &req, Response &res) {
  5190. EXPECT_EQ(4U, req.body.size());
  5191. EXPECT_EQ("application/octet-stream",
  5192. req.get_header_value("Content-Type"));
  5193. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5194. res.set_content(req.body, "application/octet-stream");
  5195. })
  5196. .Delete("/binary",
  5197. [&](const Request &req, Response &res) {
  5198. EXPECT_EQ(4U, req.body.size());
  5199. EXPECT_EQ("application/octet-stream",
  5200. req.get_header_value("Content-Type"));
  5201. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5202. res.set_content(req.body, "application/octet-stream");
  5203. })
  5204. .Get("/issue1772",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.status = 401;
  5207. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5208. })
  5209. .Delete("/issue609",
  5210. [](const httplib::Request &, httplib::Response &res,
  5211. const httplib::ContentReader &) {
  5212. res.set_content("ok", "text/plain");
  5213. })
  5214. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5215. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5216. .Get("/compress",
  5217. [&](const Request & /*req*/, Response &res) {
  5218. res.set_content(
  5219. "12345678901234567890123456789012345678901234567890123456789"
  5220. "01234567890123456789012345678901234567890",
  5221. "text/plain");
  5222. })
  5223. .Get("/compress-with-charset",
  5224. [&](const Request & /*req*/, Response &res) {
  5225. res.set_content(
  5226. "12345678901234567890123456789012345678901234567890123456789"
  5227. "01234567890123456789012345678901234567890",
  5228. "application/json; charset=utf-8");
  5229. })
  5230. .Get("/nocompress",
  5231. [&](const Request & /*req*/, Response &res) {
  5232. res.set_content(
  5233. "12345678901234567890123456789012345678901234567890123456789"
  5234. "01234567890123456789012345678901234567890",
  5235. "application/octet-stream");
  5236. })
  5237. .Post("/compress-multipart",
  5238. [&](const Request &req, Response & /*res*/) {
  5239. EXPECT_EQ(2u, req.form.fields.size());
  5240. ASSERT_TRUE(!req.form.has_field("???"));
  5241. {
  5242. const auto &text = req.form.get_field("key1");
  5243. EXPECT_EQ("test", text);
  5244. }
  5245. {
  5246. const auto &text = req.form.get_field("key2");
  5247. EXPECT_EQ("--abcdefg123", text);
  5248. }
  5249. })
  5250. #endif
  5251. ;
  5252. persons_["john"] = "programmer";
  5253. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5254. svr_.wait_until_ready();
  5255. }
  5256. virtual void TearDown() {
  5257. svr_.stop();
  5258. if (!request_threads_.empty()) {
  5259. std::this_thread::sleep_for(std::chrono::seconds(1));
  5260. for (auto &t : request_threads_) {
  5261. t.join();
  5262. }
  5263. }
  5264. t_.join();
  5265. }
  5266. map<string, string> persons_;
  5267. #ifdef CPPHTTPLIB_SSL_ENABLED
  5268. SSLClient cli_;
  5269. SSLServer svr_;
  5270. #else
  5271. Client cli_;
  5272. Server svr_;
  5273. #endif
  5274. thread t_;
  5275. std::vector<thread> request_threads_;
  5276. };
  5277. TEST_F(ServerTest, GetMethod200) {
  5278. auto res = cli_.Get("/hi");
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ("HTTP/1.1", res->version);
  5281. EXPECT_EQ(StatusCode::OK_200, res->status);
  5282. EXPECT_EQ("OK", res->reason);
  5283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. }
  5287. TEST_F(ServerTest, GetEmptyFile) {
  5288. auto res = cli_.Get("/empty_file");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5292. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5293. EXPECT_EQ("", res->body);
  5294. }
  5295. TEST_F(ServerTest, GetFileContent) {
  5296. auto res = cli_.Get("/file_content");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5300. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5301. EXPECT_EQ("test.html", res->body);
  5302. }
  5303. TEST_F(ServerTest, GetFileContentWithRange) {
  5304. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5307. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5308. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5309. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5310. EXPECT_EQ("est", res->body);
  5311. }
  5312. TEST_F(ServerTest, GetFileContentWithContentType) {
  5313. auto res = cli_.Get("/file_content_with_content_type");
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5317. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5318. EXPECT_EQ("file\n", res->body);
  5319. }
  5320. TEST_F(ServerTest, GetInvalidFileContent) {
  5321. auto res = cli_.Get("/invalid_file_content");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5324. }
  5325. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5326. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ("HTTP/1.1", res->version);
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5331. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5332. EXPECT_EQ("Hello World!", res->body);
  5333. }
  5334. TEST_F(ServerTest, GetMethod302) {
  5335. auto res = cli_.Get("/");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. EXPECT_EQ(StatusCode::Found_302, res->status);
  5338. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5339. }
  5340. TEST_F(ServerTest, GetMethod302Redirect) {
  5341. cli_.set_follow_location(true);
  5342. auto res = cli_.Get("/");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. EXPECT_EQ(StatusCode::OK_200, res->status);
  5345. EXPECT_EQ("Hello World!", res->body);
  5346. EXPECT_EQ("/hi", res->location);
  5347. }
  5348. TEST_F(ServerTest, GetMethod404) {
  5349. auto res = cli_.Get("/invalid");
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5352. }
  5353. TEST_F(ServerTest, HeadMethod200) {
  5354. auto res = cli_.Head("/hi");
  5355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_TRUE(res->body.empty());
  5359. }
  5360. TEST_F(ServerTest, HeadMethod200Static) {
  5361. auto res = cli_.Head("/mount/dir/index.html");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5366. EXPECT_TRUE(res->body.empty());
  5367. }
  5368. TEST_F(ServerTest, HeadMethod404) {
  5369. auto res = cli_.Head("/invalid");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5372. EXPECT_TRUE(res->body.empty());
  5373. }
  5374. TEST_F(ServerTest, GetMethodPersonJohn) {
  5375. auto res = cli_.Get("/person/john");
  5376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5377. EXPECT_EQ(StatusCode::OK_200, res->status);
  5378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("programmer", res->body);
  5380. }
  5381. TEST_F(ServerTest, PostMethod1) {
  5382. auto res = cli_.Get("/person/john1");
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5385. res = cli_.Post("/person", "name=john1&note=coder",
  5386. "application/x-www-form-urlencoded");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. res = cli_.Get("/person/john1");
  5390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5391. ASSERT_EQ(StatusCode::OK_200, res->status);
  5392. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5393. ASSERT_EQ("coder", res->body);
  5394. }
  5395. TEST_F(ServerTest, PostMethod2) {
  5396. auto res = cli_.Get("/person/john2");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5399. Params params;
  5400. params.emplace("name", "john2");
  5401. params.emplace("note", "coder");
  5402. res = cli_.Post("/person", params);
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. res = cli_.Get("/person/john2");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. ASSERT_EQ(StatusCode::OK_200, res->status);
  5408. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5409. ASSERT_EQ("coder", res->body);
  5410. }
  5411. TEST_F(ServerTest, PutMethod3) {
  5412. auto res = cli_.Get("/person/john3");
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5415. Params params;
  5416. params.emplace("name", "john3");
  5417. params.emplace("note", "coder");
  5418. res = cli_.Put("/person", params);
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. ASSERT_EQ(StatusCode::OK_200, res->status);
  5421. res = cli_.Get("/person/john3");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5425. ASSERT_EQ("coder", res->body);
  5426. }
  5427. TEST_F(ServerTest, DeleteMethod1) {
  5428. auto res = cli_.Get("/person/john4");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5431. Params params;
  5432. params.emplace("name", "john4");
  5433. params.emplace("note", "coder");
  5434. res = cli_.Post("/person", params);
  5435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5436. ASSERT_EQ(StatusCode::OK_200, res->status);
  5437. res = cli_.Get("/person/john4");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. ASSERT_EQ(StatusCode::OK_200, res->status);
  5440. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5441. ASSERT_EQ("coder", res->body);
  5442. Params delete_params;
  5443. delete_params.emplace("name", "john4");
  5444. res = cli_.Delete("/person", delete_params);
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. ASSERT_EQ(StatusCode::OK_200, res->status);
  5447. ASSERT_EQ("DELETED", res->body);
  5448. res = cli_.Get("/person/john4");
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5451. }
  5452. TEST_F(ServerTest, DeleteMethod2) {
  5453. auto res = cli_.Get("/person/john5");
  5454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5455. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5456. Params params;
  5457. params.emplace("name", "john5");
  5458. params.emplace("note", "developer");
  5459. res = cli_.Post("/person", params);
  5460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5461. ASSERT_EQ(StatusCode::OK_200, res->status);
  5462. res = cli_.Get("/person/john5");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. ASSERT_EQ(StatusCode::OK_200, res->status);
  5465. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5466. ASSERT_EQ("developer", res->body);
  5467. Params delete_params;
  5468. delete_params.emplace("name", "john5");
  5469. Headers headers;
  5470. headers.emplace("Custom-Header", "test-value");
  5471. res = cli_.Delete("/person", headers, delete_params);
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. ASSERT_EQ(StatusCode::OK_200, res->status);
  5474. ASSERT_EQ("DELETED", res->body);
  5475. res = cli_.Get("/person/john5");
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5478. }
  5479. TEST_F(ServerTest, DeleteMethod3) {
  5480. auto res = cli_.Get("/person/john6");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5483. Params params;
  5484. params.emplace("name", "john6");
  5485. params.emplace("note", "tester");
  5486. res = cli_.Post("/person", params);
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. res = cli_.Get("/person/john6");
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. ASSERT_EQ(StatusCode::OK_200, res->status);
  5492. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5493. ASSERT_EQ("tester", res->body);
  5494. Params delete_params;
  5495. delete_params.emplace("name", "john6");
  5496. Headers headers;
  5497. headers.emplace("Custom-Header", "test-value");
  5498. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5500. ASSERT_EQ(StatusCode::OK_200, res->status);
  5501. ASSERT_EQ("DELETED", res->body);
  5502. res = cli_.Get("/person/john6");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5505. }
  5506. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5507. Params params;
  5508. params.emplace("json", JSON_DATA);
  5509. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. ASSERT_EQ(StatusCode::OK_200, res->status);
  5512. ASSERT_EQ(JSON_DATA, res->body);
  5513. }
  5514. TEST_F(ServerTest, PostEmptyContent) {
  5515. auto res = cli_.Post("/empty", "", "text/plain");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. ASSERT_EQ(StatusCode::OK_200, res->status);
  5518. ASSERT_EQ("empty", res->body);
  5519. }
  5520. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5521. auto res = cli_.Post("/empty-no-content-type");
  5522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5523. ASSERT_EQ(StatusCode::OK_200, res->status);
  5524. ASSERT_EQ("empty-no-content-type", res->body);
  5525. }
  5526. TEST_F(ServerTest, PostPathOnly) {
  5527. auto res = cli_.Post("/path-only");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. ASSERT_EQ(StatusCode::OK_200, res->status);
  5530. ASSERT_EQ("path-only", res->body);
  5531. }
  5532. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5533. auto res = cli_.Post("/path-headers-only",
  5534. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. ASSERT_EQ(StatusCode::OK_200, res->status);
  5537. ASSERT_EQ("path-headers-only", res->body);
  5538. }
  5539. TEST_F(ServerTest, PostLarge) {
  5540. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. ASSERT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ(LARGE_DATA, res->body);
  5544. }
  5545. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5546. auto res = cli_.Put("/empty-no-content-type");
  5547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5548. ASSERT_EQ(StatusCode::OK_200, res->status);
  5549. ASSERT_EQ("empty-no-content-type", res->body);
  5550. }
  5551. TEST_F(ServerTest, GetMethodDir) {
  5552. auto res = cli_.Get("/dir/");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5556. auto body = R"(<html>
  5557. <head>
  5558. </head>
  5559. <body>
  5560. <a href="/dir/test.html">Test</a>
  5561. <a href="/hi">hi</a>
  5562. </body>
  5563. </html>
  5564. )";
  5565. EXPECT_EQ(body, res->body);
  5566. }
  5567. TEST_F(ServerTest, GetMethodDirTest) {
  5568. auto res = cli_.Get("/dir/test.html");
  5569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5570. EXPECT_EQ(StatusCode::OK_200, res->status);
  5571. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5572. EXPECT_EQ("test.html", res->body);
  5573. }
  5574. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5575. auto res = cli_.Get("/dir/../dir/test.html");
  5576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5579. EXPECT_EQ("test.html", res->body);
  5580. }
  5581. TEST_F(ServerTest, GetMethodInvalidPath) {
  5582. auto res = cli_.Get("/dir/../test.html");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5585. }
  5586. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5587. auto res = cli_.Get("/../www/dir/test.html");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5590. }
  5591. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5592. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5595. }
  5596. TEST_F(ServerTest, GetMethodDirMountTest) {
  5597. auto res = cli_.Get("/mount/dir/test.html");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. EXPECT_EQ(StatusCode::OK_200, res->status);
  5600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5601. EXPECT_EQ("test.html", res->body);
  5602. }
  5603. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5604. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5608. EXPECT_EQ("test.html", res->body);
  5609. }
  5610. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5611. auto res = cli_.Get("/mount/dir/../test.html");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5614. }
  5615. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5616. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5619. }
  5620. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5621. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5624. }
  5625. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5626. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5629. }
  5630. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5631. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5634. }
  5635. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5636. auto res = cli_.Get("/mount/dir");
  5637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5638. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5639. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5640. }
  5641. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5642. auto res = cli_.Get("//dir");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5645. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5646. }
  5647. TEST_F(ServerTest, PostMethod303) {
  5648. auto res = cli_.Post("/1", "body", "text/plain");
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5651. EXPECT_EQ("/2", res->get_header_value("Location"));
  5652. }
  5653. TEST_F(ServerTest, PostMethod303Redirect) {
  5654. cli_.set_follow_location(true);
  5655. auto res = cli_.Post("/1", "body", "text/plain");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. EXPECT_EQ("redirected.", res->body);
  5659. EXPECT_EQ("/2", res->location);
  5660. }
  5661. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5662. auto res = cli_.Get("/dir/test.abcde");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. EXPECT_EQ(StatusCode::OK_200, res->status);
  5665. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5666. EXPECT_EQ("abcde", res->body);
  5667. }
  5668. TEST_F(ServerTest, StaticFileRange) {
  5669. auto res =
  5670. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5673. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5674. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5675. EXPECT_EQ(true, res->has_header("Content-Range"));
  5676. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5677. EXPECT_EQ(std::string("cd"), res->body);
  5678. }
  5679. TEST_F(ServerTest, StaticFileRanges) {
  5680. auto res = cli_.Get("/dir/test.abcde",
  5681. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5684. EXPECT_TRUE(
  5685. res->get_header_value("Content-Type")
  5686. .find(
  5687. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5688. 0);
  5689. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5690. }
  5691. TEST_F(ServerTest, StaticFileRangeHead) {
  5692. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5695. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5696. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5697. EXPECT_EQ(true, res->has_header("Content-Range"));
  5698. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5699. }
  5700. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5701. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5705. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5706. EXPECT_EQ(true, res->has_header("Content-Range"));
  5707. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5708. res->get_header_value("Content-Range"));
  5709. EXPECT_EQ("LAST\n", res->body);
  5710. }
  5711. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5712. auto res =
  5713. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5717. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5718. EXPECT_EQ(true, res->has_header("Content-Range"));
  5719. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5720. }
  5721. TEST_F(ServerTest, StaticFileBigFile) {
  5722. auto res = cli_.Get("/dir/1MB.txt");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::OK_200, res->status);
  5725. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5726. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5727. }
  5728. TEST_F(ServerTest, InvalidBaseDirMount) {
  5729. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5730. }
  5731. TEST_F(ServerTest, Binary) {
  5732. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5733. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5734. "application/octet-stream");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. ASSERT_EQ(StatusCode::OK_200, res->status);
  5737. ASSERT_EQ(4U, res->body.size());
  5738. res = cli_.Put("/binary", binary.data(), binary.size(),
  5739. "application/octet-stream");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. ASSERT_EQ(StatusCode::OK_200, res->status);
  5742. ASSERT_EQ(4U, res->body.size());
  5743. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5744. "application/octet-stream");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ(4U, res->body.size());
  5748. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5749. "application/octet-stream");
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. ASSERT_EQ(StatusCode::OK_200, res->status);
  5752. ASSERT_EQ(4U, res->body.size());
  5753. }
  5754. TEST_F(ServerTest, BinaryString) {
  5755. auto binary = std::string("\x00\x01\x02\x03", 4);
  5756. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::OK_200, res->status);
  5759. ASSERT_EQ(4U, res->body.size());
  5760. res = cli_.Put("/binary", binary, "application/octet-stream");
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. ASSERT_EQ(StatusCode::OK_200, res->status);
  5763. ASSERT_EQ(4U, res->body.size());
  5764. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. ASSERT_EQ(StatusCode::OK_200, res->status);
  5767. ASSERT_EQ(4U, res->body.size());
  5768. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. ASSERT_EQ(StatusCode::OK_200, res->status);
  5771. ASSERT_EQ(4U, res->body.size());
  5772. }
  5773. TEST_F(ServerTest, EmptyRequest) {
  5774. auto res = cli_.Get("");
  5775. ASSERT_TRUE(!res);
  5776. EXPECT_EQ(Error::Connection, res.error());
  5777. }
  5778. TEST_F(ServerTest, LongRequest) {
  5779. std::string request;
  5780. for (size_t i = 0; i < 545; i++) {
  5781. request += "/TooLongRequest";
  5782. }
  5783. request += "OK";
  5784. auto res = cli_.Get(request.c_str());
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5787. }
  5788. TEST_F(ServerTest, TooLongRequest) {
  5789. std::string request;
  5790. for (size_t i = 0; i < 546; i++) {
  5791. request += "/TooLongRequest";
  5792. }
  5793. request += "_NG";
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(request.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, AlmostTooLongRequest) {
  5808. // test for #2046 - URI length check shouldn't include other content on req
  5809. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5810. // leading /, space, HTTP/1.1)
  5811. std::string request =
  5812. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5813. auto res = cli_.Get(request.c_str());
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5816. }
  5817. TEST_F(ServerTest, LongHeader) {
  5818. Request req;
  5819. req.method = "GET";
  5820. req.path = "/hi";
  5821. std::string host_and_port;
  5822. host_and_port += HOST;
  5823. host_and_port += ":";
  5824. host_and_port += std::to_string(PORT);
  5825. req.headers.emplace("Host", host_and_port.c_str());
  5826. req.headers.emplace("Accept", "*/*");
  5827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5828. req.headers.emplace(
  5829. "Header-Name",
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5858. "@@@@@@@@@@@@@@@@");
  5859. auto res = std::make_shared<Response>();
  5860. auto error = Error::Success;
  5861. auto ret = cli_.send(req, *res, error);
  5862. ASSERT_TRUE(ret);
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. }
  5865. TEST_F(ServerTest, LongQueryValue) {
  5866. auto start = std::chrono::high_resolution_clock::now();
  5867. cli_.set_keep_alive(true);
  5868. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5869. auto end = std::chrono::high_resolution_clock::now();
  5870. auto elapsed =
  5871. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5872. .count();
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5875. EXPECT_LE(elapsed, 1000);
  5876. EXPECT_EQ("close", res->get_header_value("Connection"));
  5877. EXPECT_FALSE(cli_.is_socket_open());
  5878. }
  5879. TEST_F(ServerTest, TooLongQueryValue) {
  5880. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5881. ASSERT_FALSE(res);
  5882. EXPECT_EQ(Error::Read, res.error());
  5883. }
  5884. TEST_F(ServerTest, TooLongHeader) {
  5885. Request req;
  5886. req.method = "GET";
  5887. req.path = "/hi";
  5888. std::string host_and_port;
  5889. host_and_port += HOST;
  5890. host_and_port += ":";
  5891. host_and_port += std::to_string(PORT);
  5892. req.headers.emplace("Host", host_and_port.c_str());
  5893. req.headers.emplace("Accept", "*/*");
  5894. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5895. req.headers.emplace(
  5896. "Header-Name",
  5897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5925. "@@@@@@@@@@@@@@@@@");
  5926. auto res = std::make_shared<Response>();
  5927. auto error = Error::Success;
  5928. auto ret = cli_.send(req, *res, error);
  5929. ASSERT_TRUE(ret);
  5930. EXPECT_EQ(StatusCode::OK_200, res->status);
  5931. }
  5932. TEST_F(ServerTest, HeaderCountAtLimit) {
  5933. // Test with headers just under the 100 limit
  5934. httplib::Headers headers;
  5935. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5936. // This should keep us just under the 100 header limit
  5937. for (int i = 0; i < 95; i++) {
  5938. std::string name = "X-Test-Header-" + std::to_string(i);
  5939. std::string value = "value" + std::to_string(i);
  5940. headers.emplace(name, value);
  5941. }
  5942. // This should work fine as we're under the limit
  5943. auto res = cli_.Get("/hi", headers);
  5944. EXPECT_TRUE(res);
  5945. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5946. }
  5947. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5948. // Test with many headers to exceed the 100 limit
  5949. httplib::Headers headers;
  5950. // Add 150 headers to definitely exceed the 100 limit
  5951. for (int i = 0; i < 150; i++) {
  5952. std::string name = "X-Test-Header-" + std::to_string(i);
  5953. std::string value = "value" + std::to_string(i);
  5954. headers.emplace(name, value);
  5955. }
  5956. // This should fail due to exceeding header count limit
  5957. cli_.set_keep_alive(true);
  5958. auto res = cli_.Get("/hi", headers);
  5959. // The server should respond with 400 Bad Request
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5962. EXPECT_EQ("close", res->get_header_value("Connection"));
  5963. EXPECT_FALSE(cli_.is_socket_open());
  5964. }
  5965. TEST_F(ServerTest, PercentEncoding) {
  5966. auto res = cli_.Get("/e%6edwith%");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. }
  5970. TEST_F(ServerTest, PercentEncodingUnicode) {
  5971. auto res = cli_.Get("/e%u006edwith%");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. }
  5975. TEST_F(ServerTest, InvalidPercentEncoding) {
  5976. auto res = cli_.Get("/%endwith%");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5979. }
  5980. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5981. auto res = cli_.Get("/%uendwith%");
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5984. }
  5985. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5986. auto res = cli_.Get("/hello?aaa=bbb%");
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5989. }
  5990. TEST_F(ServerTest, PlusSignEncoding) {
  5991. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::OK_200, res->status);
  5994. EXPECT_EQ("a +b", res->body);
  5995. }
  5996. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5997. // This test simulates a potential DoS attack using many headers
  5998. // to verify our security fix prevents memory exhaustion
  5999. httplib::Headers attack_headers;
  6000. // Attempt to add many headers like an attacker would (200 headers to far
  6001. // exceed limit)
  6002. for (int i = 0; i < 200; i++) {
  6003. std::string name = "X-Attack-Header-" + std::to_string(i);
  6004. std::string value = "attack_payload_" + std::to_string(i);
  6005. attack_headers.emplace(name, value);
  6006. }
  6007. // Try to POST with excessive headers
  6008. cli_.set_keep_alive(true);
  6009. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6010. // Should either fail or return 400 Bad Request due to security limit
  6011. if (res) {
  6012. // If we get a response, it should be 400 Bad Request
  6013. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6014. EXPECT_EQ("close", res->get_header_value("Connection"));
  6015. }
  6016. EXPECT_FALSE(cli_.is_socket_open());
  6017. }
  6018. TEST_F(ServerTest, MultipartFormData) {
  6019. UploadFormDataItems items = {
  6020. {"text1", "text default", "", ""},
  6021. {"text2", "aωb", "", ""},
  6022. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6023. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6024. {"file3", "", "", "application/octet-stream"},
  6025. {"file4", "", "", " application/json tmp-string "}};
  6026. auto res = cli_.Post("/multipart", items);
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::OK_200, res->status);
  6029. }
  6030. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6031. UploadFormDataItems items = {
  6032. {"text", "default text", "", ""},
  6033. {"multi_text1", "aaaaa", "", ""},
  6034. {"multi_text1", "bbbbb", "", ""},
  6035. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6036. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6037. "application/json"},
  6038. };
  6039. auto res = cli_.Post("/multipart/multi_file_values", items);
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. }
  6043. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6044. auto res = cli_.Get("/hi");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6048. EXPECT_EQ("Hello World!", res->body);
  6049. }
  6050. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6051. Request req;
  6052. req.method = "POST";
  6053. req.path = "/chunked";
  6054. std::string host_and_port;
  6055. host_and_port += HOST;
  6056. host_and_port += ":";
  6057. host_and_port += std::to_string(PORT);
  6058. req.headers.emplace("Host", host_and_port.c_str());
  6059. req.headers.emplace("Accept", "*/*");
  6060. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6061. req.headers.emplace("Content-Type", "text/plain");
  6062. req.headers.emplace("Content-Length", "0");
  6063. req.headers.emplace(
  6064. "Transfer-Encoding",
  6065. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6066. // Client does not chunk, so make a chunked body manually.
  6067. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6068. auto res = std::make_shared<Response>();
  6069. auto error = Error::Success;
  6070. auto ret = cli_.send(req, *res, error);
  6071. ASSERT_TRUE(ret);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. }
  6074. template <typename ClientT>
  6075. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6076. int expected_status) {
  6077. Request req;
  6078. req.method = "POST";
  6079. req.path = "/chunked";
  6080. std::string host_and_port;
  6081. host_and_port += HOST;
  6082. host_and_port += ":";
  6083. host_and_port += std::to_string(PORT);
  6084. req.headers.emplace("Host", host_and_port.c_str());
  6085. req.headers.emplace("Content-Length", "0");
  6086. req.headers.emplace("Transfer-Encoding", "chunked");
  6087. req.body = body;
  6088. auto res = std::make_shared<Response>();
  6089. auto error = Error::Success;
  6090. ASSERT_TRUE(cli.send(req, *res, error));
  6091. EXPECT_EQ(expected_status, res->status);
  6092. }
  6093. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6094. // rather than treat them as valid lengths.
  6095. template <typename ClientT>
  6096. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6097. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6098. }
  6099. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6100. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6101. }
  6102. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6103. expect_chunked_body_rejected(
  6104. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6105. }
  6106. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6107. // chunk-size line carries no CR, LF or other control character ahead of its
  6108. // terminator. Such a line must be refused rather than read as extension text.
  6109. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6110. expect_chunked_body_rejected(
  6111. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6112. }
  6113. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6114. expect_chunked_body_rejected(
  6115. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6116. }
  6117. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6118. expect_chunked_body_rejected(
  6119. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6120. }
  6121. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6122. // The literal stays split: a hex escape consumes every hex digit that
  6123. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6124. expect_chunked_body_rejected(
  6125. cli_, "4;a\x01"
  6126. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6127. }
  6128. TEST_F(ServerTest, AcceptsChunkExtension) {
  6129. expect_chunked_body_status(cli_,
  6130. "4;name=value\r\ndech\r\n"
  6131. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6132. "0;last\r\n\r\n",
  6133. StatusCode::OK_200);
  6134. }
  6135. TEST_F(ServerTest, GetStreamed2) {
  6136. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6139. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6140. EXPECT_EQ(true, res->has_header("Content-Range"));
  6141. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6142. EXPECT_EQ(std::string("ab"), res->body);
  6143. }
  6144. TEST_F(ServerTest, GetStreamed) {
  6145. auto res = cli_.Get("/streamed");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. EXPECT_EQ(StatusCode::OK_200, res->status);
  6148. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6149. EXPECT_EQ(std::string("aaabbb"), res->body);
  6150. }
  6151. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6152. auto res = cli_.Get("/streamed-without-length",
  6153. Headers{make_range_header({{0, -1}})});
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ(false, res->has_header("Content-Length"));
  6157. EXPECT_EQ(false, res->has_header("Content-Range"));
  6158. EXPECT_EQ(std::string("abcdefg"), res->body);
  6159. }
  6160. TEST_F(ServerTest, GetStreamedWithRange1) {
  6161. auto res =
  6162. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6165. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(true, res->has_header("Content-Range"));
  6167. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6168. EXPECT_EQ(std::string("def"), res->body);
  6169. }
  6170. TEST_F(ServerTest, GetStreamedWithRange2) {
  6171. auto res =
  6172. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6176. EXPECT_EQ(true, res->has_header("Content-Range"));
  6177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6178. EXPECT_EQ(std::string("bcdefg"), res->body);
  6179. }
  6180. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6181. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6184. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6185. EXPECT_EQ(true, res->has_header("Content-Range"));
  6186. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6187. EXPECT_EQ(std::string("efg"), res->body);
  6188. }
  6189. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6190. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6191. // the entire representation.
  6192. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6193. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6196. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6197. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6198. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6199. }
  6200. }
  6201. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6202. auto res =
  6203. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6206. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6207. EXPECT_EQ(false, res->has_header("Content-Range"));
  6208. EXPECT_EQ(0U, res->body.size());
  6209. }
  6210. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6211. // Only a 206 is served as a partial representation. Under any other status
  6212. // `apply_ranges()` reported the full content length, so the body must match
  6213. // that header, and the content provider must never be asked for an offset
  6214. // outside the representation.
  6215. auto check = [&](int status, const char *range) {
  6216. auto path =
  6217. std::string("/streamed-with-range?status=") + std::to_string(status);
  6218. auto ctx = path + " Range: " + range;
  6219. auto res = cli_.Get(path, Headers{{"Range", range}});
  6220. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6221. EXPECT_EQ(status, res->status) << ctx;
  6222. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6224. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6225. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6226. };
  6227. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6228. check(403, "bytes=3-5");
  6229. // The offset is far past the representation.
  6230. check(403, "bytes=100000-100200");
  6231. // `first_pos` is still -1 here, and the bounds asserts in
  6232. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6233. check(403, "bytes=-3");
  6234. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6235. // multipart branch would have written one that is empty.
  6236. check(403, "bytes=1-2, 4-5");
  6237. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6238. // covers the whole representation.
  6239. check(200, "bytes=3-5");
  6240. check(200, "bytes=1-2, 4-5");
  6241. }
  6242. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6243. auto res =
  6244. cli_.Get("/streamed-with-range",
  6245. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6246. "92233720368547758079223372036854775807"}});
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6249. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6250. EXPECT_EQ(false, res->has_header("Content-Range"));
  6251. EXPECT_EQ(0U, res->body.size());
  6252. }
  6253. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6254. auto res = cli_.Get(
  6255. "/with-range",
  6256. Headers{{"Range",
  6257. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6258. {"Accept-Encoding", ""}});
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6261. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6262. EXPECT_EQ(true, res->has_header("Content-Range"));
  6263. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6264. EXPECT_EQ(std::string("abcdefg"), res->body);
  6265. }
  6266. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6267. auto res = cli_.Get("/with-range", Headers{
  6268. {"Range", "bytes=0-"},
  6269. {"Accept-Encoding", ""},
  6270. });
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6274. EXPECT_EQ(true, res->has_header("Content-Range"));
  6275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6276. EXPECT_EQ(std::string("abcdefg"), res->body);
  6277. }
  6278. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6279. auto res = cli_.Get("/streamed-with-range",
  6280. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6283. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6284. EXPECT_EQ(false, res->has_header("Content-Range"));
  6285. EXPECT_EQ(267U, res->body.size());
  6286. // Check that both range contents are present
  6287. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6288. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6289. // Check that Content-Range headers are present for both ranges
  6290. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6291. std::string::npos);
  6292. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6293. std::string::npos);
  6294. }
  6295. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6296. Ranges ranges;
  6297. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6298. ranges.emplace_back(0, -1);
  6299. }
  6300. auto res = cli_.Get("/streamed-with-range?error",
  6301. Headers{{make_range_header(ranges)}});
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6304. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6305. EXPECT_EQ(false, res->has_header("Content-Range"));
  6306. EXPECT_EQ(0U, res->body.size());
  6307. }
  6308. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6309. auto res = cli_.Get("/streamed-with-range",
  6310. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6313. EXPECT_EQ(5U, res->body.size());
  6314. // Check that overlapping ranges are coalesced into a single range
  6315. EXPECT_EQ("bcdef", res->body);
  6316. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6317. // Should be single range, not multipart
  6318. EXPECT_TRUE(res->has_header("Content-Range"));
  6319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6320. }
  6321. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6322. auto res = cli_.Get("/streamed-with-range",
  6323. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6326. EXPECT_EQ(268U, res->body.size());
  6327. // Check that both range contents are present
  6328. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6329. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6330. // Check that Content-Range headers are present for both ranges
  6331. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6332. std::string::npos);
  6333. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6334. std::string::npos);
  6335. }
  6336. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6337. auto res = cli_.Get("/streamed-with-range",
  6338. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6341. EXPECT_EQ(269U, res->body.size());
  6342. // Check that both duplicate range contents are present
  6343. size_t first_abc = res->body.find("abc\r\n");
  6344. EXPECT_TRUE(first_abc != std::string::npos);
  6345. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6346. EXPECT_TRUE(second_abc != std::string::npos);
  6347. // Check that Content-Range headers are present for both ranges
  6348. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6349. EXPECT_TRUE(first_range != std::string::npos);
  6350. size_t second_range =
  6351. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6352. EXPECT_TRUE(second_range != std::string::npos);
  6353. }
  6354. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6355. auto res =
  6356. cli_.Get("/streamed-with-range?error",
  6357. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6360. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6361. EXPECT_EQ(false, res->has_header("Content-Range"));
  6362. EXPECT_EQ(0U, res->body.size());
  6363. }
  6364. TEST_F(ServerTest, GetStreamedEndless) {
  6365. uint64_t offset = 0;
  6366. auto res = cli_.Get("/streamed-cancel",
  6367. [&](const char * /*data*/, uint64_t data_length) {
  6368. if (offset < 100) {
  6369. offset += data_length;
  6370. return true;
  6371. }
  6372. return false;
  6373. });
  6374. ASSERT_TRUE(!res);
  6375. EXPECT_EQ(Error::Canceled, res.error());
  6376. }
  6377. TEST_F(ServerTest, ClientStop) {
  6378. std::atomic_size_t count{4};
  6379. std::vector<std::thread> threads;
  6380. for (auto i = count.load(); i != 0; --i) {
  6381. threads.emplace_back([&]() {
  6382. auto res = cli_.Get("/streamed-cancel",
  6383. [&](const char *, uint64_t) { return true; });
  6384. --count;
  6385. ASSERT_TRUE(!res);
  6386. EXPECT_TRUE(res.error() == Error::Canceled ||
  6387. res.error() == Error::Read || res.error() == Error::Write);
  6388. });
  6389. }
  6390. std::this_thread::sleep_for(std::chrono::seconds(2));
  6391. while (count != 0) {
  6392. cli_.stop();
  6393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6394. }
  6395. for (auto &t : threads) {
  6396. t.join();
  6397. }
  6398. }
  6399. TEST_F(ServerTest, GetWithRange1) {
  6400. auto res = cli_.Get("/with-range", Headers{
  6401. make_range_header({{3, 5}}),
  6402. {"Accept-Encoding", ""},
  6403. });
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6406. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6407. EXPECT_EQ(true, res->has_header("Content-Range"));
  6408. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6409. EXPECT_EQ(std::string("def"), res->body);
  6410. }
  6411. TEST_F(ServerTest, GetWithRange2) {
  6412. auto res = cli_.Get("/with-range", Headers{
  6413. make_range_header({{1, -1}}),
  6414. {"Accept-Encoding", ""},
  6415. });
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6419. EXPECT_EQ(true, res->has_header("Content-Range"));
  6420. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6421. EXPECT_EQ(std::string("bcdefg"), res->body);
  6422. }
  6423. TEST_F(ServerTest, GetWithRange3) {
  6424. auto res = cli_.Get("/with-range", Headers{
  6425. make_range_header({{0, 0}}),
  6426. {"Accept-Encoding", ""},
  6427. });
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6430. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6431. EXPECT_EQ(true, res->has_header("Content-Range"));
  6432. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6433. EXPECT_EQ(std::string("a"), res->body);
  6434. }
  6435. TEST_F(ServerTest, GetWithRange4) {
  6436. auto res = cli_.Get("/with-range", Headers{
  6437. make_range_header({{-1, 2}}),
  6438. {"Accept-Encoding", ""},
  6439. });
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(true, res->has_header("Content-Range"));
  6444. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(std::string("fg"), res->body);
  6446. }
  6447. TEST_F(ServerTest, GetWithRange5) {
  6448. auto res = cli_.Get("/with-range", Headers{
  6449. make_range_header({{0, 5}}),
  6450. {"Accept-Encoding", ""},
  6451. });
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6454. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6455. EXPECT_EQ(true, res->has_header("Content-Range"));
  6456. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6457. EXPECT_EQ(std::string("abcdef"), res->body);
  6458. }
  6459. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6460. auto res =
  6461. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6464. }
  6465. TEST_F(ServerTest, GetWithRangeMultipart) {
  6466. auto res =
  6467. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6470. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6471. EXPECT_EQ(false, res->has_header("Content-Range"));
  6472. EXPECT_EQ(267U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6475. auto res = cli_.Get("/with-range",
  6476. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6479. }
  6480. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6481. auto res = cli_.Get("/with-range-customized-response",
  6482. Headers{{make_range_header({{1, 2}})}});
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6485. EXPECT_EQ(true, res->has_header("Content-Length"));
  6486. EXPECT_EQ(false, res->has_header("Content-Range"));
  6487. EXPECT_EQ(JSON_DATA, res->body);
  6488. }
  6489. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6490. auto res = cli_.Get("/with-range-customized-response",
  6491. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6494. EXPECT_EQ(true, res->has_header("Content-Length"));
  6495. EXPECT_EQ(false, res->has_header("Content-Range"));
  6496. EXPECT_EQ(JSON_DATA, res->body);
  6497. }
  6498. TEST_F(ServerTest, Issue1772) {
  6499. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6502. }
  6503. TEST_F(ServerTest, Issue609) {
  6504. auto res = cli_.Delete("/issue609");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ(std::string("ok"), res->body);
  6508. }
  6509. TEST_F(ServerTest, GetStreamedChunked) {
  6510. auto res = cli_.Get("/streamed-chunked");
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. EXPECT_EQ(std::string("123456789"), res->body);
  6514. }
  6515. TEST_F(ServerTest, GetStreamedChunked2) {
  6516. auto res = cli_.Get("/streamed-chunked2");
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. EXPECT_EQ(std::string("123456789"), res->body);
  6520. }
  6521. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6522. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. EXPECT_EQ(StatusCode::OK_200, res->status);
  6525. EXPECT_EQ(std::string("123456789"), res->body);
  6526. EXPECT_TRUE(res->has_header("Trailer"));
  6527. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6528. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6529. // Trailers are now stored separately from headers (security fix)
  6530. EXPECT_EQ(2U, res->trailers.size());
  6531. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6532. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6533. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6534. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6535. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6536. // Verify trailers are NOT in headers (security verification)
  6537. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6538. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6539. }
  6540. TEST_F(ServerTest, LargeChunkedPost) {
  6541. Request req;
  6542. req.method = "POST";
  6543. req.path = "/large-chunked";
  6544. std::string host_and_port;
  6545. host_and_port += HOST;
  6546. host_and_port += ":";
  6547. host_and_port += std::to_string(PORT);
  6548. req.headers.emplace("Host", host_and_port.c_str());
  6549. req.headers.emplace("Accept", "*/*");
  6550. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6551. req.headers.emplace("Content-Type", "text/plain");
  6552. req.headers.emplace("Content-Length", "0");
  6553. req.headers.emplace("Transfer-Encoding", "chunked");
  6554. std::string long_string(30 * 1024u, 'a');
  6555. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6556. // Attempt to make a large enough post to exceed OS buffers, to test that
  6557. // the server handles short reads if the full chunk data isn't available.
  6558. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6559. auto res = std::make_shared<Response>();
  6560. auto error = Error::Success;
  6561. auto ret = cli_.send(req, *res, error);
  6562. ASSERT_TRUE(ret);
  6563. EXPECT_EQ(StatusCode::OK_200, res->status);
  6564. }
  6565. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6566. auto res = cli_.Get("/remote_addr");
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6570. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6571. }
  6572. TEST_F(ServerTest, GetMethodLocalAddr) {
  6573. auto res = cli_.Get("/local_addr");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6578. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6579. }
  6580. TEST_F(ServerTest, HTTPResponseSplitting) {
  6581. auto res = cli_.Get("/http_response_splitting");
  6582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, SlowRequest) {
  6586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6587. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6588. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6589. }
  6590. #if 0
  6591. TEST_F(ServerTest, SlowPost) {
  6592. char buffer[64 * 1024];
  6593. memset(buffer, 0x42, sizeof(buffer));
  6594. auto res = cli_.Post(
  6595. "/slowpost", 64 * 1024 * 1024,
  6596. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6597. auto ret = sink.write(buffer, sizeof(buffer));
  6598. EXPECT_TRUE(ret);
  6599. return true;
  6600. },
  6601. "text/plain");
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::OK_200, res->status);
  6604. }
  6605. TEST_F(ServerTest, SlowPostFail) {
  6606. char buffer[64 * 1024];
  6607. memset(buffer, 0x42, sizeof(buffer));
  6608. cli_.set_write_timeout(std::chrono::seconds(0));
  6609. auto res = cli_.Post(
  6610. "/slowpost", 64 * 1024 * 1024,
  6611. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6612. sink.write(buffer, sizeof(buffer));
  6613. return true;
  6614. },
  6615. "text/plain");
  6616. ASSERT_TRUE(!res);
  6617. EXPECT_EQ(Error::Write, res.error());
  6618. }
  6619. #endif
  6620. TEST_F(ServerTest, Put) {
  6621. auto res = cli_.Put("/put", "PUT", "text/plain");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::OK_200, res->status);
  6624. EXPECT_EQ("PUT", res->body);
  6625. }
  6626. TEST_F(ServerTest, PutWithContentProvider) {
  6627. auto res = cli_.Put(
  6628. "/put", 3,
  6629. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6630. sink.os << "PUT";
  6631. return true;
  6632. },
  6633. "text/plain");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("PUT", res->body);
  6637. }
  6638. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6639. auto res = cli_.Post(
  6640. "/post", 42,
  6641. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6642. return false;
  6643. },
  6644. "text/plain");
  6645. ASSERT_TRUE(!res);
  6646. EXPECT_EQ(Error::Canceled, res.error());
  6647. }
  6648. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6649. auto res = cli_.Put(
  6650. "/put",
  6651. [](size_t /*offset*/, DataSink &sink) {
  6652. sink.os << "PUT";
  6653. sink.done();
  6654. return true;
  6655. },
  6656. "text/plain");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("PUT", res->body);
  6660. }
  6661. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6662. auto res = cli_.Post(
  6663. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6664. "text/plain");
  6665. ASSERT_TRUE(!res);
  6666. EXPECT_EQ(Error::Canceled, res.error());
  6667. }
  6668. TEST_F(ServerTest, PostLoopBack) {
  6669. std::string body;
  6670. auto res = cli_.Post(
  6671. "/post-loopback", 9,
  6672. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6673. EXPECT_EQ(9u, length);
  6674. sink.write("123", 3);
  6675. sink.write("456", 3);
  6676. sink.write("789", 3);
  6677. return true;
  6678. },
  6679. "text/plain",
  6680. [&body](const char *data, size_t data_length) {
  6681. body.append(data, data_length);
  6682. return true;
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. EXPECT_EQ("123456789", body);
  6687. }
  6688. TEST_F(ServerTest, PutLoopBack) {
  6689. std::string body;
  6690. auto res = cli_.Put(
  6691. "/put-loopback", 9,
  6692. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6693. EXPECT_EQ(9u, length);
  6694. sink.write("123", 3);
  6695. sink.write("456", 3);
  6696. sink.write("789", 3);
  6697. return true;
  6698. },
  6699. "text/plain",
  6700. [&body](const char *data, size_t data_length) {
  6701. body.append(data, data_length);
  6702. return true;
  6703. });
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::OK_200, res->status);
  6706. EXPECT_EQ("123456789", body);
  6707. }
  6708. TEST_F(ServerTest, PatchLoopBack) {
  6709. std::string body;
  6710. auto res = cli_.Patch(
  6711. "/patch-loopback", 9,
  6712. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6713. EXPECT_EQ(9u, length);
  6714. sink.write("123", 3);
  6715. sink.write("456", 3);
  6716. sink.write("789", 3);
  6717. return true;
  6718. },
  6719. "text/plain",
  6720. [&body](const char *data, size_t data_length) {
  6721. body.append(data, data_length);
  6722. return true;
  6723. });
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::OK_200, res->status);
  6726. EXPECT_EQ("123456789", body);
  6727. }
  6728. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6729. std::string body;
  6730. auto res = cli_.Post(
  6731. "/post-loopback",
  6732. [](size_t /*offset*/, DataSink &sink) {
  6733. sink.write("123", 3);
  6734. sink.write("456", 3);
  6735. sink.write("789", 3);
  6736. sink.done();
  6737. return true;
  6738. },
  6739. "text/plain",
  6740. [&body](const char *data, size_t data_length) {
  6741. body.append(data, data_length);
  6742. return true;
  6743. });
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("123456789", body);
  6747. }
  6748. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6749. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6750. cli_.set_compress(true);
  6751. auto res = cli_.Put(
  6752. "/put", 3,
  6753. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6754. sink.os << "PUT";
  6755. return true;
  6756. },
  6757. "text/plain");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("PUT", res->body);
  6761. }
  6762. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Post(
  6765. "/post", 42,
  6766. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6767. return false;
  6768. },
  6769. "text/plain");
  6770. ASSERT_TRUE(!res);
  6771. EXPECT_EQ(Error::Canceled, res.error());
  6772. }
  6773. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6774. cli_.set_compress(true);
  6775. auto res = cli_.Put(
  6776. "/put",
  6777. [](size_t /*offset*/, DataSink &sink) {
  6778. sink.os << "PUT";
  6779. sink.done();
  6780. return true;
  6781. },
  6782. "text/plain");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("PUT", res->body);
  6786. }
  6787. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6788. cli_.set_compress(true);
  6789. auto res = cli_.Post(
  6790. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6791. "text/plain");
  6792. ASSERT_TRUE(!res);
  6793. EXPECT_EQ(Error::Canceled, res.error());
  6794. }
  6795. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6796. cli_.set_compress(true);
  6797. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::OK_200, res->status);
  6800. EXPECT_EQ(LARGE_DATA, res->body);
  6801. }
  6802. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6803. #ifdef CPPHTTPLIB_SSL_ENABLED
  6804. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6805. Client cli(s.c_str());
  6806. cli.enable_server_certificate_verification(false);
  6807. #else
  6808. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6809. Client cli(s.c_str());
  6810. #endif
  6811. cli.set_compress(true);
  6812. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ(LARGE_DATA, res->body);
  6816. // The compressed size should be less than a 10th of the original. May vary
  6817. // depending on the zlib library.
  6818. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6819. static_cast<uint64_t>(10 * 1024 * 1024));
  6820. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6821. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6822. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6823. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6824. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6825. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6826. #endif
  6827. }
  6828. TEST_F(ServerTest, PutContentWithDeflate) {
  6829. cli_.set_compress(false);
  6830. Headers headers;
  6831. headers.emplace("Content-Encoding", "deflate");
  6832. // PUT in deflate format:
  6833. auto res = cli_.Put("/put", headers,
  6834. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. EXPECT_EQ("PUT", res->body);
  6838. }
  6839. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6840. Headers headers;
  6841. headers.emplace("Accept-Encoding", "gzip, deflate");
  6842. auto res = cli_.Get("/streamed-chunked", headers);
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ(std::string("123456789"), res->body);
  6846. }
  6847. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6848. Headers headers;
  6849. headers.emplace("Accept-Encoding", "gzip, deflate");
  6850. auto res = cli_.Get("/streamed-chunked2", headers);
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ(StatusCode::OK_200, res->status);
  6853. EXPECT_EQ(std::string("123456789"), res->body);
  6854. }
  6855. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6856. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::OK_200, res->status);
  6859. }
  6860. TEST(GzipDecompressor, ChunkedDecompression) {
  6861. std::string data;
  6862. for (size_t i = 0; i < 32 * 1024; ++i) {
  6863. data.push_back(static_cast<char>('a' + i % 26));
  6864. }
  6865. std::string compressed_data;
  6866. {
  6867. httplib::detail::gzip_compressor compressor;
  6868. bool result = compressor.compress(
  6869. data.data(), data.size(),
  6870. /*last=*/true,
  6871. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6872. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6873. compressed_data_size);
  6874. return true;
  6875. });
  6876. ASSERT_TRUE(result);
  6877. }
  6878. std::string decompressed_data;
  6879. {
  6880. httplib::detail::gzip_decompressor decompressor;
  6881. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6882. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6883. size_t chunk_size = 130;
  6884. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6885. chunk_begin += chunk_size) {
  6886. size_t current_chunk_size =
  6887. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6888. bool result = decompressor.decompress(
  6889. compressed_data.data() + chunk_begin, current_chunk_size,
  6890. [&](const char *decompressed_data_chunk,
  6891. size_t decompressed_data_chunk_size) {
  6892. decompressed_data.insert(decompressed_data.size(),
  6893. decompressed_data_chunk,
  6894. decompressed_data_chunk_size);
  6895. return true;
  6896. });
  6897. ASSERT_TRUE(result);
  6898. }
  6899. }
  6900. ASSERT_EQ(data, decompressed_data);
  6901. }
  6902. TEST(GzipDecompressor, DeflateDecompression) {
  6903. std::string original_text = "Raw deflate without gzip";
  6904. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6905. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6906. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6907. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6908. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6909. std::string decompressed_data;
  6910. {
  6911. httplib::detail::gzip_decompressor decompressor;
  6912. bool result = decompressor.decompress(
  6913. compressed_data.data(), compressed_data.size(),
  6914. [&](const char *decompressed_data_chunk,
  6915. size_t decompressed_data_chunk_size) {
  6916. decompressed_data.insert(decompressed_data.size(),
  6917. decompressed_data_chunk,
  6918. decompressed_data_chunk_size);
  6919. return true;
  6920. });
  6921. ASSERT_TRUE(result);
  6922. }
  6923. ASSERT_EQ(original_text, decompressed_data);
  6924. }
  6925. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6926. std::string original_text = "Raw deflate without gzip";
  6927. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6928. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6929. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6930. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6931. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6932. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6933. std::string decompressed_data;
  6934. {
  6935. httplib::detail::gzip_decompressor decompressor;
  6936. bool result = decompressor.decompress(
  6937. compressed_data.data(), compressed_data.size(),
  6938. [&](const char *decompressed_data_chunk,
  6939. size_t decompressed_data_chunk_size) {
  6940. decompressed_data.insert(decompressed_data.size(),
  6941. decompressed_data_chunk,
  6942. decompressed_data_chunk_size);
  6943. return true;
  6944. });
  6945. ASSERT_TRUE(result);
  6946. }
  6947. ASSERT_EQ(original_text, decompressed_data);
  6948. }
  6949. #endif
  6950. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6951. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6952. Headers headers;
  6953. headers.emplace("Accept-Encoding", "br");
  6954. auto res = cli_.Get("/streamed-chunked", headers);
  6955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6956. EXPECT_EQ(StatusCode::OK_200, res->status);
  6957. EXPECT_EQ(std::string("123456789"), res->body);
  6958. }
  6959. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6960. Headers headers;
  6961. headers.emplace("Accept-Encoding", "br");
  6962. auto res = cli_.Get("/streamed-chunked2", headers);
  6963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6964. EXPECT_EQ(StatusCode::OK_200, res->status);
  6965. EXPECT_EQ(std::string("123456789"), res->body);
  6966. }
  6967. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6968. cli_.set_compress(true);
  6969. auto res = cli_.Put(
  6970. "/put", 3,
  6971. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6972. sink.os << "PUT";
  6973. return true;
  6974. },
  6975. "text/plain");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::OK_200, res->status);
  6978. EXPECT_EQ("PUT", res->body);
  6979. }
  6980. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6981. cli_.set_compress(true);
  6982. auto res = cli_.Put(
  6983. "/put",
  6984. [](size_t /*offset*/, DataSink &sink) {
  6985. sink.os << "PUT";
  6986. sink.done();
  6987. return true;
  6988. },
  6989. "text/plain");
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("PUT", res->body);
  6993. }
  6994. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6995. cli_.set_compress(true);
  6996. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ(LARGE_DATA, res->body);
  7000. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7001. }
  7002. #endif
  7003. TEST_F(ServerTest, Patch) {
  7004. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::OK_200, res->status);
  7007. EXPECT_EQ("PATCH", res->body);
  7008. }
  7009. TEST_F(ServerTest, Delete) {
  7010. auto res = cli_.Delete("/delete");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ("DELETE", res->body);
  7014. }
  7015. TEST_F(ServerTest, DeleteContentReceiver) {
  7016. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("content", res->body);
  7020. }
  7021. TEST_F(ServerTest, Options) {
  7022. auto res = cli_.Options("*");
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7026. EXPECT_TRUE(res->body.empty());
  7027. }
  7028. TEST_F(ServerTest, URL) {
  7029. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. }
  7033. TEST_F(ServerTest, ArrayParam) {
  7034. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::OK_200, res->status);
  7037. }
  7038. TEST_F(ServerTest, ArrayParamValues) {
  7039. auto res =
  7040. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. }
  7044. TEST_F(ServerTest, NoMultipleHeaders) {
  7045. Headers headers = {{"Content-Length", "5"}};
  7046. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7047. "text/plain");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. EXPECT_EQ(StatusCode::OK_200, res->status);
  7050. }
  7051. TEST_F(ServerTest, PostContentReceiver) {
  7052. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. ASSERT_EQ(StatusCode::OK_200, res->status);
  7055. ASSERT_EQ("content", res->body);
  7056. }
  7057. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7058. UploadFormDataItems items = {
  7059. {"text1", "text default", "", ""},
  7060. {"text2", "aωb", "", ""},
  7061. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7062. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7063. {"file3", "", "", "application/octet-stream"},
  7064. };
  7065. auto res = cli_.Post("/content_receiver", items);
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. }
  7069. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7070. UploadFormDataItems items = {
  7071. {"text1", "text default", "", ""},
  7072. {"text2", "aωb", "", ""},
  7073. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7074. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7075. {"file3", "", "", "application/octet-stream"},
  7076. };
  7077. auto boundary = std::string("+++++");
  7078. std::string body;
  7079. for (const auto &item : items) {
  7080. body += "--" + boundary + "\r\n";
  7081. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7082. if (!item.filename.empty()) {
  7083. body += "; filename=\"" + item.filename + "\"";
  7084. }
  7085. body += "\r\n";
  7086. if (!item.content_type.empty()) {
  7087. body += "Content-Type: " + item.content_type + "\r\n";
  7088. }
  7089. body += "\r\n";
  7090. body += item.content + "\r\n";
  7091. }
  7092. body += "--" + boundary + "--\r\n";
  7093. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7094. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. }
  7098. TEST(MultipartFormDataTest, FieldEscaping) {
  7099. Server svr;
  7100. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7101. const ContentReader &content_reader) {
  7102. ASSERT_TRUE(req.is_multipart_form_data());
  7103. std::vector<FormData> received;
  7104. content_reader(
  7105. [&](const FormData &file) {
  7106. received.push_back(file);
  7107. return true;
  7108. },
  7109. [&](const char *data, size_t data_length) {
  7110. received.back().content.append(data, data_length);
  7111. return true;
  7112. });
  7113. // '"', CR and LF in names and filenames are escaped following the
  7114. // WHATWG HTML standard, so each part still parses as a single part
  7115. // with no injected headers. Content types get CR/LF escaped too,
  7116. // while '"' (legal there, e.g. quoted charset) is preserved.
  7117. ASSERT_EQ(4U, received.size());
  7118. EXPECT_EQ("na%22me", received[0].name);
  7119. EXPECT_EQ("quoted name", received[0].content);
  7120. EXPECT_EQ("file", received[1].name);
  7121. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7122. received[1].filename);
  7123. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7124. EXPECT_EQ("injected", received[1].content);
  7125. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7126. EXPECT_EQ("my%22file.txt", received[2].filename);
  7127. EXPECT_EQ("cr lf name", received[2].content);
  7128. EXPECT_EQ("typed", received[3].name);
  7129. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7130. received[3].content_type);
  7131. EXPECT_EQ("typed content", received[3].content);
  7132. });
  7133. auto port = svr.bind_to_any_port("localhost");
  7134. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7135. auto se = detail::scope_exit([&] {
  7136. svr.stop();
  7137. t.join();
  7138. ASSERT_FALSE(svr.is_running());
  7139. });
  7140. svr.wait_until_ready();
  7141. Client cli("localhost", port);
  7142. UploadFormDataItems items = {
  7143. {"na\"me", "quoted name", "", ""},
  7144. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7145. "application/octet-stream"},
  7146. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7147. {"typed", "typed content", "",
  7148. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7149. };
  7150. auto res = cli.Post("/post", items);
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::OK_200, res->status);
  7153. }
  7154. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7155. const UploadFormDataItems items = {
  7156. {"name1", "Content 1", "", ""},
  7157. {"name2", "Content 2", "file2.txt", "text/plain"},
  7158. };
  7159. Server svr;
  7160. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7161. const ContentReader &content_reader) {
  7162. ASSERT_TRUE(req.is_multipart_form_data());
  7163. std::vector<FormData> received;
  7164. content_reader(
  7165. [&](const FormData &file) {
  7166. received.push_back(file);
  7167. return true;
  7168. },
  7169. [&](const char *data, size_t data_length) {
  7170. received.back().content.append(data, data_length);
  7171. return true;
  7172. });
  7173. ASSERT_EQ(2U, received.size());
  7174. EXPECT_EQ("name1", received[0].name);
  7175. EXPECT_EQ("Content 1", received[0].content);
  7176. EXPECT_EQ("name2", received[1].name);
  7177. EXPECT_EQ("Content 2", received[1].content);
  7178. EXPECT_EQ("file2.txt", received[1].filename);
  7179. EXPECT_EQ("text/plain", received[1].content_type);
  7180. });
  7181. auto port = svr.bind_to_any_port("localhost");
  7182. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7183. auto se = detail::scope_exit([&] {
  7184. svr.stop();
  7185. t.join();
  7186. ASSERT_FALSE(svr.is_running());
  7187. });
  7188. svr.wait_until_ready();
  7189. Client cli("localhost", port);
  7190. // Whole-body serialization with a generated boundary
  7191. {
  7192. MultipartFormDataWriter writer;
  7193. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7194. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7195. writer.content_type());
  7196. auto body = writer.serialize(items);
  7197. EXPECT_EQ(body.size(), writer.content_length(items));
  7198. auto res = cli.Post("/post", body, writer.content_type());
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. }
  7202. // Per-part framing with a custom boundary via a content provider
  7203. {
  7204. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7205. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7206. MultipartFormDataWriter writer("custom-boundary_123");
  7207. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7208. std::string body;
  7209. for (const auto &item : items) {
  7210. body += writer.item_begin(item);
  7211. body += item.content;
  7212. body += MultipartFormDataWriter::item_end();
  7213. }
  7214. body += writer.finish();
  7215. EXPECT_EQ(body.size(), writer.content_length(items));
  7216. auto res = cli.Post(
  7217. "/post", body.size(),
  7218. [&](size_t offset, size_t length, DataSink &sink) {
  7219. sink.write(body.data() + offset, length);
  7220. return true;
  7221. },
  7222. writer.content_type());
  7223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. }
  7226. }
  7227. TEST_F(ServerTest, PostContentReceiverGzip) {
  7228. cli_.set_compress(true);
  7229. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. ASSERT_EQ(StatusCode::OK_200, res->status);
  7232. ASSERT_EQ("content", res->body);
  7233. }
  7234. TEST_F(ServerTest, PutContentReceiver) {
  7235. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. ASSERT_EQ(StatusCode::OK_200, res->status);
  7238. ASSERT_EQ("content", res->body);
  7239. }
  7240. TEST_F(ServerTest, PatchContentReceiver) {
  7241. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. ASSERT_EQ(StatusCode::OK_200, res->status);
  7244. ASSERT_EQ("content", res->body);
  7245. }
  7246. template <typename ClientType>
  7247. void TestWithHeadersAndContentReceiver(
  7248. ClientType &cli,
  7249. std::function<Result(ClientType &, const std::string &, const Headers &,
  7250. const std::string &, const std::string &,
  7251. ContentReceiver, DownloadProgress)>
  7252. request_func) {
  7253. Headers headers;
  7254. headers.emplace("X-Custom-Header", "test-value");
  7255. std::string received_body;
  7256. auto res = request_func(
  7257. cli, "/content_receiver", headers, "content", "application/json",
  7258. [&](const char *data, size_t data_length) {
  7259. received_body.append(data, data_length);
  7260. return true;
  7261. },
  7262. nullptr);
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("content", received_body);
  7266. }
  7267. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7268. #ifdef CPPHTTPLIB_SSL_ENABLED
  7269. using ClientT = SSLClient;
  7270. #else
  7271. using ClientT = Client;
  7272. #endif
  7273. TestWithHeadersAndContentReceiver<ClientT>(
  7274. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7275. const std::string &body, const std::string &content_type,
  7276. ContentReceiver receiver, DownloadProgress progress) {
  7277. return cli.Post(path, headers, body, content_type, receiver, progress);
  7278. });
  7279. }
  7280. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7281. #ifdef CPPHTTPLIB_SSL_ENABLED
  7282. using ClientT = SSLClient;
  7283. #else
  7284. using ClientT = Client;
  7285. #endif
  7286. TestWithHeadersAndContentReceiver<ClientT>(
  7287. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7288. const std::string &body, const std::string &content_type,
  7289. ContentReceiver receiver, DownloadProgress progress) {
  7290. return cli.Put(path, headers, body, content_type, receiver, progress);
  7291. });
  7292. }
  7293. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7294. #ifdef CPPHTTPLIB_SSL_ENABLED
  7295. using ClientT = SSLClient;
  7296. #else
  7297. using ClientT = Client;
  7298. #endif
  7299. TestWithHeadersAndContentReceiver<ClientT>(
  7300. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7301. const std::string &body, const std::string &content_type,
  7302. ContentReceiver receiver, DownloadProgress progress) {
  7303. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7304. });
  7305. }
  7306. template <typename ClientType>
  7307. void TestWithHeadersAndContentReceiverWithProgress(
  7308. ClientType &cli,
  7309. std::function<Result(ClientType &, const std::string &, const Headers &,
  7310. const std::string &, const std::string &,
  7311. ContentReceiver, DownloadProgress)>
  7312. request_func) {
  7313. Headers headers;
  7314. headers.emplace("X-Test-Header", "progress-test");
  7315. std::string received_body;
  7316. auto progress_called = false;
  7317. auto res = request_func(
  7318. cli, "/content_receiver", headers, "content", "text/plain",
  7319. [&](const char *data, size_t data_length) {
  7320. received_body.append(data, data_length);
  7321. return true;
  7322. },
  7323. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7324. progress_called = true;
  7325. return true;
  7326. });
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::OK_200, res->status);
  7329. EXPECT_EQ("content", received_body);
  7330. EXPECT_TRUE(progress_called);
  7331. }
  7332. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7333. #ifdef CPPHTTPLIB_SSL_ENABLED
  7334. using ClientT = SSLClient;
  7335. #else
  7336. using ClientT = Client;
  7337. #endif
  7338. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7339. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7340. const std::string &body, const std::string &content_type,
  7341. ContentReceiver receiver, DownloadProgress progress) {
  7342. return cli.Post(path, headers, body, content_type, receiver, progress);
  7343. });
  7344. }
  7345. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7346. #ifdef CPPHTTPLIB_SSL_ENABLED
  7347. using ClientT = SSLClient;
  7348. #else
  7349. using ClientT = Client;
  7350. #endif
  7351. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7352. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7353. const std::string &body, const std::string &content_type,
  7354. ContentReceiver receiver, DownloadProgress progress) {
  7355. return cli.Put(path, headers, body, content_type, receiver, progress);
  7356. });
  7357. }
  7358. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7359. #ifdef CPPHTTPLIB_SSL_ENABLED
  7360. using ClientT = SSLClient;
  7361. #else
  7362. using ClientT = Client;
  7363. #endif
  7364. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7365. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7366. const std::string &body, const std::string &content_type,
  7367. ContentReceiver receiver, DownloadProgress progress) {
  7368. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7369. });
  7370. }
  7371. template <typename ClientType>
  7372. void TestWithHeadersAndContentReceiverError(
  7373. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7374. const Headers &, const std::string &,
  7375. const std::string &, ContentReceiver)>
  7376. request_func) {
  7377. Headers headers;
  7378. headers.emplace("X-Error-Test", "true");
  7379. std::string received_body;
  7380. auto receiver_failed = false;
  7381. auto res =
  7382. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7383. [&](const char *data, size_t data_length) {
  7384. received_body.append(data, data_length);
  7385. receiver_failed = true;
  7386. return false;
  7387. });
  7388. ASSERT_FALSE(res);
  7389. EXPECT_TRUE(receiver_failed);
  7390. }
  7391. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7392. #ifdef CPPHTTPLIB_SSL_ENABLED
  7393. using ClientT = SSLClient;
  7394. #else
  7395. using ClientT = Client;
  7396. #endif
  7397. TestWithHeadersAndContentReceiverError<ClientT>(
  7398. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7399. const std::string &body, const std::string &content_type,
  7400. ContentReceiver receiver) {
  7401. return cli.Post(path, headers, body, content_type, receiver);
  7402. });
  7403. }
  7404. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7405. #ifdef CPPHTTPLIB_SSL_ENABLED
  7406. using ClientT = SSLClient;
  7407. #else
  7408. using ClientT = Client;
  7409. #endif
  7410. TestWithHeadersAndContentReceiverError<ClientT>(
  7411. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7412. const std::string &body, const std::string &content_type,
  7413. ContentReceiver receiver) {
  7414. return cli.Put(path, headers, body, content_type, receiver);
  7415. });
  7416. }
  7417. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7418. #ifdef CPPHTTPLIB_SSL_ENABLED
  7419. using ClientT = SSLClient;
  7420. #else
  7421. using ClientT = Client;
  7422. #endif
  7423. TestWithHeadersAndContentReceiverError<ClientT>(
  7424. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7425. const std::string &body, const std::string &content_type,
  7426. ContentReceiver receiver) {
  7427. return cli.Patch(path, headers, body, content_type, receiver);
  7428. });
  7429. }
  7430. TEST_F(ServerTest, PostQueryStringAndBody) {
  7431. auto res =
  7432. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. ASSERT_EQ(StatusCode::OK_200, res->status);
  7435. }
  7436. TEST_F(ServerTest, HTTP2Magic) {
  7437. Request req;
  7438. req.method = "PRI";
  7439. req.path = "*";
  7440. req.body = "SM";
  7441. auto res = std::make_shared<Response>();
  7442. auto error = Error::Success;
  7443. auto ret = cli_.send(req, *res, error);
  7444. ASSERT_TRUE(ret);
  7445. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7446. }
  7447. TEST_F(ServerTest, KeepAlive) {
  7448. auto res = cli_.Get("/hi");
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7452. EXPECT_EQ("Hello World!", res->body);
  7453. res = cli_.Get("/hi");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7457. EXPECT_EQ("Hello World!", res->body);
  7458. res = cli_.Get("/hi");
  7459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7462. EXPECT_EQ("Hello World!", res->body);
  7463. res = cli_.Get("/not-exist");
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7466. res = cli_.Post("/empty", "", "text/plain");
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7470. EXPECT_EQ("empty", res->body);
  7471. EXPECT_EQ("close", res->get_header_value("Connection"));
  7472. res = cli_.Post(
  7473. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7474. "text/plain");
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7478. EXPECT_EQ("empty", res->body);
  7479. cli_.set_keep_alive(false);
  7480. res = cli_.Get("/last-request");
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("close", res->get_header_value("Connection"));
  7484. }
  7485. TEST_F(ServerTest, TooManyRedirect) {
  7486. cli_.set_follow_location(true);
  7487. auto res = cli_.Get("/redirect/0");
  7488. ASSERT_TRUE(!res);
  7489. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7490. }
  7491. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7492. Request req;
  7493. req.method = "FOOBAR";
  7494. req.path = "/hi";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteReadsBody) {
  7503. const std::string xml =
  7504. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7505. Request req;
  7506. req.method = "PROPFIND";
  7507. req.path = "/dav/dir";
  7508. req.set_header("Depth", "1");
  7509. req.body = xml;
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7513. EXPECT_EQ(xml, res->body);
  7514. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7515. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7516. }
  7517. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/42";
  7521. auto res = cli_.send(req);
  7522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7523. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7524. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7525. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7526. }
  7527. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7528. Request req;
  7529. req.method = "PROPFIND";
  7530. req.path = "/dav-re/123";
  7531. auto res = cli_.send(req);
  7532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7533. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7534. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7535. }
  7536. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7537. Request req;
  7538. req.method = "MKCOL";
  7539. req.path = "/dav-mkcol";
  7540. auto res = cli_.send(req);
  7541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7542. EXPECT_EQ(StatusCode::Created_201, res->status);
  7543. }
  7544. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7545. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7546. Request req;
  7547. req.method = "REPORT";
  7548. req.path = "/dav-report";
  7549. req.body = xml;
  7550. auto res = cli_.send(req);
  7551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7552. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7553. EXPECT_EQ(xml, res->body);
  7554. }
  7555. // A content reader route must fire even when the request carries no body,
  7556. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7557. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7558. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7559. Request req;
  7560. req.method = "REPORT";
  7561. req.path = "/dav-report";
  7562. auto res = cli_.send(req);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7565. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7566. }
  7567. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7568. Request req;
  7569. req.method = "PROPFIND";
  7570. req.path = "/not-dav";
  7571. auto res = cli_.send(req);
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7574. }
  7575. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7576. Request req;
  7577. req.method = "UNLOCK";
  7578. req.path = "/dav/dir";
  7579. cli_.set_keep_alive(true);
  7580. auto res = cli_.send(req);
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7583. EXPECT_EQ("close", res->get_header_value("Connection"));
  7584. EXPECT_FALSE(cli_.is_socket_open());
  7585. }
  7586. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7587. // The mount point serves this path, but only for GET and HEAD.
  7588. auto get_res = cli_.Get("/dir/index.html");
  7589. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7590. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7591. Request req;
  7592. req.method = "PROPFIND";
  7593. req.path = "/dir/index.html";
  7594. auto res = cli_.send(req);
  7595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7597. }
  7598. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7599. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7600. cli_.set_keep_alive(true);
  7601. for (auto i = 0; i < 2; i++) {
  7602. Request req;
  7603. req.method = "PROPFIND";
  7604. req.path = "/dav/dir";
  7605. req.body = xml;
  7606. auto res = cli_.send(req);
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7609. EXPECT_EQ(xml, res->body);
  7610. EXPECT_TRUE(cli_.is_socket_open());
  7611. }
  7612. // A built-in method must still be served on the same connection.
  7613. cli_.set_keep_alive(false);
  7614. auto res = cli_.Get("/hi");
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. EXPECT_EQ("close", res->get_header_value("Connection"));
  7618. }
  7619. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7620. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7621. Request req;
  7622. req.method = "PROPFIND";
  7623. req.path = "/dav/dir";
  7624. req.set_header("Expect", "100-continue");
  7625. req.body = xml;
  7626. auto res = cli_.send(req);
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7629. EXPECT_EQ(xml, res->body);
  7630. }
  7631. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7633. TEST_F(ServerTest, Gzip) {
  7634. Headers headers;
  7635. headers.emplace("Accept-Encoding", "gzip, deflate");
  7636. auto res = cli_.Get("/compress", headers);
  7637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7638. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7640. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7642. "7890123456789012345678901234567890",
  7643. res->body);
  7644. EXPECT_EQ(StatusCode::OK_200, res->status);
  7645. }
  7646. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7647. Headers headers;
  7648. headers.emplace("Accept-Encoding", "gzip, deflate");
  7649. auto res = cli_.Get("/compress-with-charset", headers);
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7652. EXPECT_EQ("application/json; charset=utf-8",
  7653. res->get_header_value("Content-Type"));
  7654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7655. "7890123456789012345678901234567890",
  7656. res->body);
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. }
  7659. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7660. Headers headers;
  7661. headers.emplace("Accept-Encoding", "");
  7662. auto res = cli_.Get("/compress", headers);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7666. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7667. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7668. "7890123456789012345678901234567890",
  7669. res->body);
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. }
  7672. TEST_F(ServerTest, GzipWithContentReceiver) {
  7673. Headers headers;
  7674. headers.emplace("Accept-Encoding", "gzip, deflate");
  7675. std::string body;
  7676. auto res = cli_.Get("/compress", headers,
  7677. [&](const char *data, uint64_t data_length) {
  7678. EXPECT_EQ(100U, data_length);
  7679. body.append(data, data_length);
  7680. return true;
  7681. });
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7684. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7685. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7686. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7687. "7890123456789012345678901234567890",
  7688. body);
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. }
  7691. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7692. Headers headers;
  7693. headers.emplace("Accept-Encoding", "gzip, deflate");
  7694. cli_.set_decompress(false);
  7695. auto res = cli_.Get("/compress", headers);
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7699. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7700. EXPECT_EQ(33U, res->body.size());
  7701. EXPECT_EQ(StatusCode::OK_200, res->status);
  7702. }
  7703. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7704. Headers headers;
  7705. headers.emplace("Accept-Encoding", "");
  7706. std::string body;
  7707. auto res = cli_.Get("/compress", headers,
  7708. [&](const char *data, uint64_t data_length) {
  7709. EXPECT_EQ(100U, data_length);
  7710. body.append(data, data_length);
  7711. return true;
  7712. });
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7716. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7717. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7718. "7890123456789012345678901234567890",
  7719. body);
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. }
  7722. TEST_F(ServerTest, NoGzip) {
  7723. Headers headers;
  7724. headers.emplace("Accept-Encoding", "gzip, deflate");
  7725. auto res = cli_.Get("/nocompress", headers);
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7728. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7729. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7730. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7731. "7890123456789012345678901234567890",
  7732. res->body);
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. }
  7735. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7736. Headers headers;
  7737. headers.emplace("Accept-Encoding", "gzip, deflate");
  7738. std::string body;
  7739. auto res = cli_.Get("/nocompress", headers,
  7740. [&](const char *data, uint64_t data_length) {
  7741. EXPECT_EQ(100U, data_length);
  7742. body.append(data, data_length);
  7743. return true;
  7744. });
  7745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7746. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7747. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7748. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7749. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7750. "7890123456789012345678901234567890",
  7751. body);
  7752. EXPECT_EQ(StatusCode::OK_200, res->status);
  7753. }
  7754. TEST_F(ServerTest, MultipartFormDataGzip) {
  7755. UploadFormDataItems items = {
  7756. {"key1", "test", "", ""},
  7757. {"key2", "--abcdefg123", "", ""},
  7758. };
  7759. cli_.set_compress(true);
  7760. auto res = cli_.Post("/compress-multipart", items);
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. #endif
  7765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7766. // Static file compression is opt-in, so these run their own server rather than
  7767. // flipping it on for the shared ServerTest fixture, which would silently
  7768. // rewrite what every other static file test is asserting.
  7769. class StaticFileCompressionTest : public ::testing::Test {
  7770. protected:
  7771. void TearDown() override {
  7772. if (t_.joinable()) {
  7773. svr_.stop();
  7774. t_.join();
  7775. }
  7776. }
  7777. int start(const std::function<void(Server &)> &configure = nullptr) {
  7778. // Serves the same tree as a directory of build-time compressed assets
  7779. // would be served: the mount point names the coding the files are already
  7780. // stored in. Registered before "/" so it is the one that matches.
  7781. svr_.set_mount_point("/pre-encoded", "./www",
  7782. {{"Content-Encoding", "gzip"}});
  7783. svr_.set_mount_point("/", "./www");
  7784. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7785. res.set_file_content("./www/dir/index.html", "text/html");
  7786. });
  7787. svr_.Get("/pre-encoded-file-content",
  7788. [](const Request & /*req*/, Response &res) {
  7789. res.set_header("Content-Encoding", "gzip");
  7790. res.set_file_content("./www/dir/index.html", "text/html");
  7791. });
  7792. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7793. res.set_content_provider(
  7794. 6, "text/plain",
  7795. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7796. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7797. return true;
  7798. });
  7799. });
  7800. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7801. res.set_content_provider(
  7802. 1000, "text/plain",
  7803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7804. if (offset < 100) {
  7805. std::string data(100, 'A');
  7806. sink.write(data.data(), data.size());
  7807. return true;
  7808. }
  7809. std::this_thread::sleep_for(std::chrono::seconds(2));
  7810. std::string data(900, 'B');
  7811. sink.write(data.data(), data.size());
  7812. return true;
  7813. });
  7814. });
  7815. if (configure) { configure(svr_); }
  7816. auto port = svr_.bind_to_any_port(HOST);
  7817. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7818. svr_.wait_until_ready();
  7819. return port;
  7820. }
  7821. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7822. // Every file under ./www except 1MB.txt is smaller than the default
  7823. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7824. // it out of the way.
  7825. static void enable_without_floor(Server &svr) {
  7826. svr.set_static_file_compression(true);
  7827. svr.set_static_file_compression_min_length(0);
  7828. }
  7829. Server svr_;
  7830. std::thread t_;
  7831. };
  7832. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7833. auto port = start();
  7834. Client cli(HOST, port);
  7835. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7839. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7840. EXPECT_EQ(1048576U, res->body.size());
  7841. }
  7842. TEST_F(StaticFileCompressionTest, MountPoint) {
  7843. auto port = start(enable);
  7844. Client cli(HOST, port);
  7845. cli.set_decompress(false);
  7846. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7850. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7851. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7852. // The response stays self-delimiting: a length, not a chunked body.
  7853. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7854. EXPECT_EQ(std::to_string(res->body.size()),
  7855. res->get_header_value("Content-Length"));
  7856. EXPECT_LT(res->body.size(), 1048576U);
  7857. EXPECT_FALSE(res->body.empty());
  7858. }
  7859. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7860. auto port = start(enable);
  7861. Client cli(HOST, port);
  7862. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7866. EXPECT_EQ(1048576U, res->body.size());
  7867. }
  7868. TEST_F(StaticFileCompressionTest, FileContent) {
  7869. auto port = start(enable_without_floor);
  7870. Client cli(HOST, port);
  7871. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7875. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7876. EXPECT_EQ(104U, res->body.size());
  7877. }
  7878. // A handler that serves an already-encoded file names the coding itself. The
  7879. // file-backed path decided its coding from Accept-Encoding and the content
  7880. // type alone, so it compressed the stored bytes a second time and appended a
  7881. // second Content-Encoding field line.
  7882. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7883. auto port = start(enable_without_floor);
  7884. Client cli(HOST, port);
  7885. cli.set_decompress(false);
  7886. auto res = cli.Get("/pre-encoded-file-content",
  7887. Headers{{"Accept-Encoding", "gzip"}});
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7891. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7892. // Vary belongs to a coding the server chose, and it chose none here.
  7893. EXPECT_FALSE(res->has_header("Vary"));
  7894. // The file travels exactly as it is stored on disk.
  7895. EXPECT_EQ(104U, res->body.size());
  7896. }
  7897. // The 1MB file clears the default floor, so this one runs the configuration a
  7898. // deployment would actually have.
  7899. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7900. auto port = start(enable);
  7901. Client cli(HOST, port);
  7902. cli.set_decompress(false);
  7903. auto res =
  7904. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7906. EXPECT_EQ(StatusCode::OK_200, res->status);
  7907. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7908. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7909. EXPECT_FALSE(res->has_header("Vary"));
  7910. EXPECT_EQ(1048576U, res->body.size());
  7911. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7912. }
  7913. TEST_F(StaticFileCompressionTest, Head) {
  7914. auto port = start(enable);
  7915. Client cli(HOST, port);
  7916. cli.set_decompress(false);
  7917. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7919. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7923. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7924. // HEAD still reports the size a GET would return.
  7925. EXPECT_EQ(get->get_header_value("Content-Length"),
  7926. res->get_header_value("Content-Length"));
  7927. EXPECT_TRUE(res->body.empty());
  7928. }
  7929. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7930. auto port = start(enable);
  7931. Client cli(HOST, port);
  7932. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7933. {"Accept-Encoding", "gzip"}});
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7936. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7937. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7938. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7939. EXPECT_EQ("cd", res->body);
  7940. }
  7941. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7942. auto port = start(enable);
  7943. Client cli(HOST, port);
  7944. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7948. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7949. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7950. }
  7951. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7952. auto port = start(enable);
  7953. Client cli(HOST, port);
  7954. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7958. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7959. EXPECT_TRUE(res->body.empty());
  7960. }
  7961. TEST_F(StaticFileCompressionTest, MinLength) {
  7962. auto port = start(enable);
  7963. Client cli(HOST, port);
  7964. // 104 bytes, well under the default floor. Compressing it would add the
  7965. // gzip header and trailer to a body that already fits in one packet.
  7966. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::OK_200, res->status);
  7969. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7970. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7971. }
  7972. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7973. auto port = start([](Server &svr) {
  7974. svr.set_static_file_compression(true);
  7975. svr.set_static_file_compression_min_length(1);
  7976. });
  7977. Client cli(HOST, port);
  7978. cli.set_decompress(false);
  7979. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7982. // A 9-byte file comes back larger than it went in, because gzip's header and
  7983. // trailer outweigh anything deflate can save. That is the end of the range
  7984. // the floor exists to keep out.
  7985. EXPECT_GT(res->body.size(), 9U);
  7986. }
  7987. TEST_F(StaticFileCompressionTest, MaxLength) {
  7988. auto port = start([](Server &svr) {
  7989. svr.set_static_file_compression(true);
  7990. svr.set_static_file_compression_min_length(0);
  7991. svr.set_static_file_compression_max_length(1024);
  7992. });
  7993. Client cli(HOST, port);
  7994. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7995. // defines `small` as a macro on Windows.
  7996. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7997. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7998. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7999. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8000. // Under it: compressed.
  8001. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8002. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8003. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8004. }
  8005. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8006. auto port = start(enable_without_floor);
  8007. Client cli(HOST, port);
  8008. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8009. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8010. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8011. auto identity_etag = identity->get_header_value("ETag");
  8012. ASSERT_FALSE(identity_etag.empty());
  8013. auto gzipped =
  8014. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8015. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8016. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8017. auto gzip_etag = gzipped->get_header_value("ETag");
  8018. ASSERT_FALSE(gzip_etag.empty());
  8019. // Two representations, two validators.
  8020. EXPECT_NE(identity_etag, gzip_etag);
  8021. // Each one revalidates against the request that would produce it...
  8022. auto fresh =
  8023. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8024. {"If-None-Match", gzip_etag}});
  8025. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8026. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8027. auto fresh_identity =
  8028. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8029. {"If-None-Match", identity_etag}});
  8030. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8031. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8032. // ...and not against the other representation.
  8033. auto crossed =
  8034. cli.Get("/dir/index.html",
  8035. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8036. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8037. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8038. }
  8039. // The opt-in covers responses the server reads off disk itself. A caller's own
  8040. // known-length provider keeps its Content-Length and, more importantly, keeps
  8041. // delivering incrementally: routing it through a compressor would hold every
  8042. // write back until zlib's window filled.
  8043. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8044. auto port = start(enable);
  8045. Client cli(HOST, port);
  8046. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8050. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8051. EXPECT_EQ("aaabbb", res->body);
  8052. }
  8053. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8054. auto port = start(enable);
  8055. Client cli(HOST, port);
  8056. cli.set_read_timeout(1, 0);
  8057. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8058. Headers{{"Accept-Encoding", "gzip"}});
  8059. ASSERT_TRUE(handle.is_valid());
  8060. // The provider writes 100 bytes and then stalls for longer than the read
  8061. // timeout. Those first bytes have to arrive anyway: run the response through
  8062. // a compressor and zlib holds them until its window fills, so the read would
  8063. // come back empty instead.
  8064. char buf[256];
  8065. auto n = handle.read(buf, sizeof(buf));
  8066. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8067. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8068. }
  8069. #endif
  8070. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8071. TEST_F(ServerTest, Brotli) {
  8072. Headers headers;
  8073. headers.emplace("Accept-Encoding", "br");
  8074. auto res = cli_.Get("/compress", headers);
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. res->body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. #endif
  8085. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8086. TEST_F(ServerTest, Zstd) {
  8087. Headers headers;
  8088. headers.emplace("Accept-Encoding", "zstd");
  8089. auto res = cli_.Get("/compress", headers);
  8090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8091. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8093. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8094. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8095. "7890123456789012345678901234567890",
  8096. res->body);
  8097. EXPECT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8100. Headers headers;
  8101. headers.emplace("Accept-Encoding", "");
  8102. auto res = cli_.Get("/compress", headers);
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8106. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8107. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8108. "7890123456789012345678901234567890",
  8109. res->body);
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. }
  8112. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8113. Headers headers;
  8114. headers.emplace("Accept-Encoding", "zstd");
  8115. std::string body;
  8116. auto res = cli_.Get("/compress", headers,
  8117. [&](const char *data, uint64_t data_length) {
  8118. EXPECT_EQ(100U, data_length);
  8119. body.append(data, data_length);
  8120. return true;
  8121. });
  8122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8123. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8126. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8127. "7890123456789012345678901234567890",
  8128. body);
  8129. EXPECT_EQ(StatusCode::OK_200, res->status);
  8130. }
  8131. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8132. Headers headers;
  8133. headers.emplace("Accept-Encoding", "zstd");
  8134. cli_.set_decompress(false);
  8135. auto res = cli_.Get("/compress", headers);
  8136. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8137. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8138. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8139. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8143. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. ASSERT_EQ(26U, res->body.size());
  8146. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8147. 0);
  8148. }
  8149. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8150. Headers headers;
  8151. headers.emplace("Accept-Encoding", "");
  8152. std::string body;
  8153. auto res = cli_.Get("/compress", headers,
  8154. [&](const char *data, uint64_t data_length) {
  8155. EXPECT_EQ(100U, data_length);
  8156. body.append(data, data_length);
  8157. return true;
  8158. });
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8162. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8164. "7890123456789012345678901234567890",
  8165. body);
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. }
  8168. TEST_F(ServerTest, NoZstd) {
  8169. Headers headers;
  8170. headers.emplace("Accept-Encoding", "zstd");
  8171. auto res = cli_.Get("/nocompress", headers);
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8174. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8175. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8177. "7890123456789012345678901234567890",
  8178. res->body);
  8179. EXPECT_EQ(StatusCode::OK_200, res->status);
  8180. }
  8181. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8182. Headers headers;
  8183. headers.emplace("Accept-Encoding", "zstd");
  8184. std::string body;
  8185. auto res = cli_.Get("/nocompress", headers,
  8186. [&](const char *data, uint64_t data_length) {
  8187. EXPECT_EQ(100U, data_length);
  8188. body.append(data, data_length);
  8189. return true;
  8190. });
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8196. "7890123456789012345678901234567890",
  8197. body);
  8198. EXPECT_EQ(StatusCode::OK_200, res->status);
  8199. }
  8200. // TODO: How to enable zstd ??
  8201. TEST_F(ServerTest, MultipartFormDataZstd) {
  8202. UploadFormDataItems items = {
  8203. {"key1", "test", "", ""},
  8204. {"key2", "--abcdefg123", "", ""},
  8205. };
  8206. Headers headers;
  8207. headers.emplace("Accept-Encoding", "zstd");
  8208. cli_.set_compress(true);
  8209. auto res = cli_.Post("/compress-multipart", headers, items);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8214. Headers headers;
  8215. headers.emplace("Accept-Encoding", "zstd");
  8216. cli_.set_compress(true);
  8217. auto res = cli_.Put(
  8218. "/put", headers, 3,
  8219. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8220. sink.os << "PUT";
  8221. return true;
  8222. },
  8223. "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("PUT", res->body);
  8227. }
  8228. // Pre-compression logging tests
  8229. TEST_F(ServerTest, PreCompressionLogging) {
  8230. // Test data for compression (matches the actual /compress endpoint content)
  8231. const std::string test_content =
  8232. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8233. "3456789012345678901234567890";
  8234. // Variables to capture logging data
  8235. std::string pre_compression_body;
  8236. std::string pre_compression_content_type;
  8237. std::string pre_compression_content_encoding;
  8238. std::string post_compression_body;
  8239. std::string post_compression_content_type;
  8240. std::string post_compression_content_encoding;
  8241. // Set up pre-compression logger
  8242. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8243. const Response &res) {
  8244. pre_compression_body = res.body;
  8245. pre_compression_content_type = res.get_header_value("Content-Type");
  8246. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8247. });
  8248. // Set up post-compression logger
  8249. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8250. post_compression_body = res.body;
  8251. post_compression_content_type = res.get_header_value("Content-Type");
  8252. post_compression_content_encoding =
  8253. res.get_header_value("Content-Encoding");
  8254. });
  8255. // Test with gzip compression
  8256. Headers headers;
  8257. headers.emplace("Accept-Encoding", "gzip");
  8258. auto res = cli_.Get("/compress", headers);
  8259. // Verify response was compressed
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8263. // Verify pre-compression logger captured uncompressed content
  8264. EXPECT_EQ(test_content, pre_compression_body);
  8265. EXPECT_EQ("text/plain", pre_compression_content_type);
  8266. EXPECT_TRUE(pre_compression_content_encoding
  8267. .empty()); // No encoding header before compression
  8268. // Verify post-compression logger captured compressed content
  8269. EXPECT_NE(test_content,
  8270. post_compression_body); // Should be different after compression
  8271. EXPECT_EQ("text/plain", post_compression_content_type);
  8272. EXPECT_EQ("gzip", post_compression_content_encoding);
  8273. // Verify compressed content is smaller
  8274. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8275. }
  8276. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8277. const std::string test_content =
  8278. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8279. "3456789012345678901234567890";
  8280. std::string pre_compression_body;
  8281. std::string post_compression_body;
  8282. svr_.set_pre_compression_logger(
  8283. [&](const Request & /*req*/, const Response &res) {
  8284. pre_compression_body = res.body;
  8285. });
  8286. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8287. post_compression_body = res.body;
  8288. });
  8289. Headers headers;
  8290. headers.emplace("Accept-Encoding", "br");
  8291. auto res = cli_.Get("/compress", headers);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8295. // Verify pre-compression content is uncompressed
  8296. EXPECT_EQ(test_content, pre_compression_body);
  8297. // Verify post-compression content is compressed
  8298. EXPECT_NE(test_content, post_compression_body);
  8299. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8300. }
  8301. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8302. const std::string test_content =
  8303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8304. "3456789012345678901234567890";
  8305. std::string pre_compression_body;
  8306. std::string post_compression_body;
  8307. svr_.set_pre_compression_logger(
  8308. [&](const Request & /*req*/, const Response &res) {
  8309. pre_compression_body = res.body;
  8310. });
  8311. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8312. post_compression_body = res.body;
  8313. });
  8314. // Request without compression (use /nocompress endpoint)
  8315. Headers headers;
  8316. auto res = cli_.Get("/nocompress", headers);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::OK_200, res->status);
  8319. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8320. // Pre-compression logger should not be called when no compression is applied
  8321. EXPECT_TRUE(
  8322. pre_compression_body.empty()); // Pre-compression logger not called
  8323. EXPECT_EQ(
  8324. test_content,
  8325. post_compression_body); // Post-compression logger captures final content
  8326. }
  8327. TEST_F(ServerTest, LoggerSeesContentLength) {
  8328. size_t logged_content_length = 0;
  8329. std::string logged_content_length_header;
  8330. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8331. logged_content_length = res.content_length_;
  8332. logged_content_length_header = res.get_header_value("Content-Length");
  8333. });
  8334. auto res = cli_.Get("/nocompress");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ(res->body.size(), logged_content_length);
  8338. EXPECT_EQ(std::to_string(logged_content_length),
  8339. logged_content_length_header);
  8340. }
  8341. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8342. const std::string test_content =
  8343. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8344. "3456789012345678901234567890";
  8345. std::string pre_compression_body;
  8346. bool pre_logger_called = false;
  8347. // Set only pre-compression logger
  8348. svr_.set_pre_compression_logger(
  8349. [&](const Request & /*req*/, const Response &res) {
  8350. pre_compression_body = res.body;
  8351. pre_logger_called = true;
  8352. });
  8353. Headers headers;
  8354. headers.emplace("Accept-Encoding", "gzip");
  8355. auto res = cli_.Get("/compress", headers);
  8356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8357. EXPECT_EQ(StatusCode::OK_200, res->status);
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. // Verify pre-compression logger was called
  8360. EXPECT_TRUE(pre_logger_called);
  8361. EXPECT_EQ(test_content, pre_compression_body);
  8362. }
  8363. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8364. {
  8365. // Test with Expect: 100-continue header - success case
  8366. // Server returns 100 Continue, client sends body, server returns 200 OK
  8367. Request req;
  8368. req.method = "POST";
  8369. req.path = "/post-large";
  8370. req.set_header("Expect", "100-continue");
  8371. req.body = LARGE_DATA;
  8372. Response res;
  8373. auto error = Error::Success;
  8374. cli_.set_keep_alive(true);
  8375. auto ret = cli_.send(req, res, error);
  8376. EXPECT_TRUE(ret);
  8377. EXPECT_EQ(StatusCode::OK_200, res.status);
  8378. EXPECT_EQ(LARGE_DATA, res.body);
  8379. }
  8380. {
  8381. // Test with Expect: 100-continue header - error case
  8382. // Client should not send the body when server returns an error
  8383. Request req;
  8384. req.method = "POST";
  8385. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8386. req.set_header("Expect", "100-continue");
  8387. req.body = LARGE_DATA;
  8388. Response res;
  8389. auto error = Error::Success;
  8390. auto start = std::chrono::high_resolution_clock::now();
  8391. cli_.set_keep_alive(true);
  8392. auto ret = cli_.send(req, res, error);
  8393. auto end = std::chrono::high_resolution_clock::now();
  8394. auto elapsed =
  8395. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8396. .count();
  8397. // With Expect: 100-continue, request completes successfully but with error
  8398. EXPECT_TRUE(ret);
  8399. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8400. EXPECT_EQ("close", res.get_header_value("Connection"));
  8401. EXPECT_FALSE(cli_.is_socket_open());
  8402. EXPECT_LE(elapsed, 2000);
  8403. }
  8404. {
  8405. // Send an extra GET request to ensure error recovery without hanging
  8406. Request req;
  8407. req.method = "GET";
  8408. req.path = "/hi";
  8409. auto start = std::chrono::high_resolution_clock::now();
  8410. auto res = cli_.send(req);
  8411. auto end = std::chrono::high_resolution_clock::now();
  8412. auto elapsed =
  8413. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8414. .count();
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. EXPECT_EQ("Hello World!", res->body);
  8418. EXPECT_LE(elapsed, 500);
  8419. }
  8420. }
  8421. TEST(ZstdDecompressor, ChunkedDecompression) {
  8422. std::string data;
  8423. for (size_t i = 0; i < 32 * 1024; ++i) {
  8424. data.push_back(static_cast<char>('a' + i % 26));
  8425. }
  8426. std::string compressed_data;
  8427. {
  8428. httplib::detail::zstd_compressor compressor;
  8429. bool result = compressor.compress(
  8430. data.data(), data.size(),
  8431. /*last=*/true,
  8432. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8433. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8434. compressed_data_size);
  8435. return true;
  8436. });
  8437. ASSERT_TRUE(result);
  8438. }
  8439. std::string decompressed_data;
  8440. {
  8441. httplib::detail::zstd_decompressor decompressor;
  8442. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8443. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8444. size_t chunk_size = 130;
  8445. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8446. chunk_begin += chunk_size) {
  8447. size_t current_chunk_size =
  8448. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8449. bool result = decompressor.decompress(
  8450. compressed_data.data() + chunk_begin, current_chunk_size,
  8451. [&](const char *decompressed_data_chunk,
  8452. size_t decompressed_data_chunk_size) {
  8453. decompressed_data.insert(decompressed_data.size(),
  8454. decompressed_data_chunk,
  8455. decompressed_data_chunk_size);
  8456. return true;
  8457. });
  8458. ASSERT_TRUE(result);
  8459. }
  8460. }
  8461. ASSERT_EQ(data, decompressed_data);
  8462. }
  8463. TEST(ZstdDecompressor, Decompress) {
  8464. std::string original_text = "Compressed with ZSTD";
  8465. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8466. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8467. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8468. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8469. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8470. std::string decompressed_data;
  8471. {
  8472. httplib::detail::zstd_decompressor decompressor;
  8473. bool result = decompressor.decompress(
  8474. compressed_data.data(), compressed_data.size(),
  8475. [&](const char *decompressed_data_chunk,
  8476. size_t decompressed_data_chunk_size) {
  8477. decompressed_data.insert(decompressed_data.size(),
  8478. decompressed_data_chunk,
  8479. decompressed_data_chunk_size);
  8480. return true;
  8481. });
  8482. ASSERT_TRUE(result);
  8483. }
  8484. ASSERT_EQ(original_text, decompressed_data);
  8485. }
  8486. #endif
  8487. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8488. // separate chunks so that the server sees each part in its own read(). Used to
  8489. // place a read boundary at a specific offset of a request body.
  8490. static bool send_request_in_parts(time_t read_timeout_sec,
  8491. const std::vector<std::string> &parts,
  8492. std::string *resp = nullptr,
  8493. int port = PORT) {
  8494. auto error = Error::Success;
  8495. auto client_sock = detail::create_client_socket(
  8496. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8497. /*connection_timeout_sec=*/5, 0,
  8498. /*read_timeout_sec=*/5, 0,
  8499. /*write_timeout_sec=*/5, 0, std::string(), error);
  8500. if (client_sock == INVALID_SOCKET) { return false; }
  8501. auto ret = detail::process_client_socket(
  8502. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8503. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8504. for (size_t i = 0; i < parts.size(); i++) {
  8505. const auto &part = parts[i];
  8506. if (part.size() !=
  8507. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8508. return false;
  8509. }
  8510. if (i + 1 < parts.size()) {
  8511. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8512. }
  8513. }
  8514. char buf[512];
  8515. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8516. while (line_reader.getline()) {
  8517. if (resp) { *resp += line_reader.ptr(); }
  8518. }
  8519. return true;
  8520. });
  8521. detail::close_socket(client_sock);
  8522. return ret;
  8523. }
  8524. // Sends a raw request to a server listening at HOST:PORT.
  8525. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8526. std::string *resp = nullptr, int port = PORT) {
  8527. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8528. }
  8529. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8530. Server svr;
  8531. std::string header_value;
  8532. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8533. header_value = req.get_header_value("foo");
  8534. res.set_content("ok", "text/plain");
  8535. });
  8536. thread t = thread([&] { svr.listen(HOST, PORT); });
  8537. auto se = detail::scope_exit([&] {
  8538. svr.stop();
  8539. t.join();
  8540. ASSERT_FALSE(svr.is_running());
  8541. });
  8542. svr.wait_until_ready();
  8543. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8544. // like characters are not treated the same - use vertical tab and escape.
  8545. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8546. "foo: \t \v bar \x1B\t \r\n"
  8547. "Connection: close\r\n"
  8548. "\r\n";
  8549. std::string res;
  8550. ASSERT_TRUE(send_request(5, req, &res));
  8551. EXPECT_EQ(header_value, "");
  8552. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8553. }
  8554. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8555. Server svr;
  8556. std::string received;
  8557. svr.Get("/order", [&](const Request &req, Response &res) {
  8558. received = entries_to_string(req.headers);
  8559. res.set_content("ok", "text/plain");
  8560. });
  8561. auto port = svr.bind_to_any_port(HOST);
  8562. thread t = thread([&] { svr.listen_after_bind(); });
  8563. auto se = detail::scope_exit([&] {
  8564. svr.stop();
  8565. t.join();
  8566. ASSERT_FALSE(svr.is_running());
  8567. });
  8568. svr.wait_until_ready();
  8569. const std::string req = "GET /order HTTP/1.1\r\n"
  8570. "X-First: 1\r\n"
  8571. "X-Dup: a\r\n"
  8572. "X-Second: 2\r\n"
  8573. "X-Dup: b\r\n"
  8574. "Connection: close\r\n"
  8575. "\r\n";
  8576. std::string res;
  8577. ASSERT_TRUE(send_request(5, req, &res, port));
  8578. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8579. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8580. }
  8581. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8582. Server svr;
  8583. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8584. res.set_header("Set-Cookie", "first=1");
  8585. res.set_header("X-Between", "y");
  8586. res.set_header("Set-Cookie", "second=2");
  8587. res.set_content("ok", "text/plain");
  8588. });
  8589. auto port = svr.bind_to_any_port(HOST);
  8590. thread t = thread([&] { svr.listen_after_bind(); });
  8591. auto se = detail::scope_exit([&] {
  8592. svr.stop();
  8593. t.join();
  8594. ASSERT_FALSE(svr.is_running());
  8595. });
  8596. svr.wait_until_ready();
  8597. Client cli(HOST, port);
  8598. auto res = cli.Get("/cookies");
  8599. ASSERT_TRUE(res);
  8600. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8601. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8602. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8603. }
  8604. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8605. Server svr;
  8606. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8607. auto i = new int(0);
  8608. res.set_header("Trailer", "X-Safe, X-Reflected");
  8609. res.set_chunked_content_provider(
  8610. "text/plain",
  8611. [i](size_t /*offset*/, DataSink &sink) {
  8612. if (*i == 0) {
  8613. sink.os << "body";
  8614. } else {
  8615. Headers trailer;
  8616. // A valid trailer that must survive.
  8617. trailer.emplace("X-Safe", "safe");
  8618. // Attacker-controlled value carrying CR/LF (response splitting).
  8619. trailer.emplace("X-Reflected",
  8620. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8621. // Attacker-controlled name carrying CR/LF.
  8622. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8623. sink.done_with_trailer(trailer);
  8624. }
  8625. (*i)++;
  8626. return true;
  8627. },
  8628. [i](bool /*success*/) { delete i; });
  8629. });
  8630. thread t = thread([&] { svr.listen(HOST, PORT); });
  8631. auto se = detail::scope_exit([&] {
  8632. svr.stop();
  8633. t.join();
  8634. ASSERT_FALSE(svr.is_running());
  8635. });
  8636. svr.wait_until_ready();
  8637. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8638. "Host: " + HOST +
  8639. "\r\n"
  8640. "Connection: close\r\n"
  8641. "\r\n";
  8642. std::string res;
  8643. ASSERT_TRUE(send_request(5, req, &res));
  8644. // The injected fields must not appear anywhere in the raw response.
  8645. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8646. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8647. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8648. // Invalid trailers are dropped entirely, matching set_header().
  8649. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8650. // The valid trailer still passes through.
  8651. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8652. }
  8653. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8654. Server svr;
  8655. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8656. // res.headers is a public field an application can populate directly,
  8657. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8658. // A valid header that must survive.
  8659. res.headers.emplace("X-Safe", "safe");
  8660. // Attacker-controlled value carrying CR/LF (response splitting).
  8661. res.headers.emplace("X-Reflected",
  8662. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8663. // Attacker-controlled name carrying CR/LF.
  8664. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8665. res.set_content("body", "text/plain");
  8666. });
  8667. thread t = thread([&] { svr.listen(HOST, PORT); });
  8668. auto se = detail::scope_exit([&] {
  8669. svr.stop();
  8670. t.join();
  8671. ASSERT_FALSE(svr.is_running());
  8672. });
  8673. svr.wait_until_ready();
  8674. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8675. "Host: " + HOST +
  8676. "\r\n"
  8677. "Connection: close\r\n"
  8678. "\r\n";
  8679. std::string res;
  8680. ASSERT_TRUE(send_request(5, req, &res));
  8681. // The injected fields must not appear anywhere in the raw response.
  8682. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8683. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8684. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8685. // Invalid headers are dropped entirely, matching set_header().
  8686. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8687. // The valid header still passes through.
  8688. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8689. }
  8690. // Forward declaration: in split builds split.py strips `inline` and moves the
  8691. // definition into httplib.cc, so detail::write_request_line is not visible from
  8692. // the public httplib.h. Re-declaring it here lets the tests link against the
  8693. // symbol in both header-only and split builds.
  8694. namespace httplib {
  8695. namespace detail {
  8696. ssize_t write_request_line(Stream &strm, const std::string &method,
  8697. const std::string &path);
  8698. } // namespace detail
  8699. } // namespace httplib
  8700. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8701. // A well-formed target is written verbatim.
  8702. {
  8703. detail::BufferStream strm;
  8704. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8705. EXPECT_GT(n, 0);
  8706. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8707. }
  8708. // A target carrying CR/LF, SP or other control octets must be rejected
  8709. // before anything reaches the wire, otherwise it splits the request line and
  8710. // injects a header or a whole request.
  8711. const std::string evil_targets[] = {
  8712. "/a\r\nInjected: pwned",
  8713. "/a\rInjected",
  8714. "/a\nInjected",
  8715. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8716. "/a b",
  8717. "/a\tb",
  8718. "/a\x7f",
  8719. };
  8720. for (const auto &evil : evil_targets) {
  8721. detail::BufferStream strm;
  8722. auto n = detail::write_request_line(strm, "GET", evil);
  8723. EXPECT_LT(n, 0);
  8724. EXPECT_TRUE(strm.get_buffer().empty());
  8725. }
  8726. }
  8727. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8728. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8729. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8730. // target reaches write_request. The client must fail cleanly with
  8731. // Error::Write instead of putting a request-line-less, header-injecting
  8732. // request on the wire.
  8733. Server svr;
  8734. svr.Get("/a", [](const Request &, Response &res) {
  8735. res.set_content("ok", "text/plain");
  8736. });
  8737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8738. auto se = detail::scope_exit([&] {
  8739. svr.stop();
  8740. thread.join();
  8741. ASSERT_FALSE(svr.is_running());
  8742. });
  8743. svr.wait_until_ready();
  8744. {
  8745. Client cli(HOST, PORT);
  8746. cli.set_path_encode(false);
  8747. // The request is rejected before anything is written, so the connection
  8748. // stays silent and the subsequent response read would otherwise block for
  8749. // the full default read timeout. Shorten it -- the assertion is on the
  8750. // error, not the timeout.
  8751. cli.set_read_timeout(1, 0);
  8752. auto res = cli.Get("/a\r\nInjected: pwned");
  8753. EXPECT_FALSE(res);
  8754. EXPECT_EQ(Error::Write, res.error());
  8755. }
  8756. }
  8757. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8758. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8759. // including extension methods.
  8760. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8761. for (const auto &method : good_methods) {
  8762. detail::BufferStream strm;
  8763. auto n = detail::write_request_line(strm, method, "/");
  8764. EXPECT_GT(n, 0);
  8765. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8766. }
  8767. // A method carrying CR/LF would split the request line and smuggle a whole
  8768. // request ahead of the real one. A space or an empty method corrupts the
  8769. // request line. All must be rejected before anything reaches the wire.
  8770. const std::string evil_methods[] = {
  8771. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8772. "GET\r\nInjected: pwned",
  8773. "GET\r",
  8774. "GET\n",
  8775. "GE T",
  8776. "",
  8777. };
  8778. for (const auto &evil : evil_methods) {
  8779. detail::BufferStream strm;
  8780. auto n = detail::write_request_line(strm, evil, "/");
  8781. EXPECT_LT(n, 0);
  8782. EXPECT_TRUE(strm.get_buffer().empty());
  8783. }
  8784. }
  8785. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8786. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8787. // through Client::send must fail with Error::Write and no request, neither
  8788. // the smuggled one nor the real one, may reach the server.
  8789. Server svr;
  8790. std::atomic<int> request_count(0);
  8791. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8792. request_count++;
  8793. res.status = StatusCode::OK_200;
  8794. return Server::HandlerResponse::Handled;
  8795. });
  8796. auto port = svr.bind_to_any_port(HOST);
  8797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8798. auto se = detail::scope_exit([&] {
  8799. svr.stop();
  8800. thread.join();
  8801. ASSERT_FALSE(svr.is_running());
  8802. });
  8803. svr.wait_until_ready();
  8804. {
  8805. Client cli(HOST, port);
  8806. const std::string evil_methods[] = {
  8807. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8808. "GE T",
  8809. "",
  8810. };
  8811. for (const auto &evil : evil_methods) {
  8812. Request req;
  8813. req.method = evil;
  8814. req.path = "/";
  8815. auto res = cli.send(req);
  8816. EXPECT_FALSE(res);
  8817. EXPECT_EQ(Error::Write, res.error());
  8818. }
  8819. auto handle =
  8820. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8821. EXPECT_FALSE(handle.is_valid());
  8822. EXPECT_EQ(Error::Write, handle.error);
  8823. // A valid request on the same client still goes through.
  8824. auto res = cli.Get("/");
  8825. ASSERT_TRUE(res);
  8826. EXPECT_EQ(StatusCode::OK_200, res->status);
  8827. }
  8828. EXPECT_EQ(1, request_count.load());
  8829. }
  8830. // Sends a raw request and verifies that there isn't a crash or exception.
  8831. static void test_raw_request(const std::string &req,
  8832. std::string *out = nullptr) {
  8833. Server svr;
  8834. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8835. res.set_content("ok", "text/plain");
  8836. });
  8837. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8838. res.set_content("ok", "text/plain");
  8839. });
  8840. svr.Get("/header_field_value_check",
  8841. [&](const Request & /*req*/, Response &res) {
  8842. res.set_content("ok", "text/plain");
  8843. });
  8844. svr.CustomRoute("PROPFIND", "/dav",
  8845. [&](const Request & /*req*/, Response &res) {
  8846. res.status = StatusCode::MultiStatus_207;
  8847. });
  8848. // Server read timeout must be longer than the client read timeout for the
  8849. // bug to reproduce, probably to force the server to process a request
  8850. // without a trailing blank line.
  8851. const time_t client_read_timeout_sec = 1;
  8852. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8853. bool listen_thread_ok = false;
  8854. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8855. auto se = detail::scope_exit([&] {
  8856. svr.stop();
  8857. t.join();
  8858. ASSERT_FALSE(svr.is_running());
  8859. EXPECT_TRUE(listen_thread_ok);
  8860. });
  8861. svr.wait_until_ready();
  8862. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8863. }
  8864. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8865. // A certain header line causes an exception if the header property is parsed
  8866. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8867. test_raw_request(
  8868. "GET /hi HTTP/1.1\r\n"
  8869. " : "
  8870. " "
  8871. " ");
  8872. }
  8873. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8874. // A certain header line causes an exception if the header property *name* is
  8875. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8876. // greedy matcher and requires backtracking when there are a lot of ":"
  8877. // characters.
  8878. // This occurs with libc++ but not libstdc++.
  8879. test_raw_request(
  8880. "GET /hi HTTP/1.1\r\n"
  8881. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8882. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8883. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8884. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8885. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8886. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8887. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8888. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8889. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8890. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8891. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8892. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8893. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8894. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8895. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8896. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8897. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8898. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8899. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8900. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8901. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8902. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8903. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8904. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8905. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8906. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8907. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8908. "&&&%%%");
  8909. }
  8910. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8911. // Make sure this doesn't crash the server.
  8912. // In a previous version of the header line regex, the "\r" rendered the line
  8913. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8914. // a new position where the leading white space ended and the field value
  8915. // began.
  8916. // The crash occurs with libc++ but not libstdc++.
  8917. test_raw_request("GET /hi HTTP/1.1\r\n"
  8918. "a:" +
  8919. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8920. "\r\n"
  8921. "\r\n");
  8922. }
  8923. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8924. std::string out;
  8925. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8926. "Content-Type: text/plain\r\n"
  8927. "Transfer-Encoding: chunked\r\n"
  8928. "\r\n"
  8929. "nothex\r\n",
  8930. &out);
  8931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8932. }
  8933. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8934. std::string out;
  8935. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8936. "Content-Type: text/plain\r\n"
  8937. "Transfer-Encoding: chunked\r\n"
  8938. "\r\n"
  8939. "3\r\n"
  8940. "xyz\r\n"
  8941. "NaN\r\n",
  8942. &out);
  8943. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8944. }
  8945. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8946. std::string out;
  8947. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8948. "Content-Type: text/plain\r\n"
  8949. "Transfer-Encoding: chunked\r\n"
  8950. "\r\n"
  8951. // Length is too large for 64 bits.
  8952. "1ffffffffffffffff\r\n"
  8953. "xyz\r\n",
  8954. &out);
  8955. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8956. }
  8957. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8958. test_raw_request("GET /hi HTTP/1.1\r\n"
  8959. "Content-Type: text/plain\r\n\r");
  8960. }
  8961. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8962. std::string out;
  8963. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8964. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8965. }
  8966. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8967. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8968. std::string out;
  8969. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8970. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8971. }
  8972. }
  8973. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8974. std::string out;
  8975. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8976. "Connection: close\r\n\r\n",
  8977. &out);
  8978. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8979. }
  8980. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8981. Server svr;
  8982. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8983. EXPECT_TRUE(!req.remote_addr.empty());
  8984. });
  8985. thread t = thread([&] { svr.listen(HOST, PORT); });
  8986. auto se = detail::scope_exit([&] {
  8987. svr.stop();
  8988. t.join();
  8989. ASSERT_FALSE(svr.is_running());
  8990. });
  8991. svr.wait_until_ready();
  8992. // Send an invalid request line to trigger Bad Request
  8993. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8994. std::string out;
  8995. ASSERT_TRUE(send_request(5, bad_req, &out));
  8996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8997. }
  8998. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8999. // answered right away rather than blocking on a read that waits for EOF.
  9000. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9001. std::string out;
  9002. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9003. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9004. }
  9005. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9006. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9007. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9008. for (const auto *method : methods) {
  9009. Server svr;
  9010. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9011. EXPECT_FALSE(svr.is_valid()) << method;
  9012. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9013. }
  9014. }
  9015. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9016. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9017. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9018. for (const auto *method : methods) {
  9019. Server svr;
  9020. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9021. EXPECT_FALSE(svr.is_valid()) << method;
  9022. }
  9023. }
  9024. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9025. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9026. "COPY", "MOVE", "LOCK",
  9027. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9028. Server svr;
  9029. for (const auto *method : methods) {
  9030. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9031. }
  9032. EXPECT_TRUE(svr.is_valid());
  9033. }
  9034. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9035. Server svr;
  9036. svr.CustomRoute("POST", "/x",
  9037. [](const Request &, Response &, const ContentReader &) {});
  9038. EXPECT_FALSE(svr.is_valid());
  9039. }
  9040. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9041. Server svr;
  9042. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9043. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9044. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9045. EXPECT_FALSE(svr.is_valid());
  9046. }
  9047. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9048. Server svr;
  9049. auto captured = Error::Success;
  9050. svr.set_error_logger(
  9051. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9052. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9053. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9054. }
  9055. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9056. std::string out;
  9057. std::string request(
  9058. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9059. test_raw_request(request, &out);
  9060. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9061. }
  9062. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9063. std::string out;
  9064. std::string request(
  9065. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9066. test_raw_request(request, &out);
  9067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9068. }
  9069. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9070. std::string out;
  9071. std::string request(
  9072. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9073. test_raw_request(request, &out);
  9074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9075. }
  9076. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9077. std::string out;
  9078. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9079. "Test: \r\n\r\n",
  9080. &out);
  9081. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9082. }
  9083. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9084. Server svr;
  9085. std::string x_custom;
  9086. std::string cookie;
  9087. std::string xff;
  9088. std::string x_unicode;
  9089. std::string x_iis;
  9090. svr.Get("/check", [&](const Request &req, Response &res) {
  9091. x_custom = req.get_header_value("X-Custom");
  9092. cookie = req.get_header_value("Cookie");
  9093. xff = req.get_header_value("X-Forwarded-For");
  9094. x_unicode = req.get_header_value("X-Unicode");
  9095. x_iis = req.get_header_value("X-IIS");
  9096. res.set_content("ok", "text/plain");
  9097. });
  9098. thread t = thread([&] { svr.listen(HOST, PORT); });
  9099. auto se = detail::scope_exit([&] {
  9100. svr.stop();
  9101. t.join();
  9102. ASSERT_FALSE(svr.is_running());
  9103. });
  9104. svr.wait_until_ready();
  9105. const std::string req = "GET /check HTTP/1.1\r\n"
  9106. "Host: localhost\r\n"
  9107. "X-Custom: a%0D%0AInjected: b\r\n"
  9108. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9109. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9110. "X-Unicode: %E3%81%82\r\n"
  9111. "X-IIS: %u00E9\r\n"
  9112. "Connection: close\r\n"
  9113. "\r\n";
  9114. std::string res;
  9115. ASSERT_TRUE(send_request(5, req, &res));
  9116. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9117. // Every value must be returned verbatim (wire form), with no decoding.
  9118. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9119. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9120. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9121. EXPECT_EQ("%E3%81%82", x_unicode);
  9122. EXPECT_EQ("%u00E9", x_iis);
  9123. }
  9124. // Applications that previously relied on automatic percent-decoding can
  9125. // reproduce the old behavior by explicitly calling decode_path_component()
  9126. // or, for RFC 3986 conformance, decode_uri_component().
  9127. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9128. Server svr;
  9129. std::string decoded;
  9130. svr.Get("/check", [&](const Request &req, Response &res) {
  9131. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9132. res.set_content("ok", "text/plain");
  9133. });
  9134. thread t = thread([&] { svr.listen(HOST, PORT); });
  9135. auto se = detail::scope_exit([&] {
  9136. svr.stop();
  9137. t.join();
  9138. ASSERT_FALSE(svr.is_running());
  9139. });
  9140. svr.wait_until_ready();
  9141. const std::string req = "GET /check HTTP/1.1\r\n"
  9142. "Host: localhost\r\n"
  9143. "X-Custom: hello%20world\r\n"
  9144. "Connection: close\r\n"
  9145. "\r\n";
  9146. std::string res;
  9147. ASSERT_TRUE(send_request(5, req, &res));
  9148. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9149. EXPECT_EQ("hello world", decoded);
  9150. }
  9151. // Regression test for #2033. Browsers send Referer values that include
  9152. // percent-encoded characters such as %0A inside the URL. Decoding the
  9153. // header value would either trip the post-decode CR/LF/NUL guard (the
  9154. // original bug, returning 400) or, after that guard was relaxed, silently
  9155. // store a literal LF — both unacceptable. The wire form must round-trip.
  9156. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9157. Server svr;
  9158. std::string referer;
  9159. svr.Get("/check", [&](const Request &req, Response &res) {
  9160. referer = req.get_header_value("Referer");
  9161. res.set_content("ok", "text/plain");
  9162. });
  9163. thread t = thread([&] { svr.listen(HOST, PORT); });
  9164. auto se = detail::scope_exit([&] {
  9165. svr.stop();
  9166. t.join();
  9167. ASSERT_FALSE(svr.is_running());
  9168. });
  9169. svr.wait_until_ready();
  9170. const std::string req = "GET /check HTTP/1.1\r\n"
  9171. "Host: localhost\r\n"
  9172. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9173. "Connection: close\r\n"
  9174. "\r\n";
  9175. std::string res;
  9176. ASSERT_TRUE(send_request(5, req, &res));
  9177. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9178. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9179. }
  9180. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9181. Server svr;
  9182. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9183. res.set_header("Cache-Control", "no-cache");
  9184. res.set_chunked_content_provider(
  9185. "text/event-stream", [](size_t offset, DataSink &sink) {
  9186. std::string s = "data:";
  9187. s += std::to_string(offset);
  9188. s += "\n\n";
  9189. auto ret = sink.write(s.data(), s.size());
  9190. EXPECT_TRUE(ret);
  9191. std::this_thread::sleep_for(std::chrono::seconds(1));
  9192. return true;
  9193. });
  9194. });
  9195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9196. svr.wait_until_ready();
  9197. Client client(HOST, PORT);
  9198. const Headers headers = {{"Accept", "text/event-stream"}};
  9199. auto get_thread = std::thread([&client, &headers]() {
  9200. auto res = client.Get(
  9201. "/events", headers,
  9202. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9203. });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. get_thread.join();
  9207. listen_thread.join();
  9208. ASSERT_FALSE(svr.is_running());
  9209. });
  9210. // Give GET time to get a few messages.
  9211. std::this_thread::sleep_for(std::chrono::seconds(2));
  9212. }
  9213. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9214. httplib::Server svr;
  9215. svr.Post("/hi",
  9216. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9217. res.status = StatusCode::OK_200;
  9218. });
  9219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9220. svr.wait_until_ready();
  9221. Client cli(HOST, PORT);
  9222. auto res = cli.Post("/hi", "data", "text/plain");
  9223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9224. EXPECT_EQ(StatusCode::OK_200, res->status);
  9225. svr.stop();
  9226. thread.join();
  9227. ASSERT_FALSE(svr.is_running());
  9228. res = cli.Post("/hi", "data", "text/plain");
  9229. ASSERT_FALSE(res);
  9230. }
  9231. TEST(ServerStopTest, ListenFailure) {
  9232. Server svr;
  9233. auto t = thread([&]() {
  9234. auto ret = svr.listen("????", PORT);
  9235. EXPECT_FALSE(ret);
  9236. });
  9237. svr.wait_until_ready();
  9238. svr.stop();
  9239. t.join();
  9240. }
  9241. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9242. TEST(ServerStopTest, Decommision) {
  9243. Server svr;
  9244. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9245. for (int i = 0; i < 4; i++) {
  9246. auto is_even = !(i % 2);
  9247. std::thread t{[&] {
  9248. try {
  9249. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9250. if (is_even) {
  9251. throw std::runtime_error("Some thing that happens to go wrong.");
  9252. }
  9253. svr.listen(HOST, PORT);
  9254. } catch (...) { svr.decommission(); }
  9255. }};
  9256. svr.wait_until_ready();
  9257. // Server is up
  9258. {
  9259. Client cli(HOST, PORT);
  9260. auto res = cli.Get("/hi");
  9261. if (is_even) {
  9262. EXPECT_FALSE(res);
  9263. } else {
  9264. EXPECT_TRUE(res);
  9265. EXPECT_EQ("hi...", res->body);
  9266. }
  9267. }
  9268. svr.stop();
  9269. t.join();
  9270. // Server is down...
  9271. {
  9272. Client cli(HOST, PORT);
  9273. auto res = cli.Get("/hi");
  9274. EXPECT_FALSE(res);
  9275. }
  9276. }
  9277. }
  9278. #endif
  9279. // Helper function for string body upload progress tests
  9280. template <typename SetupHandler, typename ClientCall>
  9281. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9282. ClientCall &&client_call,
  9283. const string &body) {
  9284. Server svr;
  9285. setup_handler(svr);
  9286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9287. auto se = detail::scope_exit([&] {
  9288. svr.stop();
  9289. t.join();
  9290. });
  9291. svr.wait_until_ready();
  9292. Client cli(HOST, PORT);
  9293. vector<uint64_t> progress_values;
  9294. bool progress_called = false;
  9295. auto res =
  9296. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9297. progress_values.push_back(current);
  9298. progress_called = true;
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(200, res->status);
  9303. EXPECT_TRUE(progress_called);
  9304. }
  9305. TEST(UploadProgressTest, PostStringBodyBasic) {
  9306. TestStringBodyUploadProgress(
  9307. [](Server &svr) {
  9308. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9309. res.set_content("received", "text/plain");
  9310. });
  9311. },
  9312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9313. return cli.Post("/test", body, "text/plain", progress_callback);
  9314. },
  9315. "test data for upload progress");
  9316. }
  9317. TEST(UploadProgressTest, PutStringBodyBasic) {
  9318. TestStringBodyUploadProgress(
  9319. [](Server &svr) {
  9320. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9321. res.set_content("put received", "text/plain");
  9322. });
  9323. },
  9324. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9325. return cli.Put("/test", body, "text/plain", progress_callback);
  9326. },
  9327. "put test data for upload progress");
  9328. }
  9329. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9330. TestStringBodyUploadProgress(
  9331. [](Server &svr) {
  9332. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9333. res.set_content("patch received", "text/plain");
  9334. });
  9335. },
  9336. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9337. return cli.Patch("/test", body, "text/plain", progress_callback);
  9338. },
  9339. "patch test data for upload progress");
  9340. }
  9341. // Helper function for content provider upload progress tests
  9342. template <typename SetupHandler, typename ClientCall>
  9343. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9344. ClientCall &&client_call) {
  9345. Server svr;
  9346. setup_handler(svr);
  9347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9348. auto se = detail::scope_exit([&] {
  9349. svr.stop();
  9350. t.join();
  9351. });
  9352. svr.wait_until_ready();
  9353. Client cli(HOST, PORT);
  9354. vector<uint64_t> progress_values;
  9355. auto res =
  9356. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9357. progress_values.push_back(current);
  9358. return true;
  9359. });
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(200, res->status);
  9362. EXPECT_FALSE(progress_values.empty());
  9363. }
  9364. TEST(UploadProgressTest, PostContentProviderProgress) {
  9365. TestContentProviderUploadProgress(
  9366. [](Server &svr) {
  9367. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9368. res.set_content("provider received", "text/plain");
  9369. });
  9370. },
  9371. [](Client &cli, UploadProgress progress_callback) {
  9372. return cli.Post(
  9373. "/test", 10,
  9374. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9375. sink.os << "test data";
  9376. return true;
  9377. },
  9378. "text/plain", progress_callback);
  9379. });
  9380. }
  9381. // Helper function for multipart upload progress tests
  9382. template <typename SetupHandler, typename ClientCall>
  9383. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9384. ClientCall &&client_call,
  9385. const string &endpoint) {
  9386. Server svr;
  9387. setup_handler(svr);
  9388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. t.join();
  9392. });
  9393. svr.wait_until_ready();
  9394. Client cli(HOST, PORT);
  9395. vector<uint64_t> progress_values;
  9396. UploadFormDataItems items = {
  9397. {"field1", "value1", "", ""},
  9398. {"field2", "longer value for progress tracking test", "", ""},
  9399. {"file1", "file content data for upload progress", "test.txt",
  9400. "text/plain"}};
  9401. auto res = client_call(cli, endpoint, items,
  9402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9403. progress_values.push_back(current);
  9404. return true;
  9405. });
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ(200, res->status);
  9408. EXPECT_FALSE(progress_values.empty());
  9409. }
  9410. TEST(UploadProgressTest, PostMultipartProgress) {
  9411. TestMultipartUploadProgress(
  9412. [](Server &svr) {
  9413. svr.Post("/multipart", [](const Request &req, Response &res) {
  9414. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9415. res.set_content("multipart received", "text/plain");
  9416. });
  9417. },
  9418. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9419. UploadProgress progress_callback) {
  9420. return cli.Post(endpoint, items, progress_callback);
  9421. },
  9422. "/multipart");
  9423. }
  9424. // Helper function for basic download progress tests
  9425. template <typename SetupHandler, typename ClientCall>
  9426. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9427. ClientCall &&client_call, const string &endpoint,
  9428. size_t expected_content_size) {
  9429. Server svr;
  9430. setup_handler(svr);
  9431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9432. auto se = detail::scope_exit([&] {
  9433. svr.stop();
  9434. t.join();
  9435. });
  9436. svr.wait_until_ready();
  9437. Client cli(HOST, PORT);
  9438. vector<uint64_t> progress_values;
  9439. auto res = client_call(cli, endpoint,
  9440. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9441. progress_values.push_back(current);
  9442. return true;
  9443. });
  9444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9445. EXPECT_EQ(200, res->status);
  9446. EXPECT_FALSE(progress_values.empty());
  9447. EXPECT_EQ(expected_content_size, res->body.size());
  9448. }
  9449. TEST(DownloadProgressTest, GetBasic) {
  9450. TestBasicDownloadProgress(
  9451. [](Server &svr) {
  9452. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9453. string content(1000, 'D');
  9454. res.set_content(content, "text/plain");
  9455. });
  9456. },
  9457. [](Client &cli, const string &endpoint,
  9458. DownloadProgress progress_callback) {
  9459. return cli.Get(endpoint, progress_callback);
  9460. },
  9461. "/download", 1000u);
  9462. }
  9463. // Helper function for content receiver download progress tests
  9464. template <typename SetupHandler, typename ClientCall>
  9465. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9466. ClientCall &&client_call,
  9467. const string &endpoint,
  9468. size_t expected_content_size) {
  9469. Server svr;
  9470. setup_handler(svr);
  9471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9472. auto se = detail::scope_exit([&] {
  9473. svr.stop();
  9474. t.join();
  9475. });
  9476. svr.wait_until_ready();
  9477. Client cli(HOST, PORT);
  9478. vector<uint64_t> progress_values;
  9479. string received_body;
  9480. auto res = client_call(
  9481. cli, endpoint,
  9482. [&](const char *data, size_t data_length) -> bool {
  9483. received_body.append(data, data_length);
  9484. return true;
  9485. },
  9486. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9487. progress_values.push_back(current);
  9488. return true;
  9489. });
  9490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9491. EXPECT_EQ(200, res->status);
  9492. EXPECT_FALSE(progress_values.empty());
  9493. EXPECT_EQ(expected_content_size, received_body.size());
  9494. EXPECT_TRUE(res->body.empty());
  9495. }
  9496. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9497. TestContentReceiverDownloadProgress(
  9498. [](Server &svr) {
  9499. svr.Get("/download-receiver",
  9500. [](const Request & /*req*/, Response &res) {
  9501. string content(2000, 'R');
  9502. res.set_content(content, "text/plain");
  9503. });
  9504. },
  9505. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9506. DownloadProgress progress_callback) {
  9507. return cli.Get(endpoint, content_receiver, progress_callback);
  9508. },
  9509. "/download-receiver", 2000u);
  9510. }
  9511. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9512. // A provider reaching a pass with nothing to hand over - an empty buffer
  9513. // popped off a queue, say - must not be taken to mean the body is finished.
  9514. // It used to end the loop with the terminating chunk unwritten while the
  9515. // server still considered the response complete, so the peer waited for an
  9516. // end that never arrived.
  9517. Server svr;
  9518. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9519. auto step = std::make_shared<int>(0);
  9520. res.set_chunked_content_provider("text/plain",
  9521. [step](size_t /*offset*/, DataSink &sink) {
  9522. switch ((*step)++) {
  9523. case 0: sink.write("", 0); break;
  9524. case 1: sink.write("hello", 5); break;
  9525. default: sink.done(); break;
  9526. }
  9527. return true;
  9528. });
  9529. });
  9530. auto port = svr.bind_to_any_port(HOST);
  9531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9532. auto listen_se = detail::scope_exit([&] {
  9533. svr.stop();
  9534. listen_thread.join();
  9535. ASSERT_FALSE(svr.is_running());
  9536. });
  9537. svr.wait_until_ready();
  9538. Client cli(HOST, port);
  9539. // Without the fix the body is never terminated, so bound the wait rather
  9540. // than letting the test hang on the default read timeout.
  9541. cli.set_read_timeout(5, 0);
  9542. auto res = cli.Get("/stream");
  9543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. EXPECT_EQ("hello", res->body);
  9546. }
  9547. TEST(StreamingTest, NoContentLengthStreaming) {
  9548. Server svr;
  9549. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9550. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9551. if (offset < 6) {
  9552. sink.os << (offset < 3 ? "a" : "b");
  9553. } else {
  9554. sink.done();
  9555. }
  9556. return true;
  9557. });
  9558. });
  9559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9560. auto listen_se = detail::scope_exit([&] {
  9561. svr.stop();
  9562. listen_thread.join();
  9563. ASSERT_FALSE(svr.is_running());
  9564. });
  9565. svr.wait_until_ready();
  9566. Client client(HOST, PORT);
  9567. auto get_thread = std::thread([&client]() {
  9568. std::string s;
  9569. auto res =
  9570. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9571. s += std::string(data, len);
  9572. return true;
  9573. });
  9574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. EXPECT_EQ("aaabbb", s);
  9577. });
  9578. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9579. // Give GET time to get a few messages.
  9580. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9581. }
  9582. TEST(MountTest, Unmount) {
  9583. Server svr;
  9584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. Client cli("localhost", PORT);
  9592. svr.set_mount_point("/mount2", "./www2");
  9593. auto res = cli.Get("/");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9596. res = cli.Get("/mount2/dir/test.html");
  9597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9598. EXPECT_EQ(StatusCode::OK_200, res->status);
  9599. svr.set_mount_point("/", "./www");
  9600. res = cli.Get("/dir/");
  9601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9602. EXPECT_EQ(StatusCode::OK_200, res->status);
  9603. svr.remove_mount_point("/");
  9604. res = cli.Get("/dir/");
  9605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9606. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9607. svr.remove_mount_point("/mount2");
  9608. res = cli.Get("/mount2/dir/test.html");
  9609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9611. }
  9612. TEST(MountTest, PathSegmentBoundary) {
  9613. Server svr;
  9614. svr.set_mount_point("/mount2", "./www2");
  9615. svr.set_mount_point("/", "./www");
  9616. auto port = svr.bind_to_any_port(HOST);
  9617. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9618. auto se = detail::scope_exit([&] {
  9619. svr.stop();
  9620. listen_thread.join();
  9621. ASSERT_FALSE(svr.is_running());
  9622. });
  9623. svr.wait_until_ready();
  9624. Client cli(HOST, port);
  9625. auto res = cli.Get("/mount2/dir/test.html");
  9626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9627. EXPECT_EQ(StatusCode::OK_200, res->status);
  9628. // "/mount2" must not match part-way through a path segment.
  9629. res = cli.Get("/mount2dir/test.html");
  9630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9631. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9632. // A mount point ending in '/' keeps matching every path below it.
  9633. res = cli.Get("/dir/test.html");
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_EQ(StatusCode::OK_200, res->status);
  9636. }
  9637. TEST(MountTest, Redicect) {
  9638. Server svr;
  9639. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9640. auto se = detail::scope_exit([&] {
  9641. svr.stop();
  9642. listen_thread.join();
  9643. ASSERT_FALSE(svr.is_running());
  9644. });
  9645. svr.set_mount_point("/", "./www");
  9646. svr.wait_until_ready();
  9647. Client cli("localhost", PORT);
  9648. auto res = cli.Get("/dir/");
  9649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9650. EXPECT_EQ(StatusCode::OK_200, res->status);
  9651. res = cli.Get("/dir");
  9652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9653. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9654. res = cli.Get("/file");
  9655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9656. EXPECT_EQ(StatusCode::OK_200, res->status);
  9657. res = cli.Get("/file/");
  9658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9659. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9660. cli.set_follow_location(true);
  9661. res = cli.Get("/dir");
  9662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. }
  9665. TEST(MountTest, MultibytesPathName) {
  9666. Server svr;
  9667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. listen_thread.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.set_mount_point("/", "./www");
  9674. svr.wait_until_ready();
  9675. Client cli("localhost", PORT);
  9676. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9678. EXPECT_EQ(StatusCode::OK_200, res->status);
  9679. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9680. }
  9681. #ifdef _WIN32
  9682. // Issue #2435: mmap::open() must succeed even when another handle holds
  9683. // the file open for writing (e.g. an active log file).
  9684. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9685. const char *path = "mmap_concurrent_writer_test.txt";
  9686. const char *content = "hello";
  9687. {
  9688. std::ofstream f(path, std::ios::binary);
  9689. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9690. }
  9691. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9692. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9693. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9694. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9695. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9696. detail::mmap m(path);
  9697. ASSERT_TRUE(m.is_open());
  9698. EXPECT_EQ(strlen(content), m.size());
  9699. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9700. }
  9701. #endif
  9702. #ifndef _WIN32
  9703. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9704. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9705. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9706. TEST(MmapTest, FailedMappingIsNotOpen) {
  9707. const char *path = "./mmap_failed_mapping_test_dir";
  9708. ASSERT_EQ(0, ::mkdir(path, 0755));
  9709. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9710. detail::mmap m(path);
  9711. EXPECT_FALSE(m.is_open());
  9712. EXPECT_EQ(0U, m.size());
  9713. EXPECT_NE(static_cast<const void *>(m.data()),
  9714. static_cast<const void *>(MAP_FAILED));
  9715. }
  9716. #endif
  9717. TEST(KeepAliveTest, ReadTimeout) {
  9718. Server svr;
  9719. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9720. std::this_thread::sleep_for(std::chrono::seconds(2));
  9721. res.set_content("a", "text/plain");
  9722. });
  9723. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9724. res.set_content("b", "text/plain");
  9725. });
  9726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. listen_thread.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. });
  9732. svr.wait_until_ready();
  9733. Client cli("localhost", PORT);
  9734. cli.set_keep_alive(true);
  9735. cli.set_read_timeout(std::chrono::seconds(1));
  9736. auto resa = cli.Get("/a");
  9737. ASSERT_FALSE(resa);
  9738. EXPECT_EQ(Error::Read, resa.error());
  9739. auto resb = cli.Get("/b");
  9740. ASSERT_TRUE(resb);
  9741. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9742. EXPECT_EQ("b", resb->body);
  9743. }
  9744. TEST(KeepAliveTest, MaxCount) {
  9745. size_t keep_alive_max_count = 3;
  9746. Server svr;
  9747. svr.set_keep_alive_max_count(keep_alive_max_count);
  9748. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9749. res.set_content("Hello World!", "text/plain");
  9750. });
  9751. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9752. auto se = detail::scope_exit([&] {
  9753. svr.stop();
  9754. listen_thread.join();
  9755. ASSERT_FALSE(svr.is_running());
  9756. });
  9757. svr.wait_until_ready();
  9758. Client cli(HOST, PORT);
  9759. cli.set_keep_alive(true);
  9760. for (size_t i = 0; i < 5; i++) {
  9761. auto result = cli.Get("/hi");
  9762. ASSERT_TRUE(result);
  9763. EXPECT_EQ(StatusCode::OK_200, result->status);
  9764. if (i == keep_alive_max_count - 1) {
  9765. EXPECT_EQ("close", result->get_header_value("Connection"));
  9766. } else {
  9767. EXPECT_FALSE(result->has_header("Connection"));
  9768. }
  9769. }
  9770. }
  9771. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9772. // can pull the next one into the server's buffer. The server must serve it
  9773. // without waiting for the socket to become readable again. The keep-alive
  9774. // timeout outlasts the client's read timeout, so a request left waiting for it
  9775. // shows up as a missing response.
  9776. static void serve_pipelining_routes(Server &svr,
  9777. const std::function<void(int)> &client) {
  9778. svr.set_keep_alive_timeout(5);
  9779. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9780. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9781. });
  9782. svr.Post("/echo", [](const Request &req, Response &res) {
  9783. res.set_content("echo " + req.body, "text/plain");
  9784. });
  9785. auto port = svr.bind_to_any_port(HOST);
  9786. thread t = thread([&] { svr.listen_after_bind(); });
  9787. auto se = detail::scope_exit([&] {
  9788. svr.stop();
  9789. t.join();
  9790. });
  9791. svr.wait_until_ready();
  9792. client(port);
  9793. }
  9794. static std::string
  9795. send_pipelined_requests(const std::vector<std::string> &parts) {
  9796. Server svr;
  9797. std::string res;
  9798. serve_pipelining_routes(svr, [&](int port) {
  9799. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9800. });
  9801. return res;
  9802. }
  9803. static void expect_in_order(const std::string &res,
  9804. const std::vector<std::string> &bodies) {
  9805. size_t pos = 0;
  9806. for (const auto &body : bodies) {
  9807. pos = res.find(body, pos);
  9808. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9809. pos += body.size();
  9810. }
  9811. }
  9812. TEST(KeepAliveTest, PipelinedRequests) {
  9813. auto res = send_pipelined_requests(
  9814. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9815. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9816. "Content-Length: 4\r\n\r\nbody"
  9817. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9818. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9819. }
  9820. // The second request starts in the server's buffer and ends on the socket.
  9821. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9822. auto res =
  9823. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9824. "GET /hi/2 HTTP/1.1\r\nHo",
  9825. "st: localhost\r\nConnection: close\r\n\r\n"});
  9826. expect_in_order(res, {"hi 1", "hi 2"});
  9827. }
  9828. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9829. // CRLF after a body does not turn into a 400 for the next request.
  9830. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9831. auto res = send_pipelined_requests(
  9832. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9833. "Content-Length: 4\r\n\r\nbody\r\n"
  9834. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9835. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9836. expect_in_order(res, {"echo body", "hi 2"});
  9837. }
  9838. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9839. // must not be served as the next request.
  9840. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9841. auto res = send_pipelined_requests(
  9842. {"INVALID REQUEST LINE\r\n\r\n"
  9843. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9845. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9846. }
  9847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9848. // Over TLS, the next request is held by the TLS library as already decrypted
  9849. // data rather than on the socket.
  9850. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9852. std::string res;
  9853. serve_pipelining_routes(svr, [&](int port) {
  9854. auto error = Error::Success;
  9855. auto sock = detail::create_client_socket(
  9856. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9857. /*connection_timeout_sec=*/5, 0,
  9858. /*read_timeout_sec=*/2, 0,
  9859. /*write_timeout_sec=*/5, 0, std::string(), error);
  9860. ASSERT_NE(INVALID_SOCKET, sock);
  9861. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9862. auto ctx = SSL_CTX_new(TLS_client_method());
  9863. auto ssl = SSL_new(ctx);
  9864. auto ssl_se = detail::scope_exit([&] {
  9865. SSL_free(ssl);
  9866. SSL_CTX_free(ctx);
  9867. });
  9868. SSL_set_fd(ssl, static_cast<int>(sock));
  9869. ASSERT_EQ(1, SSL_connect(ssl));
  9870. // One write, so all three requests arrive in one TLS record
  9871. const std::string req =
  9872. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9873. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9874. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9875. ASSERT_EQ(static_cast<int>(req.size()),
  9876. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9877. char buf[512];
  9878. int n;
  9879. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9880. res.append(buf, static_cast<size_t>(n));
  9881. }
  9882. });
  9883. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9884. }
  9885. #endif
  9886. TEST(KeepAliveTest, Issue1041) {
  9887. Server svr;
  9888. svr.set_keep_alive_timeout(3);
  9889. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9890. res.set_content("Hello World!", "text/plain");
  9891. });
  9892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9893. auto se = detail::scope_exit([&] {
  9894. svr.stop();
  9895. listen_thread.join();
  9896. ASSERT_FALSE(svr.is_running());
  9897. });
  9898. svr.wait_until_ready();
  9899. Client cli(HOST, PORT);
  9900. cli.set_keep_alive(true);
  9901. auto result = cli.Get("/hi");
  9902. ASSERT_TRUE(result);
  9903. EXPECT_EQ(StatusCode::OK_200, result->status);
  9904. std::this_thread::sleep_for(std::chrono::seconds(5));
  9905. result = cli.Get("/hi");
  9906. ASSERT_TRUE(result);
  9907. EXPECT_EQ(StatusCode::OK_200, result->status);
  9908. }
  9909. TEST(KeepAliveTest, Issue1959) {
  9910. Server svr;
  9911. svr.set_keep_alive_timeout(5);
  9912. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9913. res.set_content("a", "text/plain");
  9914. });
  9915. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9916. auto se = detail::scope_exit([&] {
  9917. if (!svr.is_running()) return;
  9918. svr.stop();
  9919. listen_thread.join();
  9920. ASSERT_FALSE(svr.is_running());
  9921. });
  9922. svr.wait_until_ready();
  9923. Client cli("localhost", PORT);
  9924. cli.set_keep_alive(true);
  9925. using namespace std::chrono;
  9926. auto start = steady_clock::now();
  9927. cli.Get("/a");
  9928. svr.stop();
  9929. listen_thread.join();
  9930. auto end = steady_clock::now();
  9931. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9932. EXPECT_LT(elapsed, 5000);
  9933. }
  9934. #ifdef CPPHTTPLIB_SSL_ENABLED
  9935. TEST(KeepAliveTest, SSLClientReconnection) {
  9936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9937. ASSERT_TRUE(svr.is_valid());
  9938. svr.set_keep_alive_timeout(1);
  9939. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9940. res.set_content("Hello World!", "text/plain");
  9941. });
  9942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. listen_thread.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. SSLClient cli(HOST, PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. cli.set_keep_alive(true);
  9952. auto result = cli.Get("/hi");
  9953. ASSERT_TRUE(result);
  9954. EXPECT_EQ(StatusCode::OK_200, result->status);
  9955. result = cli.Get("/hi");
  9956. ASSERT_TRUE(result);
  9957. EXPECT_EQ(StatusCode::OK_200, result->status);
  9958. std::this_thread::sleep_for(std::chrono::seconds(2));
  9959. // Recoonect
  9960. result = cli.Get("/hi");
  9961. ASSERT_TRUE(result);
  9962. EXPECT_EQ(StatusCode::OK_200, result->status);
  9963. result = cli.Get("/hi");
  9964. ASSERT_TRUE(result);
  9965. EXPECT_EQ(StatusCode::OK_200, result->status);
  9966. }
  9967. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9969. ASSERT_TRUE(svr.is_valid());
  9970. svr.set_keep_alive_timeout(1);
  9971. std::string content = "reconnect";
  9972. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9973. res.set_content("Hello World!", "text/plain");
  9974. });
  9975. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9976. auto se = detail::scope_exit([&] {
  9977. svr.stop();
  9978. listen_thread.join();
  9979. ASSERT_FALSE(svr.is_running());
  9980. });
  9981. svr.wait_until_ready();
  9982. SSLClient cli(HOST, PORT);
  9983. cli.enable_server_certificate_verification(false);
  9984. cli.set_keep_alive(true);
  9985. auto result = cli.Post(
  9986. "/hi", content.size(),
  9987. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9988. sink.write(content.c_str(), content.size());
  9989. return true;
  9990. },
  9991. "text/plain");
  9992. ASSERT_TRUE(result);
  9993. EXPECT_EQ(200, result->status);
  9994. std::this_thread::sleep_for(std::chrono::seconds(2));
  9995. // Recoonect
  9996. result = cli.Post(
  9997. "/hi", content.size(),
  9998. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9999. sink.write(content.c_str(), content.size());
  10000. return true;
  10001. },
  10002. "text/plain");
  10003. ASSERT_TRUE(result);
  10004. EXPECT_EQ(200, result->status);
  10005. result = cli.Post(
  10006. "/hi", content.size(),
  10007. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10008. sink.write(content.c_str(), content.size());
  10009. return true;
  10010. },
  10011. "text/plain");
  10012. ASSERT_TRUE(result);
  10013. EXPECT_EQ(200, result->status);
  10014. }
  10015. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10016. using namespace httplib::tls;
  10017. {
  10018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10019. ASSERT_TRUE(svr.is_valid());
  10020. svr.Get("/sni", [&](const Request &req, Response &res) {
  10021. std::string expected = req.sni();
  10022. EXPECT_EQ(expected, req.get_param_value("expected"));
  10023. res.set_content("ok", "text/plain");
  10024. });
  10025. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10026. auto se = detail::scope_exit([&] {
  10027. svr.stop();
  10028. listen_thread.join();
  10029. ASSERT_FALSE(svr.is_running());
  10030. });
  10031. svr.wait_until_ready();
  10032. {
  10033. SSLClient cli("localhost", PORT);
  10034. cli.enable_server_certificate_verification(false);
  10035. auto res = cli.Get("/sni?expected=localhost");
  10036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10037. }
  10038. {
  10039. SSLClient cli("::1", PORT);
  10040. cli.enable_server_certificate_verification(false);
  10041. auto res = cli.Get("/sni?expected=");
  10042. // NOTE: This may fail if the server is listening on IPv4 only
  10043. // (e.g., when localhost resolves to 127.0.0.1 only)
  10044. if (res) {
  10045. EXPECT_EQ(StatusCode::OK_200, res->status);
  10046. } else {
  10047. EXPECT_EQ(Error::Connection, res.error());
  10048. }
  10049. }
  10050. }
  10051. }
  10052. #endif
  10053. TEST(ClientProblemDetectionTest, ContentProvider) {
  10054. Server svr;
  10055. size_t content_length = 1024 * 1024;
  10056. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10057. res.set_content_provider(
  10058. content_length, "text/plain",
  10059. [&](size_t offset, size_t length, DataSink &sink) {
  10060. auto out_len = std::min(length, static_cast<size_t>(1024));
  10061. std::string out(out_len, '@');
  10062. sink.write(out.data(), out_len);
  10063. return offset < 4096;
  10064. },
  10065. [](bool success) { ASSERT_FALSE(success); });
  10066. });
  10067. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10068. res.set_content_provider(
  10069. 0, "text/plain",
  10070. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10071. EXPECT_TRUE(false);
  10072. return true;
  10073. },
  10074. [](bool success) { ASSERT_FALSE(success); });
  10075. });
  10076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. listen_thread.join();
  10080. ASSERT_FALSE(svr.is_running());
  10081. });
  10082. svr.wait_until_ready();
  10083. Client cli("localhost", PORT);
  10084. {
  10085. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10086. size_t /*data_length*/) { return false; });
  10087. ASSERT_FALSE(res);
  10088. }
  10089. {
  10090. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10091. size_t /*data_length*/) { return false; });
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. }
  10094. }
  10095. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10096. // A provider that reports success without writing anything and without
  10097. // calling done() used to be handed the same offset and length again on every
  10098. // pass, so it spun for as long as the peer stayed connected.
  10099. Server svr;
  10100. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10101. res.set_content("ok", "text/plain");
  10102. });
  10103. auto port = svr.bind_to_any_port(HOST);
  10104. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10105. auto se = detail::scope_exit([&] {
  10106. svr.stop();
  10107. listen_thread.join();
  10108. ASSERT_FALSE(svr.is_running());
  10109. });
  10110. svr.wait_until_ready();
  10111. std::atomic<int> call_count{0};
  10112. Client cli(HOST, port);
  10113. auto res = cli.Post(
  10114. "/", 1024,
  10115. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10116. // Give up after enough passes to show the spin, so that losing the
  10117. // check below fails this test instead of hanging it.
  10118. return ++call_count < 100;
  10119. },
  10120. "text/plain");
  10121. ASSERT_FALSE(res);
  10122. EXPECT_EQ(Error::Write, res.error());
  10123. EXPECT_EQ(1, call_count.load());
  10124. }
  10125. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10126. // A writer only has to assign `write`. The other three used to be left as
  10127. // empty std::functions, so a provider calling one threw
  10128. // std::bad_function_call out of the thread running it and took the whole
  10129. // process down.
  10130. DataSink sink;
  10131. std::string written;
  10132. sink.write = [&](const char *data, size_t data_len) {
  10133. written.append(data, data_len);
  10134. return true;
  10135. };
  10136. EXPECT_TRUE(sink.is_writable());
  10137. sink.done();
  10138. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10139. EXPECT_TRUE(written.empty());
  10140. }
  10141. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10142. // A sink that cannot carry trailers still has to finish.
  10143. DataSink sink;
  10144. auto done_count = 0;
  10145. sink.done = [&]() { done_count++; };
  10146. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10147. EXPECT_EQ(1, done_count);
  10148. }
  10149. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10150. Server svr;
  10151. const std::string body(4096, 'x');
  10152. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10153. res.set_content_provider(body.size(), "text/plain",
  10154. [&](size_t offset, size_t length, DataSink &sink) {
  10155. sink.write(body.data() + offset, length);
  10156. sink.done();
  10157. return true;
  10158. });
  10159. });
  10160. auto port = svr.bind_to_any_port(HOST);
  10161. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. listen_thread.join();
  10165. ASSERT_FALSE(svr.is_running());
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, port);
  10169. auto res = cli.Get("/");
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(StatusCode::OK_200, res->status);
  10172. EXPECT_EQ(body, res->body);
  10173. }
  10174. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10175. Server svr;
  10176. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10177. res.set_content_provider(
  10178. 1024, "text/plain",
  10179. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10180. sink.write("hello", 5);
  10181. sink.done(); // short of the 1024 bytes the response promised
  10182. return true;
  10183. });
  10184. });
  10185. auto port = svr.bind_to_any_port(HOST);
  10186. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10187. auto se = detail::scope_exit([&] {
  10188. svr.stop();
  10189. listen_thread.join();
  10190. ASSERT_FALSE(svr.is_running());
  10191. });
  10192. svr.wait_until_ready();
  10193. Client cli(HOST, port);
  10194. cli.set_read_timeout(5, 0);
  10195. // The response is short of its Content-Length, so the client cannot read a
  10196. // complete body. What matters is that this returns at all: a no-op done()
  10197. // would leave the writer looping over a provider that never makes progress.
  10198. auto res = cli.Get("/");
  10199. EXPECT_FALSE(res);
  10200. }
  10201. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10202. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10203. // The compressed path builds the whole body before connecting, so this
  10204. // fails client-side and never reaches a server.
  10205. Client cli(HOST, PORT);
  10206. cli.set_compress(true);
  10207. auto res = cli.Post(
  10208. "/", 1024,
  10209. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10210. sink.write("hello", 5);
  10211. sink.done(); // short of the 1024 bytes the request announced
  10212. return true;
  10213. },
  10214. "text/plain");
  10215. ASSERT_FALSE(res);
  10216. EXPECT_EQ(Error::Write, res.error());
  10217. }
  10218. #endif
  10219. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10220. Server svr;
  10221. svr.set_error_handler([](Request const &, Response &res) -> void {
  10222. res.set_chunked_content_provider(
  10223. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10224. sink.os << "hello";
  10225. sink.os << "world";
  10226. sink.done();
  10227. return true;
  10228. });
  10229. });
  10230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. listen_thread.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.wait_until_ready();
  10237. Client cli("localhost", PORT);
  10238. auto res = cli.Get("/");
  10239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10241. EXPECT_EQ("helloworld", res->body);
  10242. }
  10243. TEST(LongPollingTest, ClientCloseDetection) {
  10244. Server svr;
  10245. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10246. res.set_chunked_content_provider(
  10247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10248. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10249. sink.os << "hello";
  10250. auto count = 10;
  10251. while (count > 0 && sink.is_writable()) {
  10252. this_thread::sleep_for(chrono::milliseconds(10));
  10253. count--;
  10254. }
  10255. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10256. return true;
  10257. });
  10258. });
  10259. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10260. auto se = detail::scope_exit([&] {
  10261. svr.stop();
  10262. listen_thread.join();
  10263. ASSERT_FALSE(svr.is_running());
  10264. });
  10265. svr.wait_until_ready();
  10266. Client cli("localhost", PORT);
  10267. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10268. EXPECT_EQ("hello", string(data, data_length));
  10269. return false; // close the socket immediately.
  10270. });
  10271. ASSERT_FALSE(res);
  10272. }
  10273. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10274. Server svr;
  10275. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10276. res.set_chunked_content_provider(
  10277. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10278. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10279. sink.os << "hello";
  10280. EXPECT_TRUE(sink.os.good());
  10281. // Wait for the client to close the connection
  10282. auto count = 10;
  10283. while (count > 0 && sink.is_writable()) {
  10284. this_thread::sleep_for(chrono::milliseconds(10));
  10285. count--;
  10286. }
  10287. // After client disconnect, write repeatedly until the socket
  10288. // write actually fails (small writes may be absorbed by the
  10289. // kernel buffer)
  10290. std::string chunk(1024, 'x');
  10291. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10292. sink.os << chunk;
  10293. }
  10294. EXPECT_TRUE(sink.os.fail());
  10295. return true;
  10296. });
  10297. });
  10298. auto port = svr.bind_to_any_port("localhost");
  10299. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. listen_thread.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. Client cli("localhost", port);
  10307. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10308. EXPECT_EQ("hello", string(data, data_length));
  10309. return false; // close the socket immediately.
  10310. });
  10311. ASSERT_FALSE(res);
  10312. }
  10313. TEST(GetWithParametersTest, GetWithParameters) {
  10314. Server svr;
  10315. svr.Get("/", [&](const Request &req, Response &) {
  10316. EXPECT_EQ("world", req.get_param_value("hello"));
  10317. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10318. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10319. });
  10320. svr.Get("/params", [&](const Request &req, Response &) {
  10321. EXPECT_EQ("world", req.get_param_value("hello"));
  10322. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10323. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10324. });
  10325. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10326. EXPECT_EQ("resource-id", req.matches[1]);
  10327. EXPECT_EQ("foo", req.get_param_value("param1"));
  10328. EXPECT_EQ("bar", req.get_param_value("param2"));
  10329. });
  10330. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10331. EXPECT_EQ("user-id", req.path_params.at("id"));
  10332. EXPECT_EQ("foo", req.get_param_value("param1"));
  10333. EXPECT_EQ("bar", req.get_param_value("param2"));
  10334. });
  10335. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. {
  10343. Client cli(HOST, PORT);
  10344. Params params;
  10345. params.emplace("hello", "world");
  10346. params.emplace("hello2", "world2");
  10347. params.emplace("hello3", "world3");
  10348. auto res = cli.Get("/", params, Headers{});
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(StatusCode::OK_200, res->status);
  10351. }
  10352. {
  10353. Client cli(HOST, PORT);
  10354. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10356. EXPECT_EQ(StatusCode::OK_200, res->status);
  10357. }
  10358. {
  10359. Client cli(HOST, PORT);
  10360. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. EXPECT_EQ(StatusCode::OK_200, res->status);
  10363. }
  10364. {
  10365. Client cli(HOST, PORT);
  10366. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10368. EXPECT_EQ(StatusCode::OK_200, res->status);
  10369. }
  10370. }
  10371. TEST(GetWithParametersTest, GetWithParameters2) {
  10372. Server svr;
  10373. svr.Get("/", [&](const Request &req, Response &res) {
  10374. auto text = req.get_param_value("hello");
  10375. res.set_content(text, "text/plain");
  10376. });
  10377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. listen_thread.join();
  10381. ASSERT_FALSE(svr.is_running());
  10382. });
  10383. svr.wait_until_ready();
  10384. Client cli("localhost", PORT);
  10385. Params params;
  10386. params.emplace("hello", "world");
  10387. std::string body;
  10388. auto res = cli.Get("/", params, Headers{},
  10389. [&](const char *data, size_t data_length) {
  10390. body.append(data, data_length);
  10391. return true;
  10392. });
  10393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10394. EXPECT_EQ(StatusCode::OK_200, res->status);
  10395. EXPECT_EQ("world", body);
  10396. }
  10397. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10398. Server svr;
  10399. svr.Get("/search", [&](const Request &req, Response &res) {
  10400. auto q = req.get_param_value("q");
  10401. res.set_content(q, "text/plain");
  10402. });
  10403. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10404. auto se = detail::scope_exit([&] {
  10405. svr.stop();
  10406. listen_thread.join();
  10407. ASSERT_FALSE(svr.is_running());
  10408. });
  10409. svr.wait_until_ready();
  10410. Client cli("localhost", PORT);
  10411. // Verify that Get(path, params) works without requiring Headers argument
  10412. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. EXPECT_EQ(StatusCode::OK_200, res->status);
  10415. EXPECT_EQ("cpp-httplib", res->body);
  10416. }
  10417. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10418. auto host = "httpbingo.org";
  10419. auto path = std::string{"/range/32"};
  10420. #ifdef CPPHTTPLIB_SSL_ENABLED
  10421. SSLClient cli(host);
  10422. #else
  10423. Client cli(host);
  10424. #endif
  10425. cli.set_default_headers({make_range_header({{1, 10}})});
  10426. cli.set_connection_timeout(5);
  10427. {
  10428. auto res = cli.Get(path);
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. EXPECT_EQ("bcdefghijk", res->body);
  10431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10432. }
  10433. {
  10434. auto res = cli.Get(path);
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ("bcdefghijk", res->body);
  10437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10438. }
  10439. }
  10440. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10441. Server svr;
  10442. svr.set_default_headers({{"Hello", "World"}});
  10443. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10444. res.set_content("ok", "text/plain");
  10445. });
  10446. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. listen_thread.join();
  10450. ASSERT_FALSE(svr.is_running());
  10451. });
  10452. svr.wait_until_ready();
  10453. Client cli("localhost", PORT);
  10454. auto res = cli.Get("/");
  10455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10456. EXPECT_EQ(StatusCode::OK_200, res->status);
  10457. EXPECT_EQ("ok", res->body);
  10458. EXPECT_EQ("World", res->get_header_value("Hello"));
  10459. }
  10460. #ifdef CPPHTTPLIB_SSL_ENABLED
  10461. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10463. ASSERT_TRUE(svr.is_valid());
  10464. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10465. std::this_thread::sleep_for(std::chrono::seconds(2));
  10466. res.set_content("a", "text/plain");
  10467. });
  10468. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10469. res.set_content("b", "text/plain");
  10470. });
  10471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10472. auto se = detail::scope_exit([&] {
  10473. svr.stop();
  10474. listen_thread.join();
  10475. ASSERT_FALSE(svr.is_running());
  10476. });
  10477. svr.wait_until_ready();
  10478. SSLClient cli("localhost", PORT);
  10479. cli.enable_server_certificate_verification(false);
  10480. cli.set_keep_alive(true);
  10481. cli.set_read_timeout(std::chrono::seconds(1));
  10482. auto resa = cli.Get("/a");
  10483. ASSERT_TRUE(!resa);
  10484. EXPECT_EQ(Error::Read, resa.error());
  10485. auto resb = cli.Get("/b");
  10486. ASSERT_TRUE(resb);
  10487. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10488. EXPECT_EQ("b", resb->body);
  10489. }
  10490. // Closing an idle keep-alive connection sends close_notify and returns. The
  10491. // server must not wait for the client's close_notify: an idle client never
  10492. // sends one, so the worker would be held until the read timeout expires, and
  10493. // stop() would wait for it.
  10494. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10496. ASSERT_TRUE(svr.is_valid());
  10497. svr.set_keep_alive_timeout(1);
  10498. svr.set_read_timeout(10, 0);
  10499. svr.Get("/", [](const Request &, Response &res) {
  10500. res.set_content("ok", "text/plain");
  10501. });
  10502. auto port = svr.bind_to_any_port(HOST);
  10503. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10504. auto se = detail::scope_exit([&] {
  10505. if (listen_thread.joinable()) {
  10506. svr.stop();
  10507. listen_thread.join();
  10508. }
  10509. });
  10510. svr.wait_until_ready();
  10511. SSLClient cli(HOST, port);
  10512. cli.enable_server_certificate_verification(false);
  10513. cli.set_keep_alive(true);
  10514. auto res = cli.Get("/");
  10515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10516. EXPECT_EQ(StatusCode::OK_200, res->status);
  10517. // Stay idle past the keep-alive timeout so the server closes the connection.
  10518. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10519. auto start = std::chrono::steady_clock::now();
  10520. svr.stop();
  10521. listen_thread.join();
  10522. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10523. std::chrono::steady_clock::now() - start)
  10524. .count();
  10525. EXPECT_LT(elapsed, 3000);
  10526. }
  10527. #endif
  10528. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10529. protected:
  10530. ServerTestWithAI_PASSIVE()
  10531. : cli_(HOST, PORT)
  10532. #ifdef CPPHTTPLIB_SSL_ENABLED
  10533. ,
  10534. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10535. #endif
  10536. {
  10537. #ifdef CPPHTTPLIB_SSL_ENABLED
  10538. cli_.enable_server_certificate_verification(false);
  10539. #endif
  10540. }
  10541. virtual void SetUp() {
  10542. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10543. res.set_content("Hello World!", "text/plain");
  10544. });
  10545. t_ = thread(
  10546. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10547. svr_.wait_until_ready();
  10548. }
  10549. virtual void TearDown() {
  10550. svr_.stop();
  10551. t_.join();
  10552. }
  10553. #ifdef CPPHTTPLIB_SSL_ENABLED
  10554. SSLClient cli_;
  10555. SSLServer svr_;
  10556. #else
  10557. Client cli_;
  10558. Server svr_;
  10559. #endif
  10560. thread t_;
  10561. };
  10562. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10563. auto res = cli_.Get("/hi");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::OK_200, res->status);
  10566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10567. EXPECT_EQ("Hello World!", res->body);
  10568. }
  10569. class ServerUpDownTest : public ::testing::Test {
  10570. protected:
  10571. ServerUpDownTest() : cli_(HOST, PORT) {}
  10572. virtual void SetUp() {
  10573. t_ = thread([&]() {
  10574. svr_.bind_to_any_port(HOST);
  10575. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10576. ASSERT_TRUE(svr_.listen_after_bind());
  10577. });
  10578. svr_.wait_until_ready();
  10579. }
  10580. virtual void TearDown() {
  10581. svr_.stop();
  10582. t_.join();
  10583. }
  10584. Client cli_;
  10585. Server svr_;
  10586. thread t_;
  10587. };
  10588. TEST_F(ServerUpDownTest, QuickStartStop) {
  10589. // Should not crash, especially when run with
  10590. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10591. }
  10592. class PayloadMaxLengthTest : public ::testing::Test {
  10593. protected:
  10594. PayloadMaxLengthTest()
  10595. : cli_(HOST, PORT)
  10596. #ifdef CPPHTTPLIB_SSL_ENABLED
  10597. ,
  10598. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10599. #endif
  10600. {
  10601. #ifdef CPPHTTPLIB_SSL_ENABLED
  10602. cli_.enable_server_certificate_verification(false);
  10603. #endif
  10604. }
  10605. virtual void SetUp() {
  10606. svr_.set_payload_max_length(8);
  10607. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10608. res.set_content("test", "text/plain");
  10609. });
  10610. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10611. svr_.wait_until_ready();
  10612. }
  10613. virtual void TearDown() {
  10614. svr_.stop();
  10615. t_.join();
  10616. }
  10617. #ifdef CPPHTTPLIB_SSL_ENABLED
  10618. SSLClient cli_;
  10619. SSLServer svr_;
  10620. #else
  10621. Client cli_;
  10622. Server svr_;
  10623. #endif
  10624. thread t_;
  10625. };
  10626. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10627. auto res = cli_.Post("/test", "123456789", "text/plain");
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10630. res = cli_.Post("/test", "12345678", "text/plain");
  10631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10632. EXPECT_EQ(StatusCode::OK_200, res->status);
  10633. }
  10634. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10635. // Test chunked encoding with payload exceeding the 8-byte limit
  10636. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10637. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10640. }
  10641. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10642. // Test chunked encoding with payload within the 8-byte limit
  10643. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10644. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. EXPECT_EQ(StatusCode::OK_200, res->status);
  10647. }
  10648. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10649. // Test using send_request to send chunked data exceeding payload limit
  10650. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10651. "Host: " +
  10652. std::string(HOST) + ":" + std::to_string(PORT) +
  10653. "\r\n"
  10654. "Transfer-Encoding: chunked\r\n"
  10655. "Connection: close\r\n"
  10656. "\r\n"
  10657. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10658. "0123456789\r\n"
  10659. "0\r\n" // End chunk
  10660. "\r\n";
  10661. std::string response;
  10662. bool result = send_request(1, chunked_request, &response);
  10663. if (!result) {
  10664. // If send_request fails, it might be because the server closed the
  10665. // connection due to payload limit enforcement, which is acceptable
  10666. SUCCEED()
  10667. << "Server rejected oversized chunked request (connection closed)";
  10668. } else {
  10669. // If we got a response, check if it's an error response or connection was
  10670. // closed early Short response length indicates connection was closed due to
  10671. // payload limit
  10672. if (response.length() <= 10) {
  10673. SUCCEED() << "Server closed connection for oversized chunked request";
  10674. } else {
  10675. // Check for error status codes
  10676. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10677. response.find("Payload Too Large") != std::string::npos ||
  10678. response.find("400") != std::string::npos);
  10679. }
  10680. }
  10681. }
  10682. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10683. // Test request without Content-Length header exceeding payload limit
  10684. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10685. "Host: " +
  10686. std::string(HOST) + ":" +
  10687. std::to_string(PORT) +
  10688. "\r\n"
  10689. "Connection: close\r\n"
  10690. "\r\n";
  10691. // Add payload exceeding the 8-byte limit
  10692. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10693. request_without_content_length += large_payload;
  10694. std::string response;
  10695. bool result = send_request(1, request_without_content_length, &response);
  10696. if (!result) {
  10697. // If send_request fails, server likely closed connection due to payload
  10698. // limit
  10699. SUCCEED() << "Server rejected oversized request without Content-Length "
  10700. "(connection closed)";
  10701. } else {
  10702. // Check if server responded with error or closed connection early
  10703. if (response.length() <= 10) {
  10704. SUCCEED() << "Server closed connection for oversized request without "
  10705. "Content-Length";
  10706. } else {
  10707. // Check for error status codes
  10708. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10709. response.find("Payload Too Large") != std::string::npos ||
  10710. response.find("400") != std::string::npos);
  10711. }
  10712. }
  10713. }
  10714. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10715. // Test request without Content-Length header within payload limit
  10716. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10717. "Host: " +
  10718. std::string(HOST) + ":" +
  10719. std::to_string(PORT) +
  10720. "\r\n"
  10721. "Connection: close\r\n"
  10722. "\r\n";
  10723. // Add payload within the 8-byte limit
  10724. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10725. request_without_content_length += small_payload;
  10726. std::string response;
  10727. bool result = send_request(1, request_without_content_length, &response);
  10728. // For requests without Content-Length, the server may have different behavior
  10729. // The key is that it should not reject due to payload limit for small
  10730. // payloads
  10731. if (result) {
  10732. // Check for any HTTP response (success or error, but not connection closed)
  10733. if (response.length() > 10) {
  10734. SUCCEED()
  10735. << "Server processed request without Content-Length within limit";
  10736. } else {
  10737. // Short response might indicate connection closed, which is acceptable
  10738. SUCCEED() << "Server closed connection for request without "
  10739. "Content-Length (acceptable behavior)";
  10740. }
  10741. } else {
  10742. // Connection failure might be due to protocol requirements
  10743. SUCCEED() << "Connection issue with request without Content-Length "
  10744. "(environment-specific)";
  10745. }
  10746. }
  10747. class LargePayloadMaxLengthTest : public ::testing::Test {
  10748. protected:
  10749. LargePayloadMaxLengthTest()
  10750. : cli_(HOST, PORT)
  10751. #ifdef CPPHTTPLIB_SSL_ENABLED
  10752. ,
  10753. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10754. #endif
  10755. {
  10756. #ifdef CPPHTTPLIB_SSL_ENABLED
  10757. cli_.enable_server_certificate_verification(false);
  10758. #endif
  10759. }
  10760. virtual void SetUp() {
  10761. // Set 10MB payload limit
  10762. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10763. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10764. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10765. res.set_content("Large payload test", "text/plain");
  10766. });
  10767. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10768. svr_.wait_until_ready();
  10769. }
  10770. virtual void TearDown() {
  10771. svr_.stop();
  10772. t_.join();
  10773. }
  10774. #ifdef CPPHTTPLIB_SSL_ENABLED
  10775. SSLClient cli_;
  10776. SSLServer svr_;
  10777. #else
  10778. Client cli_;
  10779. Server svr_;
  10780. #endif
  10781. thread t_;
  10782. };
  10783. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10784. // Test chunked encoding with payload within 10MB limit
  10785. std::string medium_payload(5 * 1024 * 1024,
  10786. 'A'); // 5MB payload, within 10MB limit
  10787. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10789. EXPECT_EQ(StatusCode::OK_200, res->status);
  10790. }
  10791. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10792. // Test chunked encoding with payload exceeding 10MB limit
  10793. std::string large_payload(12 * 1024 * 1024,
  10794. 'B'); // 12MB payload, exceeds 10MB limit
  10795. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10796. // Server may either return 413 or close the connection
  10797. if (res) {
  10798. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10799. } else {
  10800. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10801. }
  10802. }
  10803. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10804. // Test request without Content-Length header within 10MB limit
  10805. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10806. "Host: " +
  10807. std::string(HOST) + ":" +
  10808. std::to_string(PORT) +
  10809. "\r\n"
  10810. "Connection: close\r\n"
  10811. "\r\n";
  10812. // Add 1MB payload (within 10MB limit)
  10813. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10814. request_without_content_length += medium_payload;
  10815. std::string response;
  10816. bool result = send_request(5, request_without_content_length, &response);
  10817. if (result) {
  10818. // Should get a proper HTTP response for payloads within limit
  10819. if (response.length() > 10) {
  10820. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10821. "10MB limit";
  10822. } else {
  10823. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10824. "Content-Length)";
  10825. }
  10826. } else {
  10827. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10828. }
  10829. }
  10830. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10831. // Test request without Content-Length header exceeding 10MB limit
  10832. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10833. "Host: " +
  10834. std::string(HOST) + ":" +
  10835. std::to_string(PORT) +
  10836. "\r\n"
  10837. "Connection: close\r\n"
  10838. "\r\n";
  10839. // Add 12MB payload (exceeds 10MB limit)
  10840. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10841. request_without_content_length += large_payload;
  10842. std::string response;
  10843. bool result = send_request(10, request_without_content_length, &response);
  10844. if (!result) {
  10845. // Server should close connection due to payload limit
  10846. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10847. "(connection closed)";
  10848. } else {
  10849. // Check for error response
  10850. if (response.length() <= 10) {
  10851. SUCCEED()
  10852. << "Server closed connection for 12MB request exceeding 10MB limit";
  10853. } else {
  10854. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10855. response.find("Payload Too Large") != std::string::npos ||
  10856. response.find("400") != std::string::npos);
  10857. }
  10858. }
  10859. }
  10860. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10861. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10862. // path.
  10863. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10864. Server svr;
  10865. const size_t LIMIT = 64 * 1024; // 64KB
  10866. svr.set_payload_max_length(LIMIT);
  10867. size_t total = 0;
  10868. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10869. const ContentReader &content_reader) {
  10870. content_reader([&](const char * /*data*/, size_t len) {
  10871. total += len;
  10872. return true;
  10873. });
  10874. res.status = 200;
  10875. res.set_content("stream_ok", "text/plain");
  10876. });
  10877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10878. auto se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. // Prepare 256KB raw data and gzip-compress it
  10885. std::string raw(256 * 1024, 'A');
  10886. std::string gz;
  10887. {
  10888. z_stream zs{};
  10889. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10890. Z_DEFAULT_STRATEGY);
  10891. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10892. zs.avail_in = static_cast<uInt>(raw.size());
  10893. char outbuf[4096];
  10894. int ret;
  10895. do {
  10896. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10897. zs.avail_out = sizeof(outbuf);
  10898. ret = deflate(&zs, Z_FINISH);
  10899. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10900. } while (ret != Z_STREAM_END);
  10901. deflateEnd(&zs);
  10902. }
  10903. Client cli(HOST, PORT);
  10904. cli.set_connection_timeout(std::chrono::seconds(5));
  10905. Headers headers = {{"Content-Encoding", "gzip"}};
  10906. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10907. "application/octet-stream");
  10908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10909. // Server must reject oversized decompressed payloads with 413.
  10910. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10911. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10912. EXPECT_LE(total, LIMIT);
  10913. }
  10914. #ifndef CPPHTTPLIB_SSL_ENABLED
  10915. // For a request with neither Content-Length nor Transfer-Encoding, the
  10916. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10917. // compressed wire bytes straight to the ContentReader without ever routing
  10918. // them through the decompressor, so payload_max_length_ only bounded the
  10919. // compressed size on the wire, not the decompressed size.
  10920. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10921. Server svr;
  10922. const size_t LIMIT = 64 * 1024; // 64KB
  10923. svr.set_payload_max_length(LIMIT);
  10924. size_t total = 0;
  10925. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10926. const ContentReader &content_reader) {
  10927. content_reader([&](const char * /*data*/, size_t len) {
  10928. total += len;
  10929. return true;
  10930. });
  10931. res.status = 200;
  10932. res.set_content("stream_ok", "text/plain");
  10933. });
  10934. auto port = svr.bind_to_any_port(HOST);
  10935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10936. auto se = detail::scope_exit([&] {
  10937. svr.stop();
  10938. thread.join();
  10939. ASSERT_FALSE(svr.is_running());
  10940. });
  10941. svr.wait_until_ready();
  10942. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10943. // StreamingGzipDecompression test above.
  10944. std::string raw(256 * 1024, 'A');
  10945. std::string gz;
  10946. {
  10947. httplib::detail::gzip_compressor compressor;
  10948. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10949. [&](const char *chunk, size_t len) {
  10950. gz.append(chunk, len);
  10951. return true;
  10952. });
  10953. ASSERT_TRUE(result);
  10954. }
  10955. // Send the gzip body over raw TCP with neither Content-Length nor
  10956. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10957. // kicks in.
  10958. std::string req = "POST /stream HTTP/1.1\r\n"
  10959. "Host: " +
  10960. std::string(HOST) + ":" + std::to_string(port) +
  10961. "\r\n"
  10962. "Content-Encoding: gzip\r\n"
  10963. "Connection: close\r\n"
  10964. "\r\n" +
  10965. gz;
  10966. std::string response;
  10967. ASSERT_TRUE(send_request(5, req, &response, port));
  10968. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10969. EXPECT_LE(total, LIMIT);
  10970. }
  10971. #endif
  10972. #endif
  10973. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10974. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10975. // the payload must be passed through untouched instead of being rejected.
  10976. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10977. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10978. Server svr;
  10979. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10980. res.set_content(body, "image/jpeg");
  10981. res.set_header("Content-Encoding", "UTF-8");
  10982. });
  10983. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10984. res.set_content(body, "image/jpeg");
  10985. res.set_header("Content-Encoding", "identity");
  10986. });
  10987. svr.Post("/echo", [](const Request &req, Response &res) {
  10988. res.set_content(req.body, "image/jpeg");
  10989. });
  10990. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10991. auto se = detail::scope_exit([&] {
  10992. svr.stop();
  10993. t.join();
  10994. ASSERT_FALSE(svr.is_running());
  10995. });
  10996. svr.wait_until_ready();
  10997. Client cli(HOST, PORT);
  10998. {
  10999. auto res = cli.Get("/image");
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. EXPECT_EQ(StatusCode::OK_200, res->status);
  11002. EXPECT_EQ(body, res->body);
  11003. }
  11004. {
  11005. auto res = cli.Get("/identity");
  11006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11007. EXPECT_EQ(StatusCode::OK_200, res->status);
  11008. EXPECT_EQ(body, res->body);
  11009. }
  11010. {
  11011. // The same applies to a request body reaching the server.
  11012. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11013. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11015. EXPECT_EQ(StatusCode::OK_200, res->status);
  11016. EXPECT_EQ(body, res->body);
  11017. }
  11018. }
  11019. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11020. // gzip-encoded response even when the build has no zlib support.
  11021. static const char GZIPPED_HELLO_WORLD[] = {
  11022. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11023. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11024. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11025. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11026. // A content coding is a whole token, not something the field value merely
  11027. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11028. // as "fibre" look like Brotli, and turned a multi-coding value like
  11029. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11030. // it was never meant to see.
  11031. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11032. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11033. Server svr;
  11034. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11035. res.set_content(body, "image/jpeg");
  11036. res.set_header("Content-Encoding", "fibre");
  11037. });
  11038. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11039. res.set_content(body, "image/jpeg");
  11040. res.set_header("Content-Encoding", "gzip, br");
  11041. });
  11042. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11043. res.set_content(body, "image/jpeg");
  11044. res.set_header("Content-Encoding", "x-zstd-ish");
  11045. });
  11046. auto port = svr.bind_to_any_port(HOST);
  11047. thread t = thread([&]() { svr.listen_after_bind(); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. Client cli(HOST, port);
  11055. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11056. auto res = cli.Get(path);
  11057. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11058. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11059. // Not a coding we recognize, so the payload comes back untouched
  11060. EXPECT_EQ(body, res->body) << path;
  11061. }
  11062. }
  11063. // A content coding cpp-httplib recognizes but was not built with must be
  11064. // reported as such. Handing the still-compressed payload back to the caller
  11065. // would silently corrupt it.
  11066. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11067. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11068. Server svr;
  11069. // "image/jpeg" keeps the server from applying a content coding of its own,
  11070. // so the hand-crafted Content-Encoding below survives.
  11071. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11072. res.set_content(gzipped, "image/jpeg");
  11073. res.set_header("Content-Encoding", "gzip");
  11074. });
  11075. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11076. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11077. res.set_content(gzipped, "image/jpeg");
  11078. res.set_header("Content-Encoding", "GZIP");
  11079. });
  11080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli(HOST, PORT);
  11088. {
  11089. auto res = cli.Get("/gzipped");
  11090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ("Hello World!", res->body);
  11093. #else
  11094. ASSERT_FALSE(res);
  11095. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11096. #endif
  11097. }
  11098. {
  11099. // open_stream() must behave the same way.
  11100. auto handle = cli.open_stream("GET", "/gzipped");
  11101. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11102. ASSERT_TRUE(handle.is_valid());
  11103. std::string received;
  11104. char buf[256];
  11105. ssize_t n;
  11106. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11107. received.append(buf, static_cast<size_t>(n));
  11108. }
  11109. EXPECT_EQ("Hello World!", received);
  11110. #else
  11111. EXPECT_FALSE(handle.is_valid());
  11112. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11113. #endif
  11114. }
  11115. {
  11116. // A differently-cased coding must not be mistaken for an unknown one, or
  11117. // the body would be handed back still compressed.
  11118. auto res = cli.Get("/gzipped-uppercase");
  11119. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ("Hello World!", res->body);
  11122. #else
  11123. ASSERT_FALSE(res);
  11124. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11125. #endif
  11126. }
  11127. }
  11128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11129. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11130. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11131. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11132. // body a second time and appending a second Content-Encoding field line, so
  11133. // clients that decode one coding per listed value handed back raw gzip bytes.
  11134. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11135. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11136. Server svr;
  11137. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11138. // keeps the server from applying a coding of its own.
  11139. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11140. res.set_content(gzipped, "text/plain");
  11141. res.set_header("Content-Encoding", "gzip");
  11142. });
  11143. auto port = svr.bind_to_any_port(HOST);
  11144. thread t = thread([&]() { svr.listen_after_bind(); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. ASSERT_FALSE(svr.is_running());
  11149. });
  11150. svr.wait_until_ready();
  11151. Client cli(HOST, port);
  11152. Headers headers = {{"Accept-Encoding", "gzip"}};
  11153. auto res = cli.Get("/pre-gzipped", headers);
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11157. EXPECT_EQ("Hello World!", res->body);
  11158. }
  11159. // A chunked provider settles its coding where the headers are written and
  11160. // reuses it at write time. Both ends of that have to hold: a handler's own
  11161. // Content-Encoding suppresses the coding, and a response without one is still
  11162. // compressed as it always was.
  11163. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11164. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11165. const std::string plain = "Hello World! Hello World! Hello World!";
  11166. Server svr;
  11167. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11168. res.set_header("Content-Encoding", "gzip");
  11169. res.set_chunked_content_provider(
  11170. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11171. sink.write(gzipped.data(), gzipped.size());
  11172. sink.done();
  11173. return true;
  11174. });
  11175. });
  11176. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11177. res.set_chunked_content_provider(
  11178. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11179. sink.write(plain.data(), plain.size());
  11180. sink.done();
  11181. return true;
  11182. });
  11183. });
  11184. auto port = svr.bind_to_any_port(HOST);
  11185. thread t = thread([&]() { svr.listen_after_bind(); });
  11186. auto se = detail::scope_exit([&] {
  11187. svr.stop();
  11188. t.join();
  11189. ASSERT_FALSE(svr.is_running());
  11190. });
  11191. svr.wait_until_ready();
  11192. Client cli(HOST, port);
  11193. Headers headers = {{"Accept-Encoding", "gzip"}};
  11194. {
  11195. auto res = cli.Get("/pre-gzipped", headers);
  11196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11197. EXPECT_EQ(StatusCode::OK_200, res->status);
  11198. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11199. EXPECT_EQ("Hello World!", res->body);
  11200. }
  11201. {
  11202. auto res = cli.Get("/negotiated", headers);
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. EXPECT_EQ(StatusCode::OK_200, res->status);
  11205. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11206. EXPECT_EQ(plain, res->body);
  11207. }
  11208. }
  11209. #endif
  11210. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11211. // the same message as the comma-joined one, so both have to be read the same
  11212. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11213. // single gzip coding, and a body the sender says was encoded twice was handed
  11214. // back after one pass, still compressed but presented as decoded.
  11215. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11216. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11217. Server svr;
  11218. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11219. res.set_content(body, "image/jpeg");
  11220. res.headers.emplace("Content-Encoding", "gzip");
  11221. res.headers.emplace("Content-Encoding", "gzip");
  11222. });
  11223. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11224. res.set_content(body, "image/jpeg");
  11225. res.set_header("Content-Encoding", "gzip, gzip");
  11226. });
  11227. auto port = svr.bind_to_any_port(HOST);
  11228. thread t = thread([&]() { svr.listen_after_bind(); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. t.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. Client cli(HOST, port);
  11236. // Two codings is not something cpp-httplib decodes, so both representations
  11237. // take the pass-through path rather than one of them being gunzipped once.
  11238. for (const char *path : {"/split", "/joined"}) {
  11239. auto res = cli.Get(path);
  11240. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11242. EXPECT_EQ(body, res->body) << path;
  11243. }
  11244. }
  11245. // Regression test for DoS vulnerability: a malicious server sending a response
  11246. // without Content-Length header must not cause unbounded memory consumption on
  11247. // the client side. The client should stop reading after a reasonable limit,
  11248. // similar to the server-side set_payload_max_length protection.
  11249. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11250. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11251. #ifndef _WIN32
  11252. signal(SIGPIPE, SIG_IGN);
  11253. #endif
  11254. auto server_thread = std::thread([] {
  11255. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11256. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11257. default_socket_options(srv);
  11258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11259. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11260. sockaddr_in addr{};
  11261. addr.sin_family = AF_INET;
  11262. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11263. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11264. int opt = 1;
  11265. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11266. #ifdef _WIN32
  11267. reinterpret_cast<const char *>(&opt),
  11268. #else
  11269. &opt,
  11270. #endif
  11271. sizeof(opt));
  11272. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11273. ::listen(srv, 1);
  11274. sockaddr_in cli_addr{};
  11275. socklen_t cli_len = sizeof(cli_addr);
  11276. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11277. if (cli != INVALID_SOCKET) {
  11278. char buf[4096];
  11279. ::recv(cli, buf, sizeof(buf), 0);
  11280. // Malicious response: no Content-Length, no chunked encoding
  11281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n";
  11284. ::send(cli,
  11285. #ifdef _WIN32
  11286. static_cast<const char *>(response_header.c_str()),
  11287. static_cast<int>(response_header.size()),
  11288. #else
  11289. response_header.c_str(), response_header.size(),
  11290. #endif
  11291. 0);
  11292. // Send 10MB of data
  11293. std::string chunk(64 * 1024, 'A');
  11294. size_t total_sent = 0;
  11295. while (total_sent < MALICIOUS_DATA_SIZE) {
  11296. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11297. auto sent = ::send(cli,
  11298. #ifdef _WIN32
  11299. static_cast<const char *>(chunk.c_str()),
  11300. static_cast<int>(to_send),
  11301. #else
  11302. chunk.c_str(), to_send,
  11303. #endif
  11304. 0);
  11305. if (sent <= 0) break;
  11306. total_sent += static_cast<size_t>(sent);
  11307. }
  11308. detail::close_socket(cli);
  11309. }
  11310. detail::close_socket(srv);
  11311. });
  11312. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11313. size_t total_read = 0;
  11314. {
  11315. Client cli("127.0.0.1", PORT + 2);
  11316. cli.set_read_timeout(5, 0);
  11317. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11318. auto stream = cli.open_stream("GET", "/malicious");
  11319. ASSERT_TRUE(stream.is_valid());
  11320. char buffer[64 * 1024];
  11321. ssize_t n;
  11322. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11323. total_read += static_cast<size_t>(n);
  11324. }
  11325. } // StreamHandle and Client destroyed here, closing the socket
  11326. server_thread.join();
  11327. // With set_payload_max_length, the client must stop reading before consuming
  11328. // all 10MB. The read loop should be cut off at or near the configured limit.
  11329. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11330. << "Client read " << total_read << " bytes, exceeding the configured "
  11331. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11332. }
  11333. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11334. // the entire response body without truncation.
  11335. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11336. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11337. #ifndef _WIN32
  11338. signal(SIGPIPE, SIG_IGN);
  11339. #endif
  11340. auto server_thread = std::thread([] {
  11341. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11342. default_socket_options(srv);
  11343. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11344. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11345. sockaddr_in addr{};
  11346. addr.sin_family = AF_INET;
  11347. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11348. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11349. int opt = 1;
  11350. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11351. #ifdef _WIN32
  11352. reinterpret_cast<const char *>(&opt),
  11353. #else
  11354. &opt,
  11355. #endif
  11356. sizeof(opt));
  11357. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11358. ::listen(srv, 1);
  11359. sockaddr_in cli_addr{};
  11360. socklen_t cli_len = sizeof(cli_addr);
  11361. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11362. if (cli != INVALID_SOCKET) {
  11363. char buf[4096];
  11364. ::recv(cli, buf, sizeof(buf), 0);
  11365. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11366. "Connection: close\r\n"
  11367. "\r\n";
  11368. ::send(cli,
  11369. #ifdef _WIN32
  11370. static_cast<const char *>(response_header.c_str()),
  11371. static_cast<int>(response_header.size()),
  11372. #else
  11373. response_header.c_str(), response_header.size(),
  11374. #endif
  11375. 0);
  11376. std::string chunk(64 * 1024, 'A');
  11377. size_t total_sent = 0;
  11378. while (total_sent < DATA_SIZE) {
  11379. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11380. auto sent = ::send(cli,
  11381. #ifdef _WIN32
  11382. static_cast<const char *>(chunk.c_str()),
  11383. static_cast<int>(to_send),
  11384. #else
  11385. chunk.c_str(), to_send,
  11386. #endif
  11387. 0);
  11388. if (sent <= 0) break;
  11389. total_sent += static_cast<size_t>(sent);
  11390. }
  11391. #ifdef _WIN32
  11392. ::shutdown(cli, SD_SEND);
  11393. #else
  11394. ::shutdown(cli, SHUT_WR);
  11395. #endif
  11396. // Drain until the client closes its end, ensuring all data is delivered
  11397. char drain[1024];
  11398. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11399. detail::close_socket(cli);
  11400. }
  11401. detail::close_socket(srv);
  11402. });
  11403. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11404. size_t total_read = 0;
  11405. {
  11406. Client cli("127.0.0.1", PORT + 2);
  11407. cli.set_read_timeout(5, 0);
  11408. cli.set_payload_max_length(0); // 0 means no limit
  11409. auto stream = cli.open_stream("GET", "/data");
  11410. ASSERT_TRUE(stream.is_valid());
  11411. char buffer[64 * 1024];
  11412. ssize_t n;
  11413. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11414. total_read += static_cast<size_t>(n);
  11415. }
  11416. }
  11417. server_thread.join();
  11418. EXPECT_EQ(total_read, DATA_SIZE)
  11419. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11420. << " bytes without truncation, but only read " << total_read << " bytes.";
  11421. }
  11422. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11423. // enormous Content-Length must not cause the client to pre-allocate a huge
  11424. // response body buffer. The reservation is capped at payload_max_length_, and
  11425. // the read itself fails when the body exceeds the limit.
  11426. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11427. #ifndef _WIN32
  11428. signal(SIGPIPE, SIG_IGN);
  11429. #endif
  11430. auto server_thread = std::thread([] {
  11431. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11432. default_socket_options(srv);
  11433. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11434. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11435. sockaddr_in addr{};
  11436. addr.sin_family = AF_INET;
  11437. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11438. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11439. int opt = 1;
  11440. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11441. #ifdef _WIN32
  11442. reinterpret_cast<const char *>(&opt),
  11443. #else
  11444. &opt,
  11445. #endif
  11446. sizeof(opt));
  11447. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11448. ::listen(srv, 1);
  11449. sockaddr_in cli_addr{};
  11450. socklen_t cli_len = sizeof(cli_addr);
  11451. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11452. if (cli != INVALID_SOCKET) {
  11453. char buf[4096];
  11454. ::recv(cli, buf, sizeof(buf), 0);
  11455. // Malicious response: claim a 20GB body but send only a tiny payload.
  11456. std::string response = "HTTP/1.1 200 OK\r\n"
  11457. "Content-Length: 20000000000\r\n"
  11458. "\r\n"
  11459. "abc";
  11460. ::send(cli,
  11461. #ifdef _WIN32
  11462. static_cast<const char *>(response.c_str()),
  11463. static_cast<int>(response.size()),
  11464. #else
  11465. response.c_str(), response.size(),
  11466. #endif
  11467. 0);
  11468. detail::close_socket(cli);
  11469. }
  11470. detail::close_socket(srv);
  11471. });
  11472. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11473. {
  11474. Client cli("127.0.0.1", PORT + 2);
  11475. cli.set_read_timeout(5, 0);
  11476. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11477. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11478. // (server claims more bytes than payload_max_length permits), but it must
  11479. // not exhaust memory before getting there.
  11480. auto res = cli.Get("/malicious");
  11481. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11482. }
  11483. server_thread.join();
  11484. }
  11485. // Verify that content_receiver bypasses the default payload_max_length,
  11486. // allowing streaming downloads larger than 100MB without requiring an explicit
  11487. // set_payload_max_length call.
  11488. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11489. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11490. #ifndef _WIN32
  11491. signal(SIGPIPE, SIG_IGN);
  11492. #endif
  11493. auto server_thread = std::thread([] {
  11494. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11495. default_socket_options(srv);
  11496. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11497. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11498. sockaddr_in addr{};
  11499. addr.sin_family = AF_INET;
  11500. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11501. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11502. int opt = 1;
  11503. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11504. #ifdef _WIN32
  11505. reinterpret_cast<const char *>(&opt),
  11506. #else
  11507. &opt,
  11508. #endif
  11509. sizeof(opt));
  11510. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11511. ::listen(srv, 1);
  11512. sockaddr_in cli_addr{};
  11513. socklen_t cli_len = sizeof(cli_addr);
  11514. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11515. if (cli != INVALID_SOCKET) {
  11516. char buf[4096];
  11517. ::recv(cli, buf, sizeof(buf), 0);
  11518. // Response with Content-Length larger than default 100MB limit
  11519. auto content_length = std::to_string(DATA_SIZE);
  11520. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11521. "Content-Length: " +
  11522. content_length +
  11523. "\r\n"
  11524. "Connection: close\r\n"
  11525. "\r\n";
  11526. ::send(cli,
  11527. #ifdef _WIN32
  11528. static_cast<const char *>(response_header.c_str()),
  11529. static_cast<int>(response_header.size()),
  11530. #else
  11531. response_header.c_str(), response_header.size(),
  11532. #endif
  11533. 0);
  11534. std::string chunk(64 * 1024, 'A');
  11535. size_t total_sent = 0;
  11536. while (total_sent < DATA_SIZE) {
  11537. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11538. auto sent = ::send(cli,
  11539. #ifdef _WIN32
  11540. static_cast<const char *>(chunk.c_str()),
  11541. static_cast<int>(to_send),
  11542. #else
  11543. chunk.c_str(), to_send,
  11544. #endif
  11545. 0);
  11546. if (sent <= 0) break;
  11547. total_sent += static_cast<size_t>(sent);
  11548. }
  11549. detail::close_socket(cli);
  11550. }
  11551. detail::close_socket(srv);
  11552. });
  11553. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11554. size_t total_received = 0;
  11555. {
  11556. Client cli("127.0.0.1", PORT + 2);
  11557. cli.set_read_timeout(10, 0);
  11558. // Do NOT call set_payload_max_length — use the default 100MB limit
  11559. auto res =
  11560. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11561. total_received += data_length;
  11562. return true;
  11563. });
  11564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11565. EXPECT_EQ(StatusCode::OK_200, res->status);
  11566. }
  11567. server_thread.join();
  11568. EXPECT_EQ(total_received, DATA_SIZE)
  11569. << "With content_receiver, the client should read all " << DATA_SIZE
  11570. << " bytes despite the default 100MB payload_max_length, but only read "
  11571. << total_received << " bytes.";
  11572. }
  11573. // Verify that an explicit set_payload_max_length smaller than the response is
  11574. // enforced even when a content_receiver is used.
  11575. TEST(ClientVulnerabilityTest,
  11576. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11577. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11578. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11579. #ifndef _WIN32
  11580. signal(SIGPIPE, SIG_IGN);
  11581. #endif
  11582. auto server_thread = std::thread([] {
  11583. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11584. default_socket_options(srv);
  11585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11586. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11587. sockaddr_in addr{};
  11588. addr.sin_family = AF_INET;
  11589. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11591. int opt = 1;
  11592. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11593. #ifdef _WIN32
  11594. reinterpret_cast<const char *>(&opt),
  11595. #else
  11596. &opt,
  11597. #endif
  11598. sizeof(opt));
  11599. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11600. ::listen(srv, 1);
  11601. sockaddr_in cli_addr{};
  11602. socklen_t cli_len = sizeof(cli_addr);
  11603. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11604. if (cli != INVALID_SOCKET) {
  11605. char buf[4096];
  11606. ::recv(cli, buf, sizeof(buf), 0);
  11607. auto content_length = std::to_string(DATA_SIZE);
  11608. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11609. "Content-Length: " +
  11610. content_length +
  11611. "\r\n"
  11612. "Connection: close\r\n"
  11613. "\r\n";
  11614. ::send(cli,
  11615. #ifdef _WIN32
  11616. static_cast<const char *>(response_header.c_str()),
  11617. static_cast<int>(response_header.size()),
  11618. #else
  11619. response_header.c_str(), response_header.size(),
  11620. #endif
  11621. 0);
  11622. std::string chunk(64 * 1024, 'A');
  11623. size_t total_sent = 0;
  11624. while (total_sent < DATA_SIZE) {
  11625. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11626. auto sent = ::send(cli,
  11627. #ifdef _WIN32
  11628. static_cast<const char *>(chunk.c_str()),
  11629. static_cast<int>(to_send),
  11630. #else
  11631. chunk.c_str(), to_send,
  11632. #endif
  11633. 0);
  11634. if (sent <= 0) break;
  11635. total_sent += static_cast<size_t>(sent);
  11636. }
  11637. detail::close_socket(cli);
  11638. }
  11639. detail::close_socket(srv);
  11640. });
  11641. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11642. size_t total_received = 0;
  11643. {
  11644. Client cli("127.0.0.1", PORT + 2);
  11645. cli.set_read_timeout(10, 0);
  11646. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11647. auto res =
  11648. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11649. total_received += data_length;
  11650. return true;
  11651. });
  11652. // Should fail because 200MB exceeds the explicit 150MB limit
  11653. EXPECT_FALSE(res);
  11654. }
  11655. server_thread.join();
  11656. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11657. << "Client with content_receiver should respect the explicit "
  11658. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11659. << total_received << " bytes.";
  11660. }
  11661. // Verify that an explicit set_payload_max_length larger than the response
  11662. // allows the content_receiver to read all data successfully.
  11663. TEST(ClientVulnerabilityTest,
  11664. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11665. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11666. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11667. #ifndef _WIN32
  11668. signal(SIGPIPE, SIG_IGN);
  11669. #endif
  11670. auto server_thread = std::thread([] {
  11671. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11672. default_socket_options(srv);
  11673. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11674. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11675. sockaddr_in addr{};
  11676. addr.sin_family = AF_INET;
  11677. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11678. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11679. int opt = 1;
  11680. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11681. #ifdef _WIN32
  11682. reinterpret_cast<const char *>(&opt),
  11683. #else
  11684. &opt,
  11685. #endif
  11686. sizeof(opt));
  11687. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11688. ::listen(srv, 1);
  11689. sockaddr_in cli_addr{};
  11690. socklen_t cli_len = sizeof(cli_addr);
  11691. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11692. if (cli != INVALID_SOCKET) {
  11693. char buf[4096];
  11694. ::recv(cli, buf, sizeof(buf), 0);
  11695. auto content_length = std::to_string(DATA_SIZE);
  11696. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11697. "Content-Length: " +
  11698. content_length +
  11699. "\r\n"
  11700. "Connection: close\r\n"
  11701. "\r\n";
  11702. ::send(cli,
  11703. #ifdef _WIN32
  11704. static_cast<const char *>(response_header.c_str()),
  11705. static_cast<int>(response_header.size()),
  11706. #else
  11707. response_header.c_str(), response_header.size(),
  11708. #endif
  11709. 0);
  11710. std::string chunk(64 * 1024, 'A');
  11711. size_t total_sent = 0;
  11712. while (total_sent < DATA_SIZE) {
  11713. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11714. auto sent = ::send(cli,
  11715. #ifdef _WIN32
  11716. static_cast<const char *>(chunk.c_str()),
  11717. static_cast<int>(to_send),
  11718. #else
  11719. chunk.c_str(), to_send,
  11720. #endif
  11721. 0);
  11722. if (sent <= 0) break;
  11723. total_sent += static_cast<size_t>(sent);
  11724. }
  11725. #ifdef _WIN32
  11726. ::shutdown(cli, SD_SEND);
  11727. #else
  11728. ::shutdown(cli, SHUT_WR);
  11729. #endif
  11730. char drain[1024];
  11731. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11732. detail::close_socket(cli);
  11733. }
  11734. detail::close_socket(srv);
  11735. });
  11736. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11737. size_t total_received = 0;
  11738. {
  11739. Client cli("127.0.0.1", PORT + 2);
  11740. cli.set_read_timeout(10, 0);
  11741. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11742. auto res =
  11743. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11744. total_received += data_length;
  11745. return true;
  11746. });
  11747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11748. EXPECT_EQ(StatusCode::OK_200, res->status);
  11749. }
  11750. server_thread.join();
  11751. EXPECT_EQ(total_received, DATA_SIZE)
  11752. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11753. << " bytes (larger than " << DATA_SIZE
  11754. << " bytes response), content_receiver should read all data, but only "
  11755. "read "
  11756. << total_received << " bytes.";
  11757. }
  11758. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11759. // Regression test for "zip bomb" attack on the client side: a malicious server
  11760. // sends a small gzip-compressed response that decompresses to a huge payload.
  11761. // The client must enforce payload_max_length on the decompressed size.
  11762. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11763. constexpr size_t DECOMPRESSED_SIZE =
  11764. 10 * 1024 * 1024; // 10MB after decompression
  11765. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11766. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11767. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11768. std::string compressed;
  11769. {
  11770. httplib::detail::gzip_compressor compressor;
  11771. bool ok =
  11772. compressor.compress(uncompressed.data(), uncompressed.size(),
  11773. /*last=*/true, [&](const char *buf, size_t len) {
  11774. compressed.append(buf, len);
  11775. return true;
  11776. });
  11777. ASSERT_TRUE(ok);
  11778. }
  11779. // Sanity: compressed data should be much smaller than the decompressed size
  11780. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11781. #ifndef _WIN32
  11782. signal(SIGPIPE, SIG_IGN);
  11783. #endif
  11784. // Set up the listening socket in the main thread so the server is guaranteed
  11785. // to be ready before the client connects (eliminates race condition).
  11786. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11787. default_socket_options(srv);
  11788. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11789. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11790. sockaddr_in addr{};
  11791. addr.sin_family = AF_INET;
  11792. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11793. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11794. int opt = 1;
  11795. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11796. #ifdef _WIN32
  11797. reinterpret_cast<const char *>(&opt),
  11798. #else
  11799. &opt,
  11800. #endif
  11801. sizeof(opt));
  11802. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11803. ASSERT_EQ(0, ::listen(srv, 1));
  11804. auto server_thread = std::thread([&compressed, srv] {
  11805. sockaddr_in cli_addr{};
  11806. socklen_t cli_len = sizeof(cli_addr);
  11807. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11808. if (cli != INVALID_SOCKET) {
  11809. // Read the full HTTP request (until \r\n\r\n)
  11810. char buf[4096];
  11811. size_t total = 0;
  11812. while (total < sizeof(buf)) {
  11813. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11814. if (n <= 0) break;
  11815. total += static_cast<size_t>(n);
  11816. // Check for end of headers
  11817. if (total >= 4) {
  11818. std::string req(buf, total);
  11819. if (req.find("\r\n\r\n") != std::string::npos) break;
  11820. }
  11821. }
  11822. // Malicious response: gzip-compressed body, no Content-Length
  11823. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11824. "Content-Encoding: gzip\r\n"
  11825. "Connection: close\r\n"
  11826. "\r\n";
  11827. ::send(cli,
  11828. #ifdef _WIN32
  11829. static_cast<const char *>(response_header.c_str()),
  11830. static_cast<int>(response_header.size()),
  11831. #else
  11832. response_header.c_str(), response_header.size(),
  11833. #endif
  11834. 0);
  11835. // Send the compressed payload (small on the wire, huge when decompressed)
  11836. size_t total_sent = 0;
  11837. while (total_sent < compressed.size()) {
  11838. auto to_send = std::min(compressed.size() - total_sent,
  11839. static_cast<size_t>(64 * 1024));
  11840. auto sent =
  11841. ::send(cli,
  11842. #ifdef _WIN32
  11843. static_cast<const char *>(compressed.c_str() + total_sent),
  11844. static_cast<int>(to_send),
  11845. #else
  11846. compressed.c_str() + total_sent, to_send,
  11847. #endif
  11848. 0);
  11849. if (sent <= 0) break;
  11850. total_sent += static_cast<size_t>(sent);
  11851. }
  11852. detail::close_socket(cli);
  11853. }
  11854. });
  11855. auto se = detail::scope_exit([&] {
  11856. detail::close_socket(srv);
  11857. server_thread.join();
  11858. });
  11859. size_t total_decompressed = 0;
  11860. {
  11861. Client cli("127.0.0.1", PORT + 3);
  11862. cli.set_read_timeout(5, 0);
  11863. cli.set_decompress(true);
  11864. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11865. auto stream = cli.open_stream("GET", "/zipbomb");
  11866. ASSERT_TRUE(stream.is_valid());
  11867. char buffer[64 * 1024];
  11868. ssize_t n;
  11869. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11870. total_decompressed += static_cast<size_t>(n);
  11871. }
  11872. }
  11873. // The decompressed size must be capped by payload_max_length. Without
  11874. // protection, the client would decompress the full 10MB from a tiny
  11875. // compressed payload, enabling a zip bomb DoS attack.
  11876. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11877. << "Client decompressed " << total_decompressed
  11878. << " bytes from a gzip response. The decompressed size should be "
  11879. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11880. }
  11881. #endif
  11882. TEST(HostAndPortPropertiesTest, NoSSL) {
  11883. httplib::Client cli("www.google.com", 1234);
  11884. ASSERT_EQ("www.google.com", cli.host());
  11885. ASSERT_EQ(1234, cli.port());
  11886. }
  11887. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11888. httplib::Client cli("www.google.com:1234");
  11889. ASSERT_EQ("www.google.com", cli.host());
  11890. ASSERT_EQ(1234, cli.port());
  11891. }
  11892. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11893. // Port number that overflows int — should not crash, client becomes invalid
  11894. httplib::Client cli("http://www.google.com:99999999999999999999");
  11895. ASSERT_FALSE(cli.is_valid());
  11896. }
  11897. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11898. // Port 99999 exceeds valid range (1-65535) — should not crash
  11899. httplib::Client cli("http://www.google.com:99999");
  11900. ASSERT_FALSE(cli.is_valid());
  11901. }
  11902. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11903. httplib::Client cli("http://www.google.com:80abc");
  11904. ASSERT_FALSE(cli.is_valid());
  11905. }
  11906. #ifdef CPPHTTPLIB_SSL_ENABLED
  11907. TEST(HostAndPortPropertiesTest, SSL) {
  11908. httplib::SSLClient cli("www.google.com");
  11909. ASSERT_EQ("www.google.com", cli.host());
  11910. ASSERT_EQ(443, cli.port());
  11911. }
  11912. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11913. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11914. std::string cert;
  11915. read_file(CA_CERT_FILE, cert);
  11916. httplib::SSLClient httplib_client("www.google.com");
  11917. // Load CA store first time
  11918. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11919. // Load CA store second time (update)
  11920. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11921. // Verify client is still valid and can make connections
  11922. httplib_client.enable_server_certificate_verification(true);
  11923. auto res = httplib_client.Get("/");
  11924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11925. // Google may return 200 or 301 depending on various factors
  11926. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11927. res->status == StatusCode::MovedPermanently_301);
  11928. }
  11929. TEST(SSLClientTest, ServerNameIndication_Online) {
  11930. auto host = "httpbingo.org";
  11931. auto path = std::string{"/get"};
  11932. SSLClient cli(host, 443);
  11933. auto res = cli.Get(path);
  11934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11935. ASSERT_EQ(StatusCode::OK_200, res->status);
  11936. }
  11937. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11938. // Use a site that will cause SSL verification failure due to self-signed cert
  11939. SSLClient cli("self-signed.badssl.com", 443);
  11940. cli.enable_server_certificate_verification(true);
  11941. auto res = cli.Get("/");
  11942. ASSERT_TRUE(!res);
  11943. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11944. // Verify backend error is captured for SSLServerVerification
  11945. // This occurs when certificate verification fails
  11946. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11947. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11948. EXPECT_NE(0UL, res.ssl_backend_error());
  11949. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11950. // For OpenSSL, ssl_error is 0 for verification errors
  11951. EXPECT_EQ(0, res.ssl_error());
  11952. #if !defined(_WIN32) || \
  11953. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11954. // On non-Windows or when Windows Schannel is disabled, the error comes
  11955. // from OpenSSL's verification
  11956. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11957. res.ssl_backend_error());
  11958. #endif
  11959. #endif
  11960. }
  11961. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11962. // Use a site where hostname doesn't match the certificate
  11963. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11964. SSLClient cli("wrong.host.badssl.com", 443);
  11965. cli.enable_server_certificate_verification(true);
  11966. cli.enable_server_hostname_verification(true);
  11967. auto res = cli.Get("/");
  11968. ASSERT_TRUE(!res);
  11969. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11970. // Verify backend error is captured for hostname verification failure
  11971. EXPECT_NE(0UL, res.ssl_backend_error());
  11972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11973. // For OpenSSL, ssl_error is 0 for verification errors
  11974. EXPECT_EQ(0, res.ssl_error());
  11975. #if !defined(_WIN32) || \
  11976. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11977. // On non-Windows or when Windows Schannel is disabled, the error comes
  11978. // from OpenSSL's hostname verification
  11979. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11980. res.ssl_backend_error());
  11981. #endif
  11982. #endif
  11983. }
  11984. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11985. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11986. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11987. SSLClient cli("www.google.com", 443);
  11988. cli.enable_server_certificate_verification(true);
  11989. auto res = cli.Get("/");
  11990. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11991. }
  11992. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11993. SSLClient cli("www.google.com", 443);
  11994. cli.enable_server_certificate_verification(true);
  11995. cli.enable_windows_certificate_verification(false);
  11996. auto res = cli.Get("/");
  11997. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11998. }
  11999. // The server sends an intermediate cross-signed by a root Windows trusts,
  12000. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12001. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12002. SSLClient cli("accounts.spotify.com", 443);
  12003. auto res = cli.Get("/");
  12004. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12005. << " ssl_backend_error=" << res.ssl_backend_error();
  12006. }
  12007. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12008. // policy status, which no backend reports for a self-signed certificate.
  12009. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12010. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12011. ASSERT_TRUE(svr.is_valid());
  12012. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12013. auto se = detail::scope_exit([&] {
  12014. svr.stop();
  12015. t.join();
  12016. ASSERT_FALSE(svr.is_running());
  12017. });
  12018. svr.wait_until_ready();
  12019. SSLClient cli("127.0.0.1", PORT);
  12020. cli.set_connection_timeout(30);
  12021. auto res = cli.Get("/");
  12022. ASSERT_FALSE(res);
  12023. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12024. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12025. }
  12026. #endif
  12027. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12028. Client cli("https://google.com");
  12029. auto res = cli.Get("/");
  12030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12031. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12032. }
  12033. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12034. SSLClient cli("google.com");
  12035. cli.set_ca_cert_path(CA_CERT_FILE);
  12036. auto res = cli.Get("/");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12039. }
  12040. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12041. SSLClient cli("google.com");
  12042. cli.enable_server_certificate_verification(true);
  12043. cli.set_ca_cert_path("hello");
  12044. auto res = cli.Get("/");
  12045. ASSERT_TRUE(!res);
  12046. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12047. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12048. // should be set
  12049. EXPECT_EQ(0, res.ssl_error());
  12050. // Verify backend error is captured for SSLLoadingCerts
  12051. // This error occurs when loading CA certificates fails
  12052. EXPECT_NE(0UL, res.ssl_backend_error());
  12053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12054. // OpenSSL specific error codes:
  12055. // > openssl errstr 0x80000002
  12056. // error:80000002:system library::No such file or directory
  12057. // > openssl errstr 0xA000126
  12058. // error:0A000126:SSL routines::unexpected eof while reading
  12059. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12060. res.ssl_backend_error() == 0xA000126);
  12061. #endif
  12062. }
  12063. TEST(SSLClientTest, ServerCertificateVerification4) {
  12064. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12065. ASSERT_TRUE(svr.is_valid());
  12066. svr.Get("/test", [&](const Request &, Response &res) {
  12067. res.set_content("test", "text/plain");
  12068. svr.stop();
  12069. ASSERT_TRUE(true);
  12070. });
  12071. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12072. auto se = detail::scope_exit([&] {
  12073. t.join();
  12074. ASSERT_FALSE(svr.is_running());
  12075. });
  12076. svr.wait_until_ready();
  12077. SSLClient cli("127.0.0.1", PORT);
  12078. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12079. cli.enable_server_certificate_verification(true);
  12080. cli.set_connection_timeout(30);
  12081. auto res = cli.Get("/test");
  12082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12083. ASSERT_EQ(StatusCode::OK_200, res->status);
  12084. }
  12085. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12086. std::string cert;
  12087. read_file(CA_CERT_FILE, cert);
  12088. SSLClient cli("google.com");
  12089. cli.load_ca_cert_store(cert.data(), cert.size());
  12090. const auto res = cli.Get("/");
  12091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12093. }
  12094. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12095. // clang-format off
  12096. static constexpr char cert[] =
  12097. "GlobalSign Root CA\n"
  12098. "==================\n"
  12099. "-----BEGIN CERTIFICATE-----\n"
  12100. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12101. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12102. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12103. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12104. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12105. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12106. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12107. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12108. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12109. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12110. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12111. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12112. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12113. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12114. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12115. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12116. "-----END CERTIFICATE-----\n";
  12117. // clang-format on
  12118. SSLClient cli("google.com");
  12119. cli.load_ca_cert_store(cert, sizeof(cert));
  12120. const auto res = cli.Get("/");
  12121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12122. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12123. }
  12124. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12125. SSLClient cli("www.youtube.com");
  12126. cli.set_ca_cert_path(CA_CERT_FILE);
  12127. cli.enable_server_certificate_verification(true);
  12128. cli.set_follow_location(true);
  12129. auto res = cli.Get("/");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12134. SSLClient cli("wWw.YouTube.Com");
  12135. cli.set_ca_cert_path(CA_CERT_FILE);
  12136. cli.enable_server_certificate_verification(true);
  12137. cli.enable_server_hostname_verification(true);
  12138. cli.set_follow_location(true);
  12139. auto res = cli.Get("/");
  12140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12141. ASSERT_EQ(StatusCode::OK_200, res->status);
  12142. }
  12143. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12144. SSLClient cli("gOoGlE.COm");
  12145. cli.enable_server_certificate_verification(true);
  12146. cli.enable_server_hostname_verification(true);
  12147. cli.set_follow_location(true);
  12148. auto res = cli.Get("/");
  12149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12150. ASSERT_EQ(StatusCode::OK_200, res->status);
  12151. }
  12152. TEST(SSLClientTest, Issue2004_Online) {
  12153. Client client("https://google.com");
  12154. client.set_follow_location(true);
  12155. auto res = client.Get("/");
  12156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12157. ASSERT_EQ(StatusCode::OK_200, res->status);
  12158. auto body = res->body;
  12159. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12160. }
  12161. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12162. // Create SSLClient with invalid cert/key to make is_valid() return false
  12163. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12164. "nonexistent_key.pem");
  12165. // is_valid() should be false due to cert loading failure
  12166. ASSERT_FALSE(cli.is_valid());
  12167. auto res = cli.Get("/");
  12168. ASSERT_FALSE(res);
  12169. EXPECT_EQ(Error::SSLConnection, res.error());
  12170. }
  12171. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12172. // Test for Issue #2251: SSL error not properly reported when client cert
  12173. // and key paths are swapped or mismatched
  12174. // This simulates the scenario where user accidentally swaps the cert and key
  12175. // files
  12176. // Using client cert file as private key and vice versa (completely wrong)
  12177. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12178. // Should fail validation due to cert/key mismatch
  12179. ASSERT_FALSE(cli.is_valid());
  12180. // Attempt to make a request should fail with proper error
  12181. auto res = cli.Get("/");
  12182. ASSERT_FALSE(res);
  12183. EXPECT_EQ(Error::SSLConnection, res.error());
  12184. // SSL error should be recorded in the Result object (this is the key fix for
  12185. // Issue #2251)
  12186. auto backend_error = res.ssl_backend_error();
  12187. EXPECT_NE(0u, backend_error);
  12188. }
  12189. // Tests cert/key mismatch detection at the TLS context level
  12190. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12191. // Test that using mismatched cert/key causes connection failure.
  12192. // We verify this at the SSLClient level rather than through internal
  12193. // TLS API functions.
  12194. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12195. cli.enable_server_certificate_verification(false);
  12196. cli.set_connection_timeout(2);
  12197. // The mismatch should cause a connection or handshake error
  12198. auto res = cli.Get("/test");
  12199. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12200. // Either way, the request should fail
  12201. EXPECT_FALSE(res);
  12202. }
  12203. #endif
  12204. #if 0
  12205. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12206. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12207. ASSERT_TRUE(cli != nullptr);
  12208. cli->set_address_family(AF_INET6);
  12209. cli->set_interface("en0");
  12210. auto res = cli->Get("/get");
  12211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12212. ASSERT_EQ(StatusCode::OK_200, res->status);
  12213. }
  12214. #endif
  12215. // Client certificate tests - work with all TLS backends
  12216. #ifdef CPPHTTPLIB_SSL_ENABLED
  12217. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  12218. void ClientCertPresent(
  12219. const std::string &client_cert_file,
  12220. const std::string &client_private_key_file,
  12221. const std::string &client_encrypted_private_key_pass = std::string(),
  12222. const ClientCertServerSetup &setup = nullptr) {
  12223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12224. CLIENT_CA_CERT_DIR);
  12225. ASSERT_TRUE(svr.is_valid());
  12226. if (setup) { setup(svr); }
  12227. svr.Get("/test", [&](const Request &req, Response &res) {
  12228. res.set_content("test", "text/plain");
  12229. auto cert = req.peer_cert();
  12230. ASSERT_TRUE(static_cast<bool>(cert));
  12231. std::string common_name = cert.subject_cn();
  12232. EXPECT_EQ("Common Name", common_name);
  12233. });
  12234. auto port = svr.bind_to_any_port(HOST);
  12235. ASSERT_LT(0, port);
  12236. thread t = thread([&]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. t.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  12244. client_encrypted_private_key_pass);
  12245. cli.enable_server_certificate_verification(false);
  12246. cli.set_connection_timeout(30);
  12247. auto res = cli.Get("/test");
  12248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12249. ASSERT_EQ(StatusCode::OK_200, res->status);
  12250. }
  12251. TEST(SSLClientServerTest, ClientCertPresent) {
  12252. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12253. }
  12254. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12255. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12256. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12257. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12258. }
  12259. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  12260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12261. CLIENT_CA_CERT_DIR);
  12262. ASSERT_TRUE(svr.is_valid());
  12263. if (setup) { setup(svr); }
  12264. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  12265. auto port = svr.bind_to_any_port(HOST);
  12266. ASSERT_LT(0, port);
  12267. thread t = thread([&]() { svr.listen_after_bind(); });
  12268. auto se = detail::scope_exit([&] {
  12269. svr.stop();
  12270. t.join();
  12271. ASSERT_FALSE(svr.is_running());
  12272. });
  12273. svr.wait_until_ready();
  12274. SSLClient cli(HOST, port);
  12275. cli.set_connection_timeout(30);
  12276. // Skip the server certificate check, so that the request fails because the
  12277. // client certificate is missing rather than because cert.pem is not trusted
  12278. cli.enable_server_certificate_verification(false);
  12279. auto res = cli.Get("/test");
  12280. ASSERT_FALSE(res);
  12281. // The server rejects the client during the handshake, or on TLS 1.3 right
  12282. // after it, which the client only notices on its first read
  12283. EXPECT_TRUE(res.error() == Error::SSLConnection || res.error() == Error::Read)
  12284. << to_string(res.error());
  12285. if (res.error() == Error::SSLConnection) {
  12286. EXPECT_NE(0UL, res.ssl_backend_error());
  12287. }
  12288. }
  12289. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  12290. // A server that requires client certificates must keep requiring them after a
  12291. // verify callback is set on its context, or set and then cleared again.
  12292. void ClientCertStillRequired(bool clear_callback) {
  12293. auto setup = [clear_callback](SSLServer &svr) {
  12294. ASSERT_TRUE(tls::set_verify_callback(
  12295. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  12296. if (clear_callback) {
  12297. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  12298. }
  12299. };
  12300. ClientCertMissing(setup);
  12301. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  12302. setup);
  12303. }
  12304. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  12305. ClientCertStillRequired(false);
  12306. }
  12307. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  12308. ClientCertStillRequired(true);
  12309. }
  12310. // PEM memory-based constructor tests (works with all TLS backends)
  12311. void PemMemoryClientCertPresent(
  12312. const std::string &client_cert_file,
  12313. const std::string &client_private_key_file,
  12314. const std::string &client_encrypted_private_key_pass = std::string()) {
  12315. // Read PEM files into memory
  12316. std::string server_cert_pem, server_key_pem;
  12317. std::string client_ca_pem;
  12318. std::string client_cert_pem, client_key_pem;
  12319. read_file(SERVER_CERT_FILE, server_cert_pem);
  12320. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12321. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12322. read_file(client_cert_file, client_cert_pem);
  12323. read_file(client_private_key_file, client_key_pem);
  12324. // Create server with PEM memory
  12325. SSLServer::PemMemory server_pem = {
  12326. server_cert_pem.c_str(),
  12327. server_cert_pem.size(),
  12328. server_key_pem.c_str(),
  12329. server_key_pem.size(),
  12330. client_ca_pem.c_str(),
  12331. client_ca_pem.size(),
  12332. nullptr // no password for server key
  12333. };
  12334. SSLServer svr(server_pem);
  12335. ASSERT_TRUE(svr.is_valid());
  12336. svr.Get("/test", [&](const Request &, Response &res) {
  12337. res.set_content("test", "text/plain");
  12338. });
  12339. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12340. auto se = detail::scope_exit([&] {
  12341. svr.stop();
  12342. t.join();
  12343. ASSERT_FALSE(svr.is_running());
  12344. });
  12345. svr.wait_until_ready();
  12346. // Create client with PEM memory
  12347. const char *password = client_encrypted_private_key_pass.empty()
  12348. ? nullptr
  12349. : client_encrypted_private_key_pass.c_str();
  12350. SSLClient::PemMemory client_pem = {
  12351. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12352. client_key_pem.size(), password};
  12353. SSLClient cli(HOST, PORT, client_pem);
  12354. cli.enable_server_certificate_verification(false);
  12355. cli.set_connection_timeout(30);
  12356. auto res = cli.Get("/test");
  12357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12358. ASSERT_EQ(StatusCode::OK_200, res->status);
  12359. }
  12360. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12361. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12362. }
  12363. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12364. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12365. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12366. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12367. }
  12368. TEST(SSLClientServerTest, TrustDirOptional) {
  12369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12370. ASSERT_TRUE(svr.is_valid());
  12371. svr.Get("/test", [&](const Request &, Response &res) {
  12372. res.set_content("test", "text/plain");
  12373. });
  12374. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12375. auto se = detail::scope_exit([&] {
  12376. svr.stop();
  12377. t.join();
  12378. ASSERT_FALSE(svr.is_running());
  12379. });
  12380. svr.wait_until_ready();
  12381. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12382. cli.enable_server_certificate_verification(false);
  12383. cli.set_connection_timeout(30);
  12384. auto res = cli.Get("/test");
  12385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12386. ASSERT_EQ(StatusCode::OK_200, res->status);
  12387. }
  12388. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12389. class NoListenSSLServer : public SSLServer {
  12390. public:
  12391. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12392. const char *client_ca_cert_file_path,
  12393. const char *client_ca_cert_dir_path = nullptr)
  12394. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12395. client_ca_cert_dir_path),
  12396. stop_(false) {}
  12397. std::atomic_bool stop_;
  12398. private:
  12399. bool process_and_close_socket(socket_t /*sock*/) override {
  12400. // Don't create SSL context
  12401. while (!stop_.load()) {
  12402. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12403. }
  12404. return true;
  12405. }
  12406. };
  12407. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12408. CLIENT_CA_CERT_FILE);
  12409. ASSERT_TRUE(svr.is_valid());
  12410. svr.Get("/test", [&](const Request &, Response &res) {
  12411. res.set_content("test", "text/plain");
  12412. });
  12413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop_ = true;
  12416. svr.stop();
  12417. t.join();
  12418. ASSERT_FALSE(svr.is_running());
  12419. });
  12420. svr.wait_until_ready();
  12421. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12422. cli.enable_server_certificate_verification(false);
  12423. cli.set_connection_timeout(1);
  12424. auto res = cli.Get("/test");
  12425. ASSERT_TRUE(!res);
  12426. EXPECT_EQ(Error::SSLConnection, res.error());
  12427. // Timeout results in WantRead error code (maps to backend-specific value)
  12428. EXPECT_NE(0, res.ssl_error());
  12429. }
  12430. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12431. // Test SSLServer with client certificate verification using the standard
  12432. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12434. CLIENT_CA_CERT_DIR);
  12435. ASSERT_TRUE(svr.is_valid());
  12436. svr.Get("/test", [&](const Request &req, Response &res) {
  12437. res.set_content("test", "text/plain");
  12438. auto cert = req.peer_cert();
  12439. ASSERT_TRUE(static_cast<bool>(cert));
  12440. auto common_name = cert.subject_cn();
  12441. EXPECT_EQ("Common Name", common_name);
  12442. });
  12443. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12444. auto se = detail::scope_exit([&] {
  12445. svr.stop();
  12446. t.join();
  12447. ASSERT_FALSE(svr.is_running());
  12448. });
  12449. svr.wait_until_ready();
  12450. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12451. cli.enable_server_certificate_verification(false);
  12452. cli.set_connection_timeout(30);
  12453. auto res = cli.Get("/test");
  12454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12455. ASSERT_EQ(StatusCode::OK_200, res->status);
  12456. }
  12457. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12458. // Verifies that wildcard matching and exact matching work consistently
  12459. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12460. using namespace httplib::tls;
  12461. // We need a running server to test against
  12462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12463. ASSERT_TRUE(svr.is_valid());
  12464. svr.Get("/test", [](const Request &, Response &res) {
  12465. res.set_content("ok", "text/plain");
  12466. });
  12467. thread t([&]() { svr.listen(HOST, PORT); });
  12468. auto se = detail::scope_exit([&] {
  12469. svr.stop();
  12470. t.join();
  12471. });
  12472. svr.wait_until_ready();
  12473. bool verify_callback_called = false;
  12474. bool verify_result_wrong = false;
  12475. SSLClient cli(HOST, PORT);
  12476. cli.enable_server_certificate_verification(true);
  12477. cli.set_ca_cert_path(CA_CERT_FILE);
  12478. cli.set_connection_timeout(5);
  12479. // Note: Test certificate has CN="Common Name", not "localhost"
  12480. bool verify_result_cn = false;
  12481. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12482. verify_callback_called = true;
  12483. if (!ctx.cert) return false;
  12484. // Test 1: "Common Name" should match (our test server cert CN)
  12485. verify_result_cn = ctx.check_hostname("Common Name");
  12486. // Test 2: wrong hostname should not match
  12487. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12488. return true; // Accept for the purpose of this test
  12489. });
  12490. auto res = cli.Get("/test");
  12491. // The request may succeed or fail depending on cert configuration
  12492. // but the callback should have been called
  12493. ASSERT_TRUE(verify_callback_called)
  12494. << "Verify callback should have been called";
  12495. // CN="Common Name" should match our test certificate
  12496. //
  12497. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12498. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12499. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12500. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12501. // <openssl/base.h>, which is included transitively when
  12502. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12503. #if defined(OPENSSL_IS_BORINGSSL)
  12504. EXPECT_FALSE(verify_result_cn)
  12505. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12506. #else
  12507. EXPECT_TRUE(verify_result_cn)
  12508. << "verify_hostname should match 'Common Name' (certificate CN)";
  12509. #endif
  12510. // Wrong hostname should not match
  12511. EXPECT_FALSE(verify_result_wrong)
  12512. << "verify_hostname should not match 'wronghost.example.com'";
  12513. }
  12514. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12515. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12516. // X509_check_ip behavior and must hold for every backend.
  12517. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12518. using namespace httplib::tls;
  12519. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12520. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12521. ASSERT_TRUE(svr.is_valid());
  12522. svr.Get("/test", [](const Request &, Response &res) {
  12523. res.set_content("ok", "text/plain");
  12524. });
  12525. thread t([&]() { svr.listen(HOST, PORT); });
  12526. auto se = detail::scope_exit([&] {
  12527. svr.stop();
  12528. t.join();
  12529. });
  12530. svr.wait_until_ready();
  12531. bool verify_callback_called = false;
  12532. bool ip_matched_via_cn = true;
  12533. SSLClient cli(HOST, PORT);
  12534. cli.enable_server_certificate_verification(true);
  12535. cli.set_ca_cert_path(CA_CERT_FILE);
  12536. cli.set_connection_timeout(5);
  12537. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12538. verify_callback_called = true;
  12539. if (!ctx.cert) return false;
  12540. // The IP appears only in the CN, so it must NOT be accepted.
  12541. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12542. return true; // Accept for the purpose of this test
  12543. });
  12544. cli.Get("/test");
  12545. ASSERT_TRUE(verify_callback_called)
  12546. << "Verify callback should have been called";
  12547. EXPECT_FALSE(ip_matched_via_cn)
  12548. << "An IP host must not be authenticated via the certificate CN";
  12549. }
  12550. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12551. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12552. using namespace httplib::tls;
  12553. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12554. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12555. ASSERT_TRUE(svr.is_valid());
  12556. svr.Get("/test", [](const Request &, Response &res) {
  12557. res.set_content("ok", "text/plain");
  12558. });
  12559. thread t([&]() { svr.listen(HOST, PORT); });
  12560. auto se = detail::scope_exit([&] {
  12561. svr.stop();
  12562. t.join();
  12563. });
  12564. svr.wait_until_ready();
  12565. bool verify_callback_called = false;
  12566. bool san_matched = false;
  12567. bool wrong_ipv6_matched = true;
  12568. bool cn_ipv6_matched = true;
  12569. SSLClient cli(HOST, PORT);
  12570. cli.enable_server_certificate_verification(true);
  12571. cli.set_ca_cert_path(CA_CERT_FILE);
  12572. cli.set_connection_timeout(5);
  12573. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12574. verify_callback_called = true;
  12575. if (!ctx.cert) return false;
  12576. // Matches the IPv6 iPAddress SAN.
  12577. san_matched = ctx.check_hostname("2001:db8::1");
  12578. // A different IPv6 address must not match.
  12579. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12580. // "::1" lives only in the CN, so it must not be accepted.
  12581. cn_ipv6_matched = ctx.check_hostname("::1");
  12582. return true; // Accept for the purpose of this test
  12583. });
  12584. cli.Get("/test");
  12585. ASSERT_TRUE(verify_callback_called)
  12586. << "Verify callback should have been called";
  12587. EXPECT_TRUE(san_matched)
  12588. << "verify_hostname should match an IPv6 iPAddress SAN";
  12589. EXPECT_FALSE(wrong_ipv6_matched)
  12590. << "verify_hostname should not match a non-matching IPv6 address";
  12591. EXPECT_FALSE(cn_ipv6_matched)
  12592. << "An IPv6 host must not be authenticated via the certificate CN";
  12593. }
  12594. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12595. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12596. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12597. using namespace httplib::tls;
  12598. // SANs: DNS:a.zz, IP:42.46.122.122
  12599. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12600. ASSERT_TRUE(svr.is_valid());
  12601. svr.Get("/test", [](const Request &, Response &res) {
  12602. res.set_content("ok", "text/plain");
  12603. });
  12604. auto port = svr.bind_to_any_port(HOST);
  12605. thread t([&]() { svr.listen_after_bind(); });
  12606. auto se = detail::scope_exit([&] {
  12607. svr.stop();
  12608. t.join();
  12609. });
  12610. svr.wait_until_ready();
  12611. bool verify_callback_called = false;
  12612. bool dns_san_matched = false;
  12613. bool ip_san_matched = false;
  12614. bool ip_matched_via_dns_san = true;
  12615. bool dns_matched_via_ip_san = true;
  12616. SSLClient cli(HOST, port);
  12617. cli.enable_server_certificate_verification(true);
  12618. cli.set_ca_cert_path(CA_CERT_FILE);
  12619. cli.set_connection_timeout(5);
  12620. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12621. verify_callback_called = true;
  12622. if (!ctx.cert) return false;
  12623. dns_san_matched = ctx.check_hostname("a.zz");
  12624. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12625. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12626. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12627. return true; // Accept for the purpose of this test
  12628. });
  12629. cli.Get("/test");
  12630. ASSERT_TRUE(verify_callback_called)
  12631. << "Verify callback should have been called";
  12632. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12633. EXPECT_TRUE(ip_san_matched)
  12634. << "verify_hostname should match an iPAddress SAN";
  12635. EXPECT_FALSE(ip_matched_via_dns_san)
  12636. << "An IP host must not be authenticated via a dNSName SAN";
  12637. EXPECT_FALSE(dns_matched_via_ip_san)
  12638. << "A DNS host must not be authenticated via an iPAddress SAN";
  12639. }
  12640. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12641. // "www.*.example.test" names one host and not every host under example.test.
  12642. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12643. using namespace httplib::tls;
  12644. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12645. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12646. ASSERT_TRUE(svr.is_valid());
  12647. svr.Get("/test", [](const Request &, Response &res) {
  12648. res.set_content("ok", "text/plain");
  12649. });
  12650. auto port = svr.bind_to_any_port(HOST);
  12651. thread t([&]() { svr.listen_after_bind(); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. t.join();
  12655. });
  12656. svr.wait_until_ready();
  12657. bool verify_callback_called = false;
  12658. bool leftmost_wildcard_matched = false;
  12659. bool wildcard_spanned_labels = true;
  12660. bool inner_wildcard_matched = true;
  12661. SSLClient cli(HOST, port);
  12662. cli.enable_server_certificate_verification(true);
  12663. cli.set_ca_cert_path(CA_CERT_FILE);
  12664. cli.set_connection_timeout(5);
  12665. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12666. verify_callback_called = true;
  12667. if (!ctx.cert) return false;
  12668. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12669. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12670. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12671. return true; // Accept for the purpose of this test
  12672. });
  12673. cli.Get("/test");
  12674. ASSERT_TRUE(verify_callback_called)
  12675. << "Verify callback should have been called";
  12676. EXPECT_TRUE(leftmost_wildcard_matched)
  12677. << "A leftmost wildcard should match a single label";
  12678. EXPECT_FALSE(wildcard_spanned_labels)
  12679. << "A wildcard label must not match more than one label";
  12680. EXPECT_FALSE(inner_wildcard_matched)
  12681. << "A wildcard outside the leftmost label must not be honoured";
  12682. }
  12683. // sans() must report each SAN entry under its own type.
  12684. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12685. using namespace httplib::tls;
  12686. // SANs: DNS:a.zz, IP:42.46.122.122
  12687. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12688. ASSERT_TRUE(svr.is_valid());
  12689. svr.Get("/test", [](const Request &, Response &res) {
  12690. res.set_content("ok", "text/plain");
  12691. });
  12692. auto port = svr.bind_to_any_port(HOST);
  12693. thread t([&]() { svr.listen_after_bind(); });
  12694. auto se = detail::scope_exit([&] {
  12695. svr.stop();
  12696. t.join();
  12697. });
  12698. svr.wait_until_ready();
  12699. bool verify_callback_called = false;
  12700. std::vector<SanEntry> sans;
  12701. SSLClient cli(HOST, port);
  12702. cli.enable_server_certificate_verification(true);
  12703. cli.set_ca_cert_path(CA_CERT_FILE);
  12704. cli.set_connection_timeout(5);
  12705. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12706. verify_callback_called = true;
  12707. if (!ctx.cert) return false;
  12708. sans = ctx.sans();
  12709. return true; // Accept for the purpose of this test
  12710. });
  12711. cli.Get("/test");
  12712. ASSERT_TRUE(verify_callback_called)
  12713. << "Verify callback should have been called";
  12714. auto has_san = [&](SanType type, const std::string &value) {
  12715. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12716. return san.type == type && san.value == value;
  12717. });
  12718. };
  12719. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12720. << "sans() should report the dNSName SAN";
  12721. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12722. << "sans() should report the iPAddress SAN";
  12723. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12724. << "sans() must not report the dNSName SAN as an address";
  12725. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12726. << "sans() must not report the iPAddress SAN as a DNS name";
  12727. }
  12728. #endif
  12729. // mbedTLS-specific callback constructor test
  12730. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12731. #ifdef CPPHTTPLIB_SSL_ENABLED
  12732. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12734. ASSERT_TRUE(svr.is_valid());
  12735. // Set up a handler to verify client certificate is present
  12736. bool client_cert_verified = false;
  12737. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12738. // Verify that client certificate was provided
  12739. client_cert_verified = true;
  12740. res.set_content("success", "text/plain");
  12741. });
  12742. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12743. auto se = detail::scope_exit([&] {
  12744. svr.stop();
  12745. t.join();
  12746. ASSERT_FALSE(svr.is_running());
  12747. });
  12748. svr.wait_until_ready();
  12749. // Client with certificate
  12750. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12751. cli.enable_server_certificate_verification(false);
  12752. cli.set_connection_timeout(30);
  12753. auto res = cli.Get("/test");
  12754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12755. ASSERT_EQ(StatusCode::OK_200, res->status);
  12756. ASSERT_TRUE(client_cert_verified);
  12757. EXPECT_EQ("success", res->body);
  12758. }
  12759. #endif
  12760. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12761. // backends
  12762. #ifdef CPPHTTPLIB_SSL_ENABLED
  12763. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12764. using namespace httplib::tls;
  12765. // Test that when client CA cert file is provided,
  12766. // the server properly requests and validates client certificates
  12767. // Create a server with client authentication
  12768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12769. ASSERT_TRUE(svr.is_valid());
  12770. bool handler_called = false;
  12771. svr.Get("/test", [&](const Request &req, Response &res) {
  12772. handler_called = true;
  12773. // Verify that a client certificate was provided
  12774. auto cert = req.peer_cert();
  12775. ASSERT_TRUE(static_cast<bool>(cert));
  12776. // Get the issuer name
  12777. std::string issuer_str = cert.issuer_name();
  12778. ASSERT_FALSE(issuer_str.empty());
  12779. // The client certificate should be issued by our test CA
  12780. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12781. res.set_content("authenticated", "text/plain");
  12782. });
  12783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12784. auto se = detail::scope_exit([&] {
  12785. svr.stop();
  12786. t.join();
  12787. ASSERT_FALSE(svr.is_running());
  12788. });
  12789. svr.wait_until_ready();
  12790. // Connect with a client certificate issued by the CA
  12791. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12792. cli.enable_server_certificate_verification(false);
  12793. cli.set_connection_timeout(30);
  12794. auto res = cli.Get("/test");
  12795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12796. ASSERT_EQ(StatusCode::OK_200, res->status);
  12797. ASSERT_TRUE(handler_called);
  12798. EXPECT_EQ("authenticated", res->body);
  12799. }
  12800. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12801. using namespace httplib::tls;
  12802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12803. ASSERT_TRUE(svr.is_valid());
  12804. svr.Get("/test", [](const Request &, Response &res) {
  12805. res.set_content("ok", "text/plain");
  12806. });
  12807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12808. auto se = detail::scope_exit([&] {
  12809. svr.stop();
  12810. t.join();
  12811. });
  12812. svr.wait_until_ready();
  12813. SSLClient cli(HOST, PORT);
  12814. cli.enable_server_certificate_verification(false);
  12815. cli.set_connection_timeout(30);
  12816. bool cert_checked = false;
  12817. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12818. if (ctx.cert) {
  12819. auto sans = ctx.sans();
  12820. // Test certificate may or may not have SANs - just verify the API
  12821. // works If SANs exist, verify the types are valid
  12822. for (const auto &san : sans) {
  12823. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12824. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12825. san.type == SanType::OTHER);
  12826. EXPECT_FALSE(san.value.empty());
  12827. }
  12828. cert_checked = true;
  12829. }
  12830. return true;
  12831. });
  12832. auto res = cli.Get("/test");
  12833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12834. EXPECT_TRUE(cert_checked);
  12835. }
  12836. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12837. using namespace httplib::tls;
  12838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12839. ASSERT_TRUE(svr.is_valid());
  12840. svr.Get("/test", [](const Request &, Response &res) {
  12841. res.set_content("ok", "text/plain");
  12842. });
  12843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. });
  12848. svr.wait_until_ready();
  12849. SSLClient cli(HOST, PORT);
  12850. cli.enable_server_certificate_verification(false);
  12851. cli.set_connection_timeout(30);
  12852. bool validity_checked = false;
  12853. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12854. if (ctx.cert) {
  12855. time_t not_before = 0, not_after = 0;
  12856. bool result = ctx.validity(not_before, not_after);
  12857. EXPECT_TRUE(result);
  12858. // Verify that not_before < now < not_after for a valid cert
  12859. time_t now = time(nullptr);
  12860. EXPECT_LT(not_before, now);
  12861. EXPECT_GT(not_after, now);
  12862. validity_checked = true;
  12863. }
  12864. return true;
  12865. });
  12866. auto res = cli.Get("/test");
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. EXPECT_TRUE(validity_checked);
  12869. }
  12870. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12871. using namespace httplib::tls;
  12872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12873. ASSERT_TRUE(svr.is_valid());
  12874. svr.Get("/test", [](const Request &, Response &res) {
  12875. res.set_content("ok", "text/plain");
  12876. });
  12877. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12878. auto se = detail::scope_exit([&] {
  12879. svr.stop();
  12880. t.join();
  12881. });
  12882. svr.wait_until_ready();
  12883. SSLClient cli(HOST, PORT);
  12884. cli.enable_server_certificate_verification(false);
  12885. cli.set_connection_timeout(30);
  12886. bool serial_checked = false;
  12887. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12888. if (ctx.cert) {
  12889. std::string serial = ctx.serial();
  12890. EXPECT_FALSE(serial.empty());
  12891. // Serial should be a hex string
  12892. for (char c : serial) {
  12893. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12894. (c >= 'a' && c <= 'f'));
  12895. }
  12896. serial_checked = true;
  12897. }
  12898. return true;
  12899. });
  12900. auto res = cli.Get("/test");
  12901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12902. EXPECT_TRUE(serial_checked);
  12903. }
  12904. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12905. // Test 1: Valid CA file - no error should be recorded
  12906. {
  12907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12908. CLIENT_CA_CERT_FILE);
  12909. ASSERT_TRUE(svr.is_valid());
  12910. // With valid setup, last_ssl_error should be 0
  12911. EXPECT_EQ(0, svr.ssl_last_error());
  12912. }
  12913. // Test 2: Invalid CA file content
  12914. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12915. {
  12916. // Create a temporary file with completely invalid content
  12917. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12918. {
  12919. std::ofstream ofs(temp_invalid_ca);
  12920. ofs << "This is not a certificate file at all\n";
  12921. ofs << "Just plain text content\n";
  12922. }
  12923. // Create server with invalid CA file
  12924. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12925. // Clean up temporary file
  12926. std::remove(temp_invalid_ca);
  12927. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12928. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12929. // Note: SSL_CTX_load_verify_locations typically fails first,
  12930. // but our error handling code path is still exercised
  12931. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12932. }
  12933. }
  12934. TEST(VerifyCallbackTest, VerifyContextFields) {
  12935. using namespace httplib::tls;
  12936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12937. ASSERT_TRUE(svr.is_valid());
  12938. svr.Get("/test", [](const Request &, Response &res) {
  12939. res.set_content("ok", "text/plain");
  12940. });
  12941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12942. auto se = detail::scope_exit([&] {
  12943. svr.stop();
  12944. t.join();
  12945. });
  12946. svr.wait_until_ready();
  12947. SSLClient cli(HOST, PORT);
  12948. cli.enable_server_certificate_verification(false);
  12949. cli.set_connection_timeout(30);
  12950. int callback_count = 0;
  12951. bool saw_leaf_cert = false;
  12952. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12953. if (ctx.cert) {
  12954. callback_count++;
  12955. // We should see at least one certificate (the leaf)
  12956. std::string cn = ctx.subject_cn();
  12957. if (!cn.empty()) { saw_leaf_cert = true; }
  12958. // Verify context fields are populated
  12959. EXPECT_NE(ctx.session, nullptr);
  12960. EXPECT_GE(ctx.depth, 0);
  12961. }
  12962. return true;
  12963. });
  12964. auto res = cli.Get("/test");
  12965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12966. EXPECT_GT(callback_count, 0);
  12967. EXPECT_TRUE(saw_leaf_cert);
  12968. }
  12969. // Each client's verifier is stored with its own TLS context, so configuring a
  12970. // second client on the same thread must not replace the first one's.
  12971. TEST(VerifyCallbackTest, PerClientVerifiersOnSameThread) {
  12972. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12973. ASSERT_TRUE(svr.is_valid());
  12974. svr.Get("/test", [](const Request &, Response &res) {
  12975. res.set_content("ok", "text/plain");
  12976. });
  12977. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12978. auto se = detail::scope_exit([&] {
  12979. svr.stop();
  12980. t.join();
  12981. });
  12982. svr.wait_until_ready();
  12983. std::atomic<int> count1{0};
  12984. std::atomic<int> count2{0};
  12985. SSLClient cli1(HOST, PORT);
  12986. cli1.enable_server_certificate_verification(false);
  12987. cli1.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12988. count1++;
  12989. return true;
  12990. });
  12991. SSLClient cli2(HOST, PORT);
  12992. cli2.enable_server_certificate_verification(false);
  12993. cli2.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12994. count2++;
  12995. return true;
  12996. });
  12997. auto res1 = cli1.Get("/test");
  12998. ASSERT_TRUE(res1) << "Error: " << to_string(res1.error());
  12999. EXPECT_GT(count1.load(), 0);
  13000. EXPECT_EQ(0, count2.load());
  13001. count1 = 0;
  13002. auto res2 = cli2.Get("/test");
  13003. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  13004. EXPECT_EQ(0, count1.load());
  13005. EXPECT_GT(count2.load(), 0);
  13006. }
  13007. // A verifier set on one thread must still run when the request is made from
  13008. // another thread.
  13009. TEST(VerifyCallbackTest, VerifierRunsOnAnotherThread) {
  13010. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13011. ASSERT_TRUE(svr.is_valid());
  13012. svr.Get("/test", [](const Request &, Response &res) {
  13013. res.set_content("ok", "text/plain");
  13014. });
  13015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13016. auto se = detail::scope_exit([&] {
  13017. svr.stop();
  13018. t.join();
  13019. });
  13020. svr.wait_until_ready();
  13021. std::atomic<int> count{0};
  13022. SSLClient cli(HOST, PORT);
  13023. cli.enable_server_certificate_verification(false);
  13024. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13025. count++;
  13026. return true;
  13027. });
  13028. Result res;
  13029. thread worker([&]() { res = cli.Get("/test"); });
  13030. worker.join();
  13031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13032. EXPECT_GT(count.load(), 0);
  13033. }
  13034. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13035. using httplib::tls::TlsError;
  13036. // Test that verify_error_to_string returns empty for success
  13037. std::string success_str = TlsError::verify_error_to_string(0);
  13038. EXPECT_TRUE(success_str.empty());
  13039. // Test that verify_error_to_string returns non-empty for error codes
  13040. // Using a common error code (certificate expired)
  13041. std::string error_str =
  13042. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13043. EXPECT_FALSE(error_str.empty());
  13044. }
  13045. TEST(SessionVerifierTest, CertificateAccepted) {
  13046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13047. ASSERT_TRUE(svr.is_valid());
  13048. svr.Get("/test", [](const Request &, Response &res) {
  13049. res.set_content("ok", "text/plain");
  13050. });
  13051. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13052. auto se = detail::scope_exit([&] {
  13053. svr.stop();
  13054. t.join();
  13055. });
  13056. svr.wait_until_ready();
  13057. SSLClient cli(HOST, PORT);
  13058. cli.enable_server_certificate_verification(false);
  13059. cli.set_connection_timeout(30);
  13060. bool callback_called = false;
  13061. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13062. EXPECT_NE(session, nullptr);
  13063. callback_called = true;
  13064. return SSLVerifierResponse::CertificateAccepted;
  13065. });
  13066. auto res = cli.Get("/test");
  13067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13068. EXPECT_EQ(200, res->status);
  13069. EXPECT_TRUE(callback_called);
  13070. }
  13071. TEST(SessionVerifierTest, CertificateRejected) {
  13072. SSLServer svr(SERVER_CERT_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 = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13078. auto se = detail::scope_exit([&] {
  13079. svr.stop();
  13080. t.join();
  13081. });
  13082. svr.wait_until_ready();
  13083. SSLClient cli(HOST, PORT);
  13084. cli.enable_server_certificate_verification(false);
  13085. cli.set_connection_timeout(30);
  13086. bool callback_called = false;
  13087. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13088. EXPECT_NE(session, nullptr);
  13089. callback_called = true;
  13090. return SSLVerifierResponse::CertificateRejected;
  13091. });
  13092. auto res = cli.Get("/test");
  13093. EXPECT_FALSE(res);
  13094. EXPECT_TRUE(callback_called);
  13095. }
  13096. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13098. ASSERT_TRUE(svr.is_valid());
  13099. svr.Get("/test", [](const Request &, Response &res) {
  13100. res.set_content("ok", "text/plain");
  13101. });
  13102. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13103. auto se = detail::scope_exit([&] {
  13104. svr.stop();
  13105. t.join();
  13106. });
  13107. svr.wait_until_ready();
  13108. // NoDecisionMade with verification disabled should succeed (no default check)
  13109. SSLClient cli(HOST, PORT);
  13110. cli.enable_server_certificate_verification(false);
  13111. cli.set_connection_timeout(30);
  13112. bool callback_called = false;
  13113. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13114. EXPECT_NE(session, nullptr);
  13115. callback_called = true;
  13116. return SSLVerifierResponse::NoDecisionMade;
  13117. });
  13118. auto res = cli.Get("/test");
  13119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13120. EXPECT_EQ(200, res->status);
  13121. EXPECT_TRUE(callback_called);
  13122. }
  13123. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13125. ASSERT_TRUE(svr.is_valid());
  13126. svr.Get("/test", [](const Request &, Response &res) {
  13127. res.set_content("ok", "text/plain");
  13128. });
  13129. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13130. auto se = detail::scope_exit([&] {
  13131. svr.stop();
  13132. t.join();
  13133. });
  13134. svr.wait_until_ready();
  13135. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13136. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13137. // so we only check that the request fails, not whether the callback was
  13138. // called.
  13139. SSLClient cli(HOST, PORT);
  13140. cli.enable_server_certificate_verification(true);
  13141. cli.set_connection_timeout(30);
  13142. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13143. EXPECT_NE(session, nullptr);
  13144. return SSLVerifierResponse::NoDecisionMade;
  13145. });
  13146. auto res = cli.Get("/test");
  13147. EXPECT_FALSE(res);
  13148. }
  13149. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13150. // Test SSL server using PemMemory constructor with client CA certificates
  13151. // Read PEM files
  13152. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13153. read_file(SERVER_CERT_FILE, server_cert_pem);
  13154. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13155. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13156. // Create SSLServer with PemMemory constructor including client CA
  13157. SSLServer::PemMemory server_pem = {
  13158. server_cert_pem.c_str(),
  13159. server_cert_pem.size(),
  13160. server_key_pem.c_str(),
  13161. server_key_pem.size(),
  13162. client_ca_pem.c_str(),
  13163. client_ca_pem.size(),
  13164. nullptr // no password for server key
  13165. };
  13166. SSLServer svr(server_pem);
  13167. ASSERT_TRUE(svr.is_valid());
  13168. // No SSL error should be recorded for valid setup
  13169. EXPECT_EQ(0, svr.ssl_last_error());
  13170. // Set up server endpoints
  13171. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13172. res.set_content("ok", "text/plain");
  13173. });
  13174. // Start server in a thread
  13175. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13176. svr.wait_until_ready();
  13177. // Connect with client certificate (using constructor with paths)
  13178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13179. cli.enable_server_certificate_verification(false);
  13180. auto res = cli.Get("/test-pem-ca");
  13181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13182. EXPECT_EQ(200, res->status);
  13183. EXPECT_EQ("ok", res->body);
  13184. svr.stop();
  13185. server_thread.join();
  13186. }
  13187. #endif
  13188. #ifdef _WIN32
  13189. TEST(CleanupTest, WSACleanup) {
  13190. int ret = WSACleanup();
  13191. ASSERT_EQ(0, ret);
  13192. }
  13193. #endif
  13194. #ifndef CPPHTTPLIB_SSL_ENABLED
  13195. TEST(NoSSLSupport, SimpleInterface) {
  13196. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13197. }
  13198. #endif
  13199. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13200. TEST(InvalidScheme, SimpleInterface) {
  13201. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13202. }
  13203. #endif
  13204. TEST(NoScheme, SimpleInterface) {
  13205. Client cli("yahoo.com:80");
  13206. ASSERT_TRUE(cli.is_valid());
  13207. }
  13208. TEST(SendAPI, SimpleInterface_Online) {
  13209. Client cli("http://yahoo.com");
  13210. Request req;
  13211. req.method = "GET";
  13212. req.path = "/";
  13213. auto res = cli.send(req);
  13214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13215. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13216. }
  13217. TEST(SendAPI, WithParamsInRequest) {
  13218. Server svr;
  13219. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13220. EXPECT_TRUE(req.has_param("test"));
  13221. EXPECT_EQ("test_value", req.get_param_value("test"));
  13222. });
  13223. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13224. auto se = detail::scope_exit([&] {
  13225. svr.stop();
  13226. t.join();
  13227. ASSERT_FALSE(svr.is_running());
  13228. });
  13229. svr.wait_until_ready();
  13230. Client cli(HOST, PORT);
  13231. {
  13232. Request req;
  13233. req.method = "GET";
  13234. req.path = "/";
  13235. req.params.emplace("test", "test_value");
  13236. auto res = cli.send(req);
  13237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13238. }
  13239. {
  13240. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13242. }
  13243. }
  13244. TEST(ClientImplMethods, GetSocketTest) {
  13245. httplib::Server svr;
  13246. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13247. res.status = StatusCode::OK_200;
  13248. });
  13249. auto port = svr.bind_to_any_port("127.0.0.1");
  13250. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13251. auto se = detail::scope_exit([&] {
  13252. svr.stop();
  13253. thread.join();
  13254. ASSERT_FALSE(svr.is_running());
  13255. });
  13256. svr.wait_until_ready();
  13257. {
  13258. httplib::Client cli("127.0.0.1", port);
  13259. cli.set_keep_alive(true);
  13260. // Use the behavior of cpp-httplib of opening the connection
  13261. // only when the first request happens. If that changes,
  13262. // this test would be obsolete.
  13263. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13264. // This also implicitly tests the server. But other tests would fail much
  13265. // earlier than this one to be considered.
  13266. auto res = cli.Get("/");
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. EXPECT_EQ(StatusCode::OK_200, res->status);
  13269. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13270. }
  13271. }
  13272. #ifdef CPPHTTPLIB_SSL_ENABLED
  13273. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13274. Client cli("http://yahoo.com");
  13275. auto res = cli.Get("/");
  13276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13277. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13278. cli.set_follow_location(true);
  13279. res = cli.Get("/");
  13280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13281. EXPECT_EQ(StatusCode::OK_200, res->status);
  13282. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13283. }
  13284. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13285. Client cli("https://yahoo.com");
  13286. auto res = cli.Get("/");
  13287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13288. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13289. cli.set_follow_location(true);
  13290. res = cli.Get("/");
  13291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13292. EXPECT_EQ(StatusCode::OK_200, res->status);
  13293. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13294. }
  13295. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13296. Client cli("https://yahoo.com");
  13297. auto res = cli.Get("/");
  13298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13299. ASSERT_FALSE(!res);
  13300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13301. ASSERT_FALSE(res == nullptr);
  13302. ASSERT_TRUE(res != nullptr);
  13303. EXPECT_EQ(Error::Success, res.error());
  13304. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13305. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13306. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13307. cli.set_follow_location(true);
  13308. res = cli.Get("/");
  13309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13310. EXPECT_EQ(Error::Success, res.error());
  13311. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13312. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13313. EXPECT_EQ(StatusCode::OK_200, res->status);
  13314. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13315. }
  13316. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13317. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13318. Client cli("https://cdnjs.cloudflare.com");
  13319. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13320. Headers{{"Accept-Encoding", "br"}});
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. EXPECT_EQ(StatusCode::OK_200, res->status);
  13323. EXPECT_EQ(287630U, res->body.size());
  13324. EXPECT_EQ("application/javascript; charset=utf-8",
  13325. res->get_header_value("Content-Type"));
  13326. }
  13327. #endif
  13328. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13329. #undef REDIR_HOST // Silence compiler warning
  13330. #define REDIR_HOST "https://httpbingo.org"
  13331. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13332. Client cli(REDIR_HOST);
  13333. cli.set_follow_location(true);
  13334. auto res =
  13335. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13337. EXPECT_EQ(StatusCode::OK_200, res->status);
  13338. }
  13339. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13340. Client cli(REDIR_HOST);
  13341. cli.set_follow_location(true);
  13342. Params params;
  13343. params.emplace("url", "http://example.com");
  13344. params.emplace("status_code", "302");
  13345. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13347. EXPECT_EQ(StatusCode::OK_200, res->status);
  13348. }
  13349. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13350. Client cli(REDIR_HOST);
  13351. cli.set_follow_location(true);
  13352. Params params;
  13353. params.emplace("url", "http://example.com");
  13354. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13356. EXPECT_EQ(StatusCode::OK_200, res->status);
  13357. }
  13358. TEST(HttpToHttpsRedirectTest, CertFile) {
  13359. auto ssl_port = PORT + 1;
  13360. Server svr;
  13361. ASSERT_TRUE(svr.is_valid());
  13362. svr.Get("/index", [&](const Request &, Response &res) {
  13363. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13364. "/index");
  13365. svr.stop();
  13366. });
  13367. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13368. ASSERT_TRUE(ssl_svr.is_valid());
  13369. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13370. res.set_content("test", "text/plain");
  13371. ssl_svr.stop();
  13372. });
  13373. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13374. thread t2 =
  13375. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13376. auto se = detail::scope_exit([&] {
  13377. t2.join();
  13378. t.join();
  13379. ASSERT_FALSE(svr.is_running());
  13380. });
  13381. svr.wait_until_ready();
  13382. ssl_svr.wait_until_ready();
  13383. Client cli("127.0.0.1", PORT);
  13384. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13385. cli.enable_server_certificate_verification(true);
  13386. cli.set_follow_location(true);
  13387. cli.set_connection_timeout(30);
  13388. auto res = cli.Get("/index");
  13389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13390. ASSERT_EQ(StatusCode::OK_200, res->status);
  13391. }
  13392. TEST(SSLClientRedirectTest, CertFile) {
  13393. auto ssl_port = PORT + 1;
  13394. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13395. ASSERT_TRUE(ssl_svr1.is_valid());
  13396. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13397. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13398. "/index");
  13399. ssl_svr1.stop();
  13400. });
  13401. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13402. ASSERT_TRUE(ssl_svr2.is_valid());
  13403. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13404. res.set_content("test", "text/plain");
  13405. ssl_svr2.stop();
  13406. });
  13407. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13408. thread t2 =
  13409. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13410. auto se = detail::scope_exit([&] {
  13411. t2.join();
  13412. t.join();
  13413. ASSERT_FALSE(ssl_svr1.is_running());
  13414. });
  13415. ssl_svr1.wait_until_ready();
  13416. ssl_svr2.wait_until_ready();
  13417. SSLClient cli("127.0.0.1", PORT);
  13418. std::string cert;
  13419. read_file(SERVER_CERT2_FILE, cert);
  13420. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13421. cli.enable_server_certificate_verification(true);
  13422. cli.set_follow_location(true);
  13423. cli.set_connection_timeout(30);
  13424. auto res = cli.Get("/index");
  13425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13426. ASSERT_EQ(StatusCode::OK_200, res->status);
  13427. }
  13428. // A store set via set_ca_cert_store() must be carried over to the client that
  13429. // follows a cross-host redirect, rather than replaced by the system CAs.
  13430. TEST(SSLClientRedirectTest, SetCaCertStore) {
  13431. auto ssl_port = PORT + 1;
  13432. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13433. ASSERT_TRUE(ssl_svr1.is_valid());
  13434. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13435. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13436. "/index");
  13437. });
  13438. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13439. ASSERT_TRUE(ssl_svr2.is_valid());
  13440. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13441. res.set_content("test", "text/plain");
  13442. });
  13443. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13444. thread t2 =
  13445. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13446. auto se = detail::scope_exit([&] {
  13447. ssl_svr2.stop();
  13448. ssl_svr1.stop();
  13449. t2.join();
  13450. t.join();
  13451. ASSERT_FALSE(ssl_svr1.is_running());
  13452. });
  13453. ssl_svr1.wait_until_ready();
  13454. ssl_svr2.wait_until_ready();
  13455. SSLClient cli("127.0.0.1", PORT);
  13456. std::string cert;
  13457. read_file(SERVER_CERT2_FILE, cert);
  13458. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13459. cli.enable_server_certificate_verification(true);
  13460. cli.set_follow_location(true);
  13461. cli.set_connection_timeout(30);
  13462. auto res = cli.Get("/index");
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. ASSERT_EQ(StatusCode::OK_200, res->status);
  13465. }
  13466. // The session verifier must also run for the host a redirect leads to.
  13467. TEST(SSLClientRedirectTest, SessionVerifier) {
  13468. auto ssl_port = PORT + 1;
  13469. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13470. ASSERT_TRUE(ssl_svr1.is_valid());
  13471. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13472. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13473. "/index");
  13474. });
  13475. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13476. ASSERT_TRUE(ssl_svr2.is_valid());
  13477. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13478. res.set_content("test", "text/plain");
  13479. });
  13480. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13481. thread t2 =
  13482. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13483. auto se = detail::scope_exit([&] {
  13484. ssl_svr2.stop();
  13485. ssl_svr1.stop();
  13486. t2.join();
  13487. t.join();
  13488. ASSERT_FALSE(ssl_svr1.is_running());
  13489. });
  13490. ssl_svr1.wait_until_ready();
  13491. ssl_svr2.wait_until_ready();
  13492. SSLClient cli("127.0.0.1", PORT);
  13493. std::string cert;
  13494. read_file(SERVER_CERT2_FILE, cert);
  13495. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13496. cli.enable_server_certificate_verification(true);
  13497. cli.set_follow_location(true);
  13498. cli.set_connection_timeout(30);
  13499. // Accept the first host only.
  13500. std::atomic<int> sessions{0};
  13501. cli.set_session_verifier([&](tls::session_t) -> SSLVerifierResponse {
  13502. return sessions++ == 0 ? SSLVerifierResponse::CertificateAccepted
  13503. : SSLVerifierResponse::CertificateRejected;
  13504. });
  13505. auto res = cli.Get("/index");
  13506. ASSERT_FALSE(res);
  13507. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13508. EXPECT_EQ(2, sessions.load());
  13509. }
  13510. // So must the verifier given to set_server_certificate_verifier().
  13511. TEST(SSLClientRedirectTest, ServerCertificateVerifier) {
  13512. auto ssl_port = PORT + 1;
  13513. std::atomic<bool> redirected{false};
  13514. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13515. ASSERT_TRUE(ssl_svr1.is_valid());
  13516. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13517. redirected = true;
  13518. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13519. "/index");
  13520. });
  13521. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13522. ASSERT_TRUE(ssl_svr2.is_valid());
  13523. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13524. res.set_content("test", "text/plain");
  13525. });
  13526. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13527. thread t2 =
  13528. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13529. auto se = detail::scope_exit([&] {
  13530. ssl_svr2.stop();
  13531. ssl_svr1.stop();
  13532. t2.join();
  13533. t.join();
  13534. ASSERT_FALSE(ssl_svr1.is_running());
  13535. });
  13536. ssl_svr1.wait_until_ready();
  13537. ssl_svr2.wait_until_ready();
  13538. SSLClient cli("127.0.0.1", PORT);
  13539. std::string cert;
  13540. read_file(SERVER_CERT2_FILE, cert);
  13541. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13542. cli.enable_server_certificate_verification(true);
  13543. cli.set_follow_location(true);
  13544. cli.set_connection_timeout(30);
  13545. // Accept the host that redirects only; the verifier runs once per
  13546. // certificate in the chain, so count the calls made after the redirect.
  13547. std::atomic<int> calls_after_redirect{0};
  13548. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13549. if (!redirected) { return true; }
  13550. calls_after_redirect++;
  13551. return false;
  13552. });
  13553. auto res = cli.Get("/index");
  13554. ASSERT_FALSE(res);
  13555. EXPECT_LT(0, calls_after_redirect.load());
  13556. }
  13557. #endif
  13558. #ifdef CPPHTTPLIB_SSL_ENABLED
  13559. // Test that set_ca_cert_store() skips system certs (consistent with
  13560. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13561. // should be trusted - system certs should NOT be loaded.
  13562. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13563. // Load a specific cert that is NOT a system CA cert
  13564. std::string cert;
  13565. read_file(SERVER_CERT2_FILE, cert);
  13566. SSLClient cli("google.com");
  13567. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13568. cli.enable_server_certificate_verification(true);
  13569. // This should FAIL because:
  13570. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13571. // 2. System certs should NOT be loaded when custom store is set
  13572. // If system certs WERE loaded, this would succeed
  13573. auto res = cli.Get("/");
  13574. ASSERT_FALSE(res);
  13575. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13576. }
  13577. // Same as above, but through the native store handle path. Regression test:
  13578. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13579. // merged system certs into the user-provided store.
  13580. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13581. std::string cert;
  13582. read_file(SERVER_CERT2_FILE, cert);
  13583. SSLClient cli("google.com");
  13584. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13585. cli.enable_server_certificate_verification(true);
  13586. auto res = cli.Get("/");
  13587. ASSERT_FALSE(res);
  13588. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13589. }
  13590. // A custom store set via the native handle must still verify a server whose
  13591. // cert it does contain.
  13592. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13593. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13594. ASSERT_TRUE(svr.is_valid());
  13595. svr.Get("/test", [&](const Request &, Response &res) {
  13596. res.set_content("test", "text/plain");
  13597. });
  13598. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13599. auto se = detail::scope_exit([&] {
  13600. svr.stop();
  13601. t.join();
  13602. ASSERT_FALSE(svr.is_running());
  13603. });
  13604. svr.wait_until_ready();
  13605. SSLClient cli("127.0.0.1", PORT);
  13606. std::string cert;
  13607. read_file(SERVER_CERT2_FILE, cert);
  13608. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13609. cli.enable_server_certificate_verification(true);
  13610. cli.set_connection_timeout(30);
  13611. auto res = cli.Get("/test");
  13612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13613. ASSERT_EQ(StatusCode::OK_200, res->status);
  13614. }
  13615. // CA certs loaded through the universal Client must be transferred to the
  13616. // client created internally for following an HTTPS redirect. Regression test:
  13617. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13618. // the CA data for redirect transfer.
  13619. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13620. auto ssl_port = PORT + 1;
  13621. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13622. ASSERT_TRUE(ssl_svr1.is_valid());
  13623. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13624. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13625. "/index");
  13626. });
  13627. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13628. ASSERT_TRUE(ssl_svr2.is_valid());
  13629. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13630. res.set_content("test", "text/plain");
  13631. });
  13632. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13633. thread t2 =
  13634. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13635. auto se = detail::scope_exit([&] {
  13636. ssl_svr2.stop();
  13637. ssl_svr1.stop();
  13638. t2.join();
  13639. t.join();
  13640. ASSERT_FALSE(ssl_svr1.is_running());
  13641. });
  13642. ssl_svr1.wait_until_ready();
  13643. ssl_svr2.wait_until_ready();
  13644. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13645. std::string cert;
  13646. read_file(SERVER_CERT2_FILE, cert);
  13647. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13648. cli.enable_server_certificate_verification(true);
  13649. cli.set_follow_location(true);
  13650. cli.set_connection_timeout(30);
  13651. auto res = cli.Get("/index");
  13652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13653. ASSERT_EQ(StatusCode::OK_200, res->status);
  13654. }
  13655. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13656. // so a host signed by a system CA verifies even though a custom CA is set
  13657. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13658. std::string cert;
  13659. read_file(SERVER_CERT2_FILE, cert);
  13660. SSLClient cli("google.com");
  13661. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13662. cli.enable_system_ca(true);
  13663. cli.enable_server_certificate_verification(true);
  13664. auto res = cli.Get("/");
  13665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13666. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13667. }
  13668. // The custom CA remains effective when combined with the system CA
  13669. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13670. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13671. ASSERT_TRUE(svr.is_valid());
  13672. svr.Get("/test", [&](const Request &, Response &res) {
  13673. res.set_content("test", "text/plain");
  13674. });
  13675. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13676. auto se = detail::scope_exit([&] {
  13677. svr.stop();
  13678. t.join();
  13679. ASSERT_FALSE(svr.is_running());
  13680. });
  13681. svr.wait_until_ready();
  13682. SSLClient cli("127.0.0.1", PORT);
  13683. std::string cert;
  13684. read_file(SERVER_CERT2_FILE, cert);
  13685. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13686. cli.enable_system_ca(true);
  13687. cli.enable_server_certificate_verification(true);
  13688. cli.set_connection_timeout(30);
  13689. auto res = cli.Get("/test");
  13690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13691. ASSERT_EQ(StatusCode::OK_200, res->status);
  13692. }
  13693. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13694. // skip chain verification entirely (only the certificate identity was
  13695. // checked), so a server presenting an untrusted certificate with a matching
  13696. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13697. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13698. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13699. ASSERT_TRUE(svr.is_valid());
  13700. svr.Get("/test", [&](const Request &, Response &res) {
  13701. res.set_content("test", "text/plain");
  13702. });
  13703. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13704. auto se = detail::scope_exit([&] {
  13705. svr.stop();
  13706. t.join();
  13707. ASSERT_FALSE(svr.is_running());
  13708. });
  13709. svr.wait_until_ready();
  13710. SSLClient cli("127.0.0.1", PORT);
  13711. std::string cert;
  13712. // A trusted CA that did not sign the server certificate. The server cert
  13713. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13714. // this connection.
  13715. read_file(CLIENT_CA_CERT_FILE, cert);
  13716. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13717. cli.enable_server_certificate_verification(true);
  13718. cli.set_connection_timeout(30);
  13719. auto res = cli.Get("/test");
  13720. ASSERT_FALSE(res);
  13721. }
  13722. // enable_system_ca(false) prevents system CA loading entirely
  13723. TEST(SSLClientTest, DisableSystemCa_Online) {
  13724. SSLClient cli("google.com");
  13725. cli.enable_system_ca(false);
  13726. cli.enable_server_certificate_verification(true);
  13727. auto res = cli.Get("/");
  13728. ASSERT_FALSE(res);
  13729. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13730. // itself when the CA chain is empty
  13731. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13732. res.error() == Error::SSLConnection);
  13733. }
  13734. // The universal Client forwards enable_system_ca()
  13735. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13736. std::string cert;
  13737. read_file(SERVER_CERT2_FILE, cert);
  13738. Client cli("https://google.com");
  13739. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13740. cli.enable_system_ca(true);
  13741. cli.enable_server_certificate_verification(true);
  13742. auto res = cli.Get("/");
  13743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13744. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13745. }
  13746. // The system CA policy must carry over to the client created internally for
  13747. // following a cross-host HTTPS redirect
  13748. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13749. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13750. ASSERT_TRUE(svr.is_valid());
  13751. svr.Get("/index", [&](const Request &, Response &res) {
  13752. res.set_redirect("https://www.google.com/");
  13753. });
  13754. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13755. auto se = detail::scope_exit([&] {
  13756. svr.stop();
  13757. t.join();
  13758. ASSERT_FALSE(svr.is_running());
  13759. });
  13760. svr.wait_until_ready();
  13761. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13762. std::string cert;
  13763. read_file(SERVER_CERT2_FILE, cert);
  13764. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13765. cli.enable_system_ca(true);
  13766. cli.enable_server_certificate_verification(true);
  13767. cli.set_follow_location(true);
  13768. cli.set_connection_timeout(30);
  13769. // Receiving any response proves the redirect client completed the TLS
  13770. // handshake with a system-CA-signed host
  13771. auto res = cli.Get("/index");
  13772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13773. }
  13774. TEST(MultipartFormDataTest, LargeData) {
  13775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13776. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13777. const ContentReader &content_reader) {
  13778. if (req.is_multipart_form_data()) {
  13779. std::vector<FormData> items;
  13780. content_reader(
  13781. [&](const FormData &file) {
  13782. items.push_back(file);
  13783. return true;
  13784. },
  13785. [&](const char *data, size_t data_length) {
  13786. items.back().content.append(data, data_length);
  13787. return true;
  13788. });
  13789. EXPECT_TRUE(std::string(items[0].name) == "document");
  13790. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13791. EXPECT_TRUE(items[0].filename == "2MB_data");
  13792. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13793. EXPECT_TRUE(items[1].name == "hello");
  13794. EXPECT_TRUE(items[1].content == "world");
  13795. EXPECT_TRUE(items[1].filename == "");
  13796. EXPECT_TRUE(items[1].content_type == "");
  13797. } else {
  13798. std::string body;
  13799. content_reader([&](const char *data, size_t data_length) {
  13800. body.append(data, data_length);
  13801. return true;
  13802. });
  13803. }
  13804. });
  13805. auto port = svr.bind_to_any_port(HOST);
  13806. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13807. auto se = detail::scope_exit([&] {
  13808. svr.stop();
  13809. t.join();
  13810. ASSERT_FALSE(svr.is_running());
  13811. });
  13812. svr.wait_until_ready();
  13813. {
  13814. std::string data(1024 * 1024 * 2, '.');
  13815. std::stringstream buffer;
  13816. buffer << data;
  13817. SSLClient cli(HOST, port);
  13818. cli.enable_server_certificate_verification(false);
  13819. UploadFormDataItems items{
  13820. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13821. {"hello", "world", "", ""},
  13822. };
  13823. auto res = cli.Post("/post", items);
  13824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13825. ASSERT_EQ(StatusCode::OK_200, res->status);
  13826. }
  13827. }
  13828. TEST(MultipartFormDataTest, DataProviderItems) {
  13829. std::random_device seed_gen;
  13830. std::mt19937 random(seed_gen());
  13831. std::string rand1;
  13832. rand1.resize(1000);
  13833. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13834. std::string rand2;
  13835. rand2.resize(3000);
  13836. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13838. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13839. const ContentReader &content_reader) {
  13840. ASSERT_FALSE(req.is_multipart_form_data());
  13841. std::string body;
  13842. content_reader([&](const char *data, size_t data_length) {
  13843. body.append(data, data_length);
  13844. return true;
  13845. });
  13846. EXPECT_EQ(body, "");
  13847. });
  13848. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13849. const ContentReader &content_reader) {
  13850. ASSERT_TRUE(req.is_multipart_form_data());
  13851. std::vector<FormData> items;
  13852. content_reader(
  13853. [&](const FormData &file) {
  13854. items.push_back(file);
  13855. return true;
  13856. },
  13857. [&](const char *data, size_t data_length) {
  13858. items.back().content.append(data, data_length);
  13859. return true;
  13860. });
  13861. ASSERT_TRUE(items.size() == 2);
  13862. EXPECT_EQ(std::string(items[0].name), "name1");
  13863. EXPECT_EQ(items[0].content, "Testing123");
  13864. EXPECT_EQ(items[0].filename, "filename1");
  13865. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13866. EXPECT_EQ(items[1].name, "name2");
  13867. EXPECT_EQ(items[1].content, "Testing456");
  13868. EXPECT_EQ(items[1].filename, "");
  13869. EXPECT_EQ(items[1].content_type, "");
  13870. });
  13871. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13872. const ContentReader &content_reader) {
  13873. ASSERT_TRUE(req.is_multipart_form_data());
  13874. std::vector<FormData> items;
  13875. content_reader(
  13876. [&](const FormData &file) {
  13877. items.push_back(file);
  13878. return true;
  13879. },
  13880. [&](const char *data, size_t data_length) {
  13881. items.back().content.append(data, data_length);
  13882. return true;
  13883. });
  13884. ASSERT_TRUE(items.size() == 2);
  13885. EXPECT_EQ(items[0].name, "name3");
  13886. EXPECT_EQ(items[0].content, rand1);
  13887. EXPECT_EQ(items[0].filename, "filename3");
  13888. EXPECT_EQ(items[0].content_type, "");
  13889. EXPECT_EQ(items[1].name, "name4");
  13890. EXPECT_EQ(items[1].content, rand2);
  13891. EXPECT_EQ(items[1].filename, "filename4");
  13892. EXPECT_EQ(items[1].content_type, "");
  13893. });
  13894. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13895. const ContentReader &content_reader) {
  13896. ASSERT_TRUE(req.is_multipart_form_data());
  13897. std::vector<FormData> items;
  13898. content_reader(
  13899. [&](const FormData &file) {
  13900. items.push_back(file);
  13901. return true;
  13902. },
  13903. [&](const char *data, size_t data_length) {
  13904. items.back().content.append(data, data_length);
  13905. return true;
  13906. });
  13907. ASSERT_TRUE(items.size() == 4);
  13908. EXPECT_EQ(std::string(items[0].name), "name1");
  13909. EXPECT_EQ(items[0].content, "Testing123");
  13910. EXPECT_EQ(items[0].filename, "filename1");
  13911. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13912. EXPECT_EQ(items[1].name, "name2");
  13913. EXPECT_EQ(items[1].content, "Testing456");
  13914. EXPECT_EQ(items[1].filename, "");
  13915. EXPECT_EQ(items[1].content_type, "");
  13916. EXPECT_EQ(items[2].name, "name3");
  13917. EXPECT_EQ(items[2].content, rand1);
  13918. EXPECT_EQ(items[2].filename, "filename3");
  13919. EXPECT_EQ(items[2].content_type, "");
  13920. EXPECT_EQ(items[3].name, "name4");
  13921. EXPECT_EQ(items[3].content, rand2);
  13922. EXPECT_EQ(items[3].filename, "filename4");
  13923. EXPECT_EQ(items[3].content_type, "");
  13924. });
  13925. auto port = svr.bind_to_any_port("localhost");
  13926. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13927. auto se = detail::scope_exit([&] {
  13928. svr.stop();
  13929. t.join();
  13930. ASSERT_FALSE(svr.is_running());
  13931. });
  13932. svr.wait_until_ready();
  13933. {
  13934. SSLClient cli("localhost", port);
  13935. cli.enable_server_certificate_verification(false);
  13936. UploadFormDataItems items{
  13937. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13938. {"name2", "Testing456", "", ""}, // not a file
  13939. };
  13940. {
  13941. auto res = cli.Post("/post-none", {}, {}, {});
  13942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13943. ASSERT_EQ(StatusCode::OK_200, res->status);
  13944. }
  13945. FormDataProviderItems providers;
  13946. {
  13947. auto res =
  13948. cli.Post("/post-items", {}, items, providers); // empty providers
  13949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13950. ASSERT_EQ(StatusCode::OK_200, res->status);
  13951. }
  13952. providers.push_back({"name3",
  13953. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13954. // test the offset is given correctly at each step
  13955. if (!offset)
  13956. sink.os.write(rand1.data(), 30);
  13957. else if (offset == 30)
  13958. sink.os.write(rand1.data() + 30, 300);
  13959. else if (offset == 330)
  13960. sink.os.write(rand1.data() + 330, 670);
  13961. else if (offset == rand1.size())
  13962. sink.done();
  13963. return true;
  13964. },
  13965. "filename3",
  13966. {}});
  13967. providers.push_back({"name4",
  13968. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13969. // test the offset is given correctly at each step
  13970. if (!offset)
  13971. sink.os.write(rand2.data(), 2000);
  13972. else if (offset == 2000)
  13973. sink.os.write(rand2.data() + 2000, 1);
  13974. else if (offset == 2001)
  13975. sink.os.write(rand2.data() + 2001, 999);
  13976. else if (offset == rand2.size())
  13977. sink.done();
  13978. return true;
  13979. },
  13980. "filename4",
  13981. {}});
  13982. {
  13983. auto res = cli.Post("/post-providers", {}, {}, providers);
  13984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13985. ASSERT_EQ(StatusCode::OK_200, res->status);
  13986. }
  13987. {
  13988. auto res = cli.Post("/post-both", {}, items, providers);
  13989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13990. ASSERT_EQ(StatusCode::OK_200, res->status);
  13991. }
  13992. }
  13993. }
  13994. TEST(MultipartFormDataTest, BadHeader) {
  13995. Server svr;
  13996. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13997. res.set_content("ok", "text/plain");
  13998. });
  13999. thread t = thread([&] { svr.listen(HOST, PORT); });
  14000. auto se = detail::scope_exit([&] {
  14001. svr.stop();
  14002. t.join();
  14003. ASSERT_FALSE(svr.is_running());
  14004. });
  14005. svr.wait_until_ready();
  14006. const std::string body =
  14007. "This is the preamble. It is to be ignored, though it\r\n"
  14008. "is a handy place for composition agents to include an\r\n"
  14009. "explanatory note to non-MIME conformant readers.\r\n"
  14010. "\r\n"
  14011. "\r\n"
  14012. "--simple boundary\r\n"
  14013. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14014. ": BAD...\r\n"
  14015. "\r\n"
  14016. "value1\r\n"
  14017. "--simple boundary\r\n"
  14018. "Content-Disposition: form-data; name=\"field2\"; "
  14019. "filename=\"example.txt\"\r\n"
  14020. "\r\n"
  14021. "value2\r\n"
  14022. "--simple boundary--\r\n"
  14023. "This is the epilogue. It is also to be ignored.\r\n";
  14024. std::string content_type =
  14025. R"(multipart/form-data; boundary="simple boundary")";
  14026. Client cli(HOST, PORT);
  14027. auto res = cli.Post("/post", body, content_type.c_str());
  14028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14029. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14030. }
  14031. TEST(MultipartFormDataTest, WithPreamble) {
  14032. Server svr;
  14033. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14034. res.set_content("ok", "text/plain");
  14035. });
  14036. thread t = thread([&] { svr.listen(HOST, PORT); });
  14037. auto se = detail::scope_exit([&] {
  14038. svr.stop();
  14039. t.join();
  14040. ASSERT_FALSE(svr.is_running());
  14041. });
  14042. svr.wait_until_ready();
  14043. const std::string body =
  14044. "This is the preamble. It is to be ignored, though it\r\n"
  14045. "is a handy place for composition agents to include an\r\n"
  14046. "explanatory note to non-MIME conformant readers.\r\n"
  14047. "\r\n"
  14048. "\r\n"
  14049. "--simple boundary\r\n"
  14050. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14051. "\r\n"
  14052. "value1\r\n"
  14053. "--simple boundary\r\n"
  14054. "Content-Disposition: form-data; name=\"field2\"; "
  14055. "filename=\"example.txt\"\r\n"
  14056. "\r\n"
  14057. "value2\r\n"
  14058. "--simple boundary--\r\n"
  14059. "This is the epilogue. It is also to be ignored.\r\n";
  14060. std::string content_type =
  14061. R"(multipart/form-data; boundary="simple boundary")";
  14062. Client cli(HOST, PORT);
  14063. auto res = cli.Post("/post", body, content_type.c_str());
  14064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14065. EXPECT_EQ(StatusCode::OK_200, res->status);
  14066. }
  14067. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14068. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14069. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14070. const ContentReader &content_reader) {
  14071. if (req.is_multipart_form_data()) {
  14072. std::vector<FormData> items;
  14073. content_reader(
  14074. [&](const FormData &file) {
  14075. items.push_back(file);
  14076. return true;
  14077. },
  14078. [&](const char *data, size_t data_length) {
  14079. items.back().content.append(data, data_length);
  14080. return true;
  14081. });
  14082. EXPECT_TRUE(std::string(items[0].name) == "document");
  14083. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14084. EXPECT_TRUE(items[0].filename == "2MB_data");
  14085. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14086. EXPECT_TRUE(items[1].name == "hello");
  14087. EXPECT_TRUE(items[1].content == "world");
  14088. EXPECT_TRUE(items[1].filename == "");
  14089. EXPECT_TRUE(items[1].content_type == "");
  14090. } else {
  14091. std::string body;
  14092. content_reader([&](const char *data, size_t data_length) {
  14093. body.append(data, data_length);
  14094. return true;
  14095. });
  14096. }
  14097. });
  14098. auto port = svr.bind_to_any_port("localhost");
  14099. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14100. auto se = detail::scope_exit([&] {
  14101. svr.stop();
  14102. t.join();
  14103. ASSERT_FALSE(svr.is_running());
  14104. });
  14105. svr.wait_until_ready();
  14106. {
  14107. std::string data(1024 * 1024 * 2, '.');
  14108. std::stringstream buffer;
  14109. buffer << data;
  14110. SSLClient cli("localhost", port);
  14111. cli.enable_server_certificate_verification(false);
  14112. UploadFormDataItems items{
  14113. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14114. {"hello", "world", "", ""},
  14115. };
  14116. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14118. ASSERT_EQ(StatusCode::OK_200, res->status);
  14119. }
  14120. }
  14121. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14122. std::string data(1024 * 1024 * 2, '&');
  14123. std::stringstream buffer;
  14124. buffer << data;
  14125. Client cli("https://localhost:8080");
  14126. UploadFormDataItems items{
  14127. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14128. {"hello", "world", "", ""},
  14129. };
  14130. for (const char &c : " \t\r\n") {
  14131. auto res =
  14132. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14133. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14134. ASSERT_FALSE(res);
  14135. }
  14136. }
  14137. TEST(MultipartFormDataTest, PutFormData) {
  14138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14139. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14140. const ContentReader &content_reader) {
  14141. if (req.is_multipart_form_data()) {
  14142. std::vector<FormData> items;
  14143. content_reader(
  14144. [&](const FormData &file) {
  14145. items.push_back(file);
  14146. return true;
  14147. },
  14148. [&](const char *data, size_t data_length) {
  14149. items.back().content.append(data, data_length);
  14150. return true;
  14151. });
  14152. EXPECT_TRUE(std::string(items[0].name) == "document");
  14153. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14154. EXPECT_TRUE(items[0].filename == "2MB_data");
  14155. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14156. EXPECT_TRUE(items[1].name == "hello");
  14157. EXPECT_TRUE(items[1].content == "world");
  14158. EXPECT_TRUE(items[1].filename == "");
  14159. EXPECT_TRUE(items[1].content_type == "");
  14160. } else {
  14161. std::string body;
  14162. content_reader([&](const char *data, size_t data_length) {
  14163. body.append(data, data_length);
  14164. return true;
  14165. });
  14166. }
  14167. });
  14168. auto port = svr.bind_to_any_port("localhost");
  14169. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14170. auto se = detail::scope_exit([&] {
  14171. svr.stop();
  14172. t.join();
  14173. ASSERT_FALSE(svr.is_running());
  14174. });
  14175. svr.wait_until_ready();
  14176. {
  14177. std::string data(1024 * 1024 * 2, '&');
  14178. std::stringstream buffer;
  14179. buffer << data;
  14180. SSLClient cli("localhost", port);
  14181. cli.enable_server_certificate_verification(false);
  14182. UploadFormDataItems items{
  14183. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14184. {"hello", "world", "", ""},
  14185. };
  14186. auto res = cli.Put("/put", items);
  14187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14188. ASSERT_EQ(StatusCode::OK_200, res->status);
  14189. }
  14190. }
  14191. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14193. svr.Put("/put_customboundary",
  14194. [&](const Request &req, const Response & /*res*/,
  14195. const ContentReader &content_reader) {
  14196. if (req.is_multipart_form_data()) {
  14197. std::vector<FormData> items;
  14198. content_reader(
  14199. [&](const FormData &file) {
  14200. items.push_back(file);
  14201. return true;
  14202. },
  14203. [&](const char *data, size_t data_length) {
  14204. items.back().content.append(data, data_length);
  14205. return true;
  14206. });
  14207. EXPECT_TRUE(std::string(items[0].name) == "document");
  14208. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14209. EXPECT_TRUE(items[0].filename == "2MB_data");
  14210. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14211. EXPECT_TRUE(items[1].name == "hello");
  14212. EXPECT_TRUE(items[1].content == "world");
  14213. EXPECT_TRUE(items[1].filename == "");
  14214. EXPECT_TRUE(items[1].content_type == "");
  14215. } else {
  14216. std::string body;
  14217. content_reader([&](const char *data, size_t data_length) {
  14218. body.append(data, data_length);
  14219. return true;
  14220. });
  14221. }
  14222. });
  14223. auto port = svr.bind_to_any_port("localhost");
  14224. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14225. auto se = detail::scope_exit([&] {
  14226. svr.stop();
  14227. t.join();
  14228. ASSERT_FALSE(svr.is_running());
  14229. });
  14230. svr.wait_until_ready();
  14231. {
  14232. std::string data(1024 * 1024 * 2, '&');
  14233. std::stringstream buffer;
  14234. buffer << data;
  14235. SSLClient cli("localhost", port);
  14236. cli.enable_server_certificate_verification(false);
  14237. UploadFormDataItems items{
  14238. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14239. {"hello", "world", "", ""},
  14240. };
  14241. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14243. ASSERT_EQ(StatusCode::OK_200, res->status);
  14244. }
  14245. }
  14246. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14247. std::string data(1024 * 1024 * 2, '&');
  14248. std::stringstream buffer;
  14249. buffer << data;
  14250. Client cli("https://localhost:8080");
  14251. cli.enable_server_certificate_verification(false);
  14252. UploadFormDataItems items{
  14253. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14254. {"hello", "world", "", ""},
  14255. };
  14256. for (const char &c : " \t\r\n") {
  14257. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14258. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14259. ASSERT_FALSE(res);
  14260. }
  14261. }
  14262. TEST(MultipartFormDataTest, AlternateFilename) {
  14263. auto handled = false;
  14264. Server svr;
  14265. svr.Post("/test", [&](const Request &req, Response &res) {
  14266. ASSERT_EQ(2u, req.form.files.size());
  14267. ASSERT_EQ(1u, req.form.fields.size());
  14268. // Test files
  14269. const auto &file1 = req.form.get_file("file1");
  14270. ASSERT_EQ("file1", file1.name);
  14271. ASSERT_EQ("A.txt", file1.filename);
  14272. ASSERT_EQ("text/plain", file1.content_type);
  14273. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14274. const auto &file2 = req.form.get_file("file2");
  14275. ASSERT_EQ("file2", file2.name);
  14276. ASSERT_EQ("a.html", file2.filename);
  14277. ASSERT_EQ("text/html", file2.content_type);
  14278. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14279. file2.content);
  14280. // Test text field
  14281. const auto &text = req.form.get_field("text");
  14282. ASSERT_EQ("text default", text);
  14283. res.set_content("ok", "text/plain");
  14284. handled = true;
  14285. });
  14286. thread t = thread([&] { svr.listen(HOST, PORT); });
  14287. auto se = detail::scope_exit([&] {
  14288. svr.stop();
  14289. t.join();
  14290. ASSERT_FALSE(svr.is_running());
  14291. ASSERT_TRUE(handled);
  14292. });
  14293. svr.wait_until_ready();
  14294. auto req = "POST /test HTTP/1.1\r\n"
  14295. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14296. "Content-Length: 399\r\n"
  14297. "\r\n"
  14298. "----------\r\n"
  14299. "Content-Disposition: form-data; name=\"text\"\r\n"
  14300. "\r\n"
  14301. "text default\r\n"
  14302. "----------\r\n"
  14303. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14304. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14305. "Content-Type: text/plain\r\n"
  14306. "\r\n"
  14307. "Content of a.txt.\r\n"
  14308. "\r\n"
  14309. "----------\r\n"
  14310. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14311. "\"a.html\"\r\n"
  14312. "Content-Type: text/html\r\n"
  14313. "\r\n"
  14314. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14315. "\r\n"
  14316. "------------\r\n";
  14317. ASSERT_TRUE(send_request(1, req));
  14318. }
  14319. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14320. auto handled = false;
  14321. Server svr;
  14322. svr.Post("/test", [&](const Request &req, Response &res) {
  14323. // Case-insensitive "utf-8''" prefix with a long value
  14324. const auto &file = req.form.get_file("file1");
  14325. ASSERT_EQ("file1", file.name);
  14326. // 8000 chars exercises both the Content-Disposition parser and the
  14327. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14328. // Prior to the fix, std::regex_match on this header would cause O(N)
  14329. // stack recursion in libstdc++, leading to SIGSEGV.
  14330. std::string expected_filename(8000, 'A');
  14331. ASSERT_EQ(expected_filename, file.filename);
  14332. res.set_content("ok", "text/plain");
  14333. handled = true;
  14334. });
  14335. thread t = thread([&] { svr.listen(HOST, PORT); });
  14336. auto se = detail::scope_exit([&] {
  14337. svr.stop();
  14338. t.join();
  14339. ASSERT_FALSE(svr.is_running());
  14340. ASSERT_TRUE(handled);
  14341. });
  14342. svr.wait_until_ready();
  14343. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14344. // Regression test for GHSA-qq6v-r583-3h69
  14345. std::string long_filename(8000, 'A');
  14346. std::string body = "----------\r\n"
  14347. "Content-Disposition: form-data; name=\"file1\"; "
  14348. "filename*=\"Utf-8''" +
  14349. long_filename +
  14350. "\"\r\n"
  14351. "\r\n"
  14352. "hello\r\n"
  14353. "------------\r\n";
  14354. auto req = "POST /test HTTP/1.1\r\n"
  14355. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14356. "Content-Length: " +
  14357. std::to_string(body.size()) + "\r\n\r\n" + body;
  14358. ASSERT_TRUE(send_request(1, req));
  14359. }
  14360. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14361. auto handled = false;
  14362. Server svr;
  14363. svr.Post("/test", [&](const Request &req, Response &) {
  14364. ASSERT_EQ(2u, req.form.fields.size());
  14365. const auto &text1 = req.form.get_field("text1");
  14366. ASSERT_EQ("text1", text1);
  14367. const auto &text2 = req.form.get_field("text2");
  14368. ASSERT_EQ("text2", text2);
  14369. handled = true;
  14370. });
  14371. thread t = thread([&] { svr.listen(HOST, PORT); });
  14372. auto se = detail::scope_exit([&] {
  14373. svr.stop();
  14374. t.join();
  14375. ASSERT_FALSE(svr.is_running());
  14376. ASSERT_TRUE(handled);
  14377. });
  14378. svr.wait_until_ready();
  14379. auto req = "POST /test HTTP/1.1\r\n"
  14380. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14381. "Content-Length: 146\r\n"
  14382. "\r\n----------\r\n"
  14383. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14384. "\r\n"
  14385. "text1"
  14386. "\r\n----------\r\n"
  14387. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14388. "\r\n"
  14389. "text2"
  14390. "\r\n------------";
  14391. std::string response;
  14392. ASSERT_TRUE(send_request(1, req, &response));
  14393. ASSERT_EQ("200", response.substr(9, 3));
  14394. }
  14395. TEST(MultipartFormDataTest, ContentLength) {
  14396. auto handled = false;
  14397. Server svr;
  14398. svr.Post("/test", [&](const Request &req, Response &) {
  14399. ASSERT_EQ(2u, req.form.fields.size());
  14400. const auto &text1 = req.form.get_field("text1");
  14401. ASSERT_EQ("text1", text1);
  14402. const auto &text2 = req.form.get_field("text2");
  14403. ASSERT_EQ("text2", text2);
  14404. handled = true;
  14405. });
  14406. thread t = thread([&] { svr.listen(HOST, PORT); });
  14407. auto se = detail::scope_exit([&] {
  14408. svr.stop();
  14409. t.join();
  14410. ASSERT_FALSE(svr.is_running());
  14411. ASSERT_TRUE(handled);
  14412. });
  14413. svr.wait_until_ready();
  14414. auto req = "POST /test HTTP/1.1\r\n"
  14415. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14416. "Content-Length: 167\r\n"
  14417. "\r\n----------\r\n"
  14418. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14419. "Content-Length: 5\r\n"
  14420. "\r\n"
  14421. "text1"
  14422. "\r\n----------\r\n"
  14423. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14424. "\r\n"
  14425. "text2"
  14426. "\r\n------------\r\n";
  14427. std::string response;
  14428. ASSERT_TRUE(send_request(1, req, &response));
  14429. ASSERT_EQ("200", response.substr(9, 3));
  14430. }
  14431. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14432. auto handled = false;
  14433. Server svr;
  14434. svr.Post("/test", [&](const Request &req, Response &) {
  14435. ASSERT_EQ(2u, req.form.fields.size());
  14436. const auto &text1 = req.form.get_field("text1");
  14437. ASSERT_EQ("text1", text1);
  14438. // TODO: Add header access for text fields if needed
  14439. const auto &text2 = req.form.get_field("text2");
  14440. ASSERT_EQ("text2", text2);
  14441. // TODO: Header access for text fields needs to be implemented
  14442. // auto &headers = it->second.headers;
  14443. // ASSERT_EQ(3U, headers.size());
  14444. // auto custom_header = headers.find("x-whatever");
  14445. // ASSERT_TRUE(custom_header != headers.end());
  14446. // ASSERT_NE("customvalue", custom_header->second);
  14447. // ASSERT_EQ("CustomValue", custom_header->second);
  14448. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14449. handled = true;
  14450. });
  14451. thread t = thread([&] { svr.listen(HOST, PORT); });
  14452. auto se = detail::scope_exit([&] {
  14453. svr.stop();
  14454. t.join();
  14455. ASSERT_FALSE(svr.is_running());
  14456. ASSERT_TRUE(handled);
  14457. });
  14458. svr.wait_until_ready();
  14459. auto req = "POST /test HTTP/1.1\r\n"
  14460. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14461. "Content-Length: 232\r\n"
  14462. "\r\n----------\r\n"
  14463. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14464. "Content-Length: 5\r\n"
  14465. "X-Test: 1\r\n"
  14466. "\r\n"
  14467. "text1"
  14468. "\r\n----------\r\n"
  14469. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14470. "Content-Type: text/plain\r\n"
  14471. "X-Whatever: CustomValue\r\n"
  14472. "\r\n"
  14473. "text2"
  14474. "\r\n------------\r\n"
  14475. "That should be disregarded. Not even read";
  14476. std::string response;
  14477. ASSERT_TRUE(send_request(1, req, &response));
  14478. ASSERT_EQ("200", response.substr(9, 3));
  14479. }
  14480. TEST(MultipartFormDataTest, LargeHeader) {
  14481. auto handled = false;
  14482. Server svr;
  14483. svr.Post("/test", [&](const Request &req, Response &) {
  14484. ASSERT_EQ(1u, req.form.fields.size());
  14485. const auto &text = req.form.get_field("name1");
  14486. ASSERT_EQ("text1", text);
  14487. handled = true;
  14488. });
  14489. thread t = thread([&] { svr.listen(HOST, PORT); });
  14490. auto se = detail::scope_exit([&] {
  14491. svr.stop();
  14492. t.join();
  14493. ASSERT_FALSE(svr.is_running());
  14494. ASSERT_TRUE(handled);
  14495. });
  14496. svr.wait_until_ready();
  14497. auto boundary = std::string("cpp-httplib-multipart-data");
  14498. std::string content = "--" + boundary +
  14499. "\r\n"
  14500. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14501. "\r\n"
  14502. "text1\r\n"
  14503. "--" +
  14504. boundary + "--\r\n";
  14505. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14506. "Content-Type: multipart/form-data;boundary=" +
  14507. boundary +
  14508. "\r\n"
  14509. "Content-Length: " +
  14510. std::to_string(content.size()) +
  14511. "\r\n"
  14512. "Dummy-Header: ";
  14513. std::string header_suffix = "\r\n"
  14514. "\r\n";
  14515. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14516. size_t header_dummy_size =
  14517. read_buff_size -
  14518. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14519. auto header_dummy = std::string(header_dummy_size, '@');
  14520. auto req = header_prefix + header_dummy + header_suffix + content;
  14521. std::string response;
  14522. ASSERT_TRUE(send_request(1, req, &response));
  14523. ASSERT_EQ("200", response.substr(9, 3));
  14524. }
  14525. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14526. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14527. // (not chunked Transfer-Encoding) after the streaming refactor.
  14528. auto handled = false;
  14529. Server svr;
  14530. svr.Post("/upload", [&](const Request &req, Response &res) {
  14531. auto cl_it = req.headers.find("Content-Length");
  14532. EXPECT_TRUE(cl_it != req.headers.end());
  14533. auto te_it = req.headers.find("Transfer-Encoding");
  14534. EXPECT_TRUE(te_it == req.headers.end());
  14535. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14536. res.set_content("ok", "text/plain");
  14537. handled = true;
  14538. });
  14539. auto port = svr.bind_to_any_port(HOST);
  14540. auto t = thread([&] { svr.listen_after_bind(); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. t.join();
  14544. ASSERT_FALSE(svr.is_running());
  14545. ASSERT_TRUE(handled);
  14546. });
  14547. svr.wait_until_ready();
  14548. UploadFormDataItems items = {
  14549. {"field1", "hello", "", "text/plain"},
  14550. {"file1", "world", "test.txt", "application/octet-stream"},
  14551. };
  14552. Client cli(HOST, port);
  14553. auto res = cli.Post("/upload", {}, items);
  14554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14555. EXPECT_EQ(StatusCode::OK_200, res->status);
  14556. }
  14557. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14558. // Verify that make_multipart_content_provider coalesces many small segments
  14559. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14560. constexpr size_t kItemCount = 1000;
  14561. UploadFormDataItems items;
  14562. items.reserve(kItemCount);
  14563. for (size_t i = 0; i < kItemCount; i++) {
  14564. items.push_back(
  14565. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14566. }
  14567. const std::string boundary = "----test-boundary";
  14568. auto content_length = detail::get_multipart_content_length(items, boundary);
  14569. auto provider = detail::make_multipart_content_provider(items, boundary);
  14570. // Drive the provider the same way write_content_with_progress does
  14571. size_t write_count = 0;
  14572. size_t total_bytes = 0;
  14573. DataSink sink;
  14574. size_t offset = 0;
  14575. sink.write = [&](const char *d, size_t l) -> bool {
  14576. (void)d;
  14577. write_count++;
  14578. total_bytes += l;
  14579. offset += l;
  14580. return true;
  14581. };
  14582. sink.is_writable = []() -> bool { return true; };
  14583. while (offset < content_length) {
  14584. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14585. }
  14586. EXPECT_EQ(content_length, total_bytes);
  14587. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14588. // With buffering into 64KB blocks, write_count should be much smaller.
  14589. auto segment_count = 3 * kItemCount + 1;
  14590. EXPECT_LT(write_count, segment_count / 10);
  14591. }
  14592. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14593. // Integration test: send many UploadFormDataItems and verify the server
  14594. // receives all of them correctly (#2410).
  14595. constexpr size_t kItemCount = 500;
  14596. auto handled = false;
  14597. Server svr;
  14598. svr.Post("/upload", [&](const Request &req, Response &res) {
  14599. EXPECT_EQ(kItemCount, req.form.fields.size());
  14600. for (size_t i = 0; i < kItemCount; i++) {
  14601. auto key = "field" + std::to_string(i);
  14602. auto val = "value" + std::to_string(i);
  14603. auto it = req.form.fields.find(key);
  14604. if (it != req.form.fields.end()) {
  14605. EXPECT_EQ(val, it->second.content);
  14606. } else {
  14607. ADD_FAILURE() << "Missing field: " << key;
  14608. }
  14609. }
  14610. res.set_content("ok", "text/plain");
  14611. handled = true;
  14612. });
  14613. auto port = svr.bind_to_any_port(HOST);
  14614. auto t = thread([&] { svr.listen_after_bind(); });
  14615. auto se = detail::scope_exit([&] {
  14616. svr.stop();
  14617. t.join();
  14618. ASSERT_FALSE(svr.is_running());
  14619. ASSERT_TRUE(handled);
  14620. });
  14621. svr.wait_until_ready();
  14622. UploadFormDataItems items;
  14623. items.reserve(kItemCount);
  14624. for (size_t i = 0; i < kItemCount; i++) {
  14625. items.push_back(
  14626. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14627. }
  14628. Client cli(HOST, port);
  14629. auto res = cli.Post("/upload", items);
  14630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14631. EXPECT_EQ(StatusCode::OK_200, res->status);
  14632. }
  14633. TEST(MultipartFormDataTest, MakeFileProvider) {
  14634. // Verify make_file_provider sends a file's contents correctly.
  14635. const std::string file_content(4096, 'Z');
  14636. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14637. {
  14638. std::ofstream ofs(tmp_path, std::ios::binary);
  14639. ofs.write(file_content.data(),
  14640. static_cast<std::streamsize>(file_content.size()));
  14641. }
  14642. auto handled = false;
  14643. Server svr;
  14644. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14645. const ContentReader &content_reader) {
  14646. ASSERT_TRUE(req.is_multipart_form_data());
  14647. std::vector<FormData> items;
  14648. content_reader(
  14649. [&](const FormData &file) {
  14650. items.push_back(file);
  14651. return true;
  14652. },
  14653. [&](const char *data, size_t data_length) {
  14654. items.back().content.append(data, data_length);
  14655. return true;
  14656. });
  14657. ASSERT_EQ(1u, items.size());
  14658. EXPECT_EQ("myfile", items[0].name);
  14659. EXPECT_EQ("data.bin", items[0].filename);
  14660. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14661. EXPECT_EQ(file_content, items[0].content);
  14662. handled = true;
  14663. });
  14664. auto port = svr.bind_to_any_port(HOST);
  14665. auto t = thread([&] { svr.listen_after_bind(); });
  14666. auto se = detail::scope_exit([&] {
  14667. svr.stop();
  14668. t.join();
  14669. ASSERT_FALSE(svr.is_running());
  14670. ASSERT_TRUE(handled);
  14671. std::remove(tmp_path.c_str());
  14672. });
  14673. svr.wait_until_ready();
  14674. FormDataProviderItems providers;
  14675. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14676. "application/octet-stream"));
  14677. Client cli(HOST, port);
  14678. auto res = cli.Post("/upload", {}, {}, providers);
  14679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14680. EXPECT_EQ(StatusCode::OK_200, res->status);
  14681. }
  14682. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14683. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14684. // (100) headers is rejected with a 400 Bad Request response.
  14685. Server svr;
  14686. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14687. res.set_content("ok", "text/plain");
  14688. });
  14689. thread t = thread([&] { svr.listen(HOST, PORT); });
  14690. auto se = detail::scope_exit([&] {
  14691. svr.stop();
  14692. t.join();
  14693. ASSERT_FALSE(svr.is_running());
  14694. });
  14695. svr.wait_until_ready();
  14696. // Build a multipart part with 101 custom headers (exceeding
  14697. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14698. std::stringstream body;
  14699. body << "--simpleboundary\r\n"
  14700. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14701. for (int i = 0; i < 101; i++) {
  14702. body << "X-Custom-Header-" << i << ": value\r\n";
  14703. }
  14704. body << "\r\n"
  14705. << "value1\r\n"
  14706. << "--simpleboundary--\r\n";
  14707. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14708. Client cli(HOST, PORT);
  14709. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14711. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14712. }
  14713. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14714. // A body that never contains the declared boundary must not be accumulated
  14715. // while the parser waits for it. Buffering it would also make every read
  14716. // rescan everything seen so far, which is quadratic in the body size.
  14717. Server svr;
  14718. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14719. res.set_content("ok", "text/plain");
  14720. });
  14721. auto port = svr.bind_to_any_port(HOST);
  14722. thread t = thread([&] { svr.listen_after_bind(); });
  14723. auto se = detail::scope_exit([&] {
  14724. svr.stop();
  14725. t.join();
  14726. ASSERT_FALSE(svr.is_running());
  14727. });
  14728. svr.wait_until_ready();
  14729. Client cli(HOST, port);
  14730. cli.set_read_timeout(60, 0);
  14731. cli.set_write_timeout(60, 0);
  14732. // '-' is the worst case: it matches the first character of the boundary, so
  14733. // every position has to be checked against it.
  14734. auto post_dashes = [&](size_t size) {
  14735. const std::string body(size, '-');
  14736. auto start = std::chrono::steady_clock::now();
  14737. auto res =
  14738. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14739. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14740. std::chrono::steady_clock::now() - start)
  14741. .count();
  14742. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14743. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14744. return ms;
  14745. };
  14746. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14747. // Windows.
  14748. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14749. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14750. // Comparing the two sizes rather than checking an absolute duration keeps
  14751. // this meaningful across build types and CI load, both of which move the
  14752. // absolute numbers by more than an order of magnitude. Four times the bytes
  14753. // costs about four times the time when parsing is linear, and about sixteen
  14754. // times when the body is buffered and rescanned.
  14755. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14756. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14757. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14758. << "ms, which suggests the body is being buffered and rescanned";
  14759. }
  14760. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14761. // A boundary can only be followed by CRLF or by "--", so anything else is
  14762. // malformed no matter what comes next. The parser must say so right away
  14763. // instead of buffering the rest of the declared body.
  14764. Server svr;
  14765. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14766. res.set_content("ok", "text/plain");
  14767. });
  14768. auto port = svr.bind_to_any_port(HOST);
  14769. thread t = thread([&] { svr.listen_after_bind(); });
  14770. auto se = detail::scope_exit([&] {
  14771. svr.stop();
  14772. t.join();
  14773. ASSERT_FALSE(svr.is_running());
  14774. });
  14775. svr.wait_until_ready();
  14776. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14777. // buffers instead of failing would still be waiting for the remaining bytes.
  14778. const std::string body = "--zzzz\r\n"
  14779. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14780. "\r\n"
  14781. "text1"
  14782. "\r\n--zzzzXX";
  14783. const std::string req = "POST /post HTTP/1.1\r\n"
  14784. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14785. "Content-Length: 1048576\r\n"
  14786. "\r\n" +
  14787. body;
  14788. std::string response;
  14789. ASSERT_TRUE(send_request(3, req, &response, port));
  14790. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14791. EXPECT_EQ("400", response.substr(9, 3));
  14792. }
  14793. // Posts a multipart body split into two writes, so that the server sees the
  14794. // split at whatever offset the caller chose, and expects the single "text1"
  14795. // field to come through.
  14796. static void expect_split_multipart_ok(const std::string &body1,
  14797. const std::string &body2) {
  14798. auto handled = false;
  14799. Server svr;
  14800. svr.Post("/post", [&](const Request &req, Response &) {
  14801. EXPECT_EQ(1u, req.form.fields.size());
  14802. EXPECT_EQ("text1", req.form.get_field("text1"));
  14803. handled = true;
  14804. });
  14805. auto port = svr.bind_to_any_port(HOST);
  14806. thread t = thread([&] { svr.listen_after_bind(); });
  14807. auto se = detail::scope_exit([&] {
  14808. svr.stop();
  14809. t.join();
  14810. ASSERT_FALSE(svr.is_running());
  14811. ASSERT_TRUE(handled);
  14812. });
  14813. svr.wait_until_ready();
  14814. // "Connection: close" makes the server close once it has answered, so the
  14815. // response drain ends immediately instead of idling until the read timeout.
  14816. const std::string head =
  14817. "POST /post HTTP/1.1\r\n"
  14818. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14819. "Connection: close\r\n"
  14820. "Content-Length: " +
  14821. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14822. std::string response;
  14823. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14824. ASSERT_GE(response.size(), 12u) << "no response";
  14825. EXPECT_EQ("200", response.substr(9, 3));
  14826. }
  14827. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14828. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14829. // ignored, including when it does not arrive in the same read as the
  14830. // close-delimiter itself.
  14831. expect_split_multipart_ok("--zzzz\r\n"
  14832. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14833. "\r\n"
  14834. "text1"
  14835. "\r\n--zzzz--",
  14836. "\r\nthis epilogue must be ignored\r\n");
  14837. }
  14838. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14839. // The initial boundary may be preceded by a preamble of any length and may
  14840. // straddle a read boundary. Discarding data while waiting for it must not
  14841. // throw away a partial boundary sitting at the end of the buffer.
  14842. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14843. "zz\r\n"
  14844. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14845. "\r\n"
  14846. "text1"
  14847. "\r\n--zzzz--\r\n");
  14848. }
  14849. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14850. // The received boundary was only checked for being non-empty, so it could be
  14851. // as long as a header is allowed to be. The parser scans the body for
  14852. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14853. // costs a nearly full comparison at nearly every position, making the
  14854. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14855. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14856. Server svr;
  14857. svr.Post("/post", [](const Request &req, Response &res) {
  14858. EXPECT_EQ(1u, req.form.fields.size());
  14859. EXPECT_EQ("text1", req.form.get_field("text1"));
  14860. res.set_content("ok", "text/plain");
  14861. });
  14862. auto port = svr.bind_to_any_port(HOST);
  14863. thread t = thread([&] { svr.listen_after_bind(); });
  14864. auto se = detail::scope_exit([&] {
  14865. svr.stop();
  14866. t.join();
  14867. ASSERT_FALSE(svr.is_running());
  14868. });
  14869. svr.wait_until_ready();
  14870. Client cli(HOST, port);
  14871. auto post_with_boundary_of_length = [&](size_t len) {
  14872. const std::string boundary(len, 'a');
  14873. const std::string body =
  14874. "--" + boundary +
  14875. "\r\n"
  14876. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14877. "\r\n"
  14878. "text1"
  14879. "\r\n--" +
  14880. boundary + "--\r\n";
  14881. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14882. };
  14883. auto res = post_with_boundary_of_length(70);
  14884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14885. EXPECT_EQ(StatusCode::OK_200, res->status);
  14886. res = post_with_boundary_of_length(71);
  14887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14888. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14889. }
  14890. TEST(MakeFileBodyTest, Basic) {
  14891. const std::string file_content(4096, 'Z');
  14892. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14893. {
  14894. std::ofstream ofs(tmp_path, std::ios::binary);
  14895. ofs.write(file_content.data(),
  14896. static_cast<std::streamsize>(file_content.size()));
  14897. }
  14898. auto handled = false;
  14899. Server svr;
  14900. svr.Post("/upload", [&](const Request &req, Response &res) {
  14901. EXPECT_EQ(file_content, req.body);
  14902. handled = true;
  14903. res.status = StatusCode::OK_200;
  14904. });
  14905. auto port = svr.bind_to_any_port(HOST);
  14906. auto t = thread([&] { svr.listen_after_bind(); });
  14907. auto se = detail::scope_exit([&] {
  14908. svr.stop();
  14909. t.join();
  14910. ASSERT_FALSE(svr.is_running());
  14911. ASSERT_TRUE(handled);
  14912. std::remove(tmp_path.c_str());
  14913. });
  14914. svr.wait_until_ready();
  14915. auto fb = make_file_body(tmp_path);
  14916. ASSERT_GT(fb.first, 0u);
  14917. Client cli(HOST, port);
  14918. auto res =
  14919. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14921. EXPECT_EQ(StatusCode::OK_200, res->status);
  14922. }
  14923. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14924. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14925. {
  14926. std::ofstream ofs(path, std::ios::binary);
  14927. const std::string content(100, 'A');
  14928. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14929. }
  14930. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14931. auto body = make_file_body(path);
  14932. ASSERT_EQ(100u, body.first);
  14933. ASSERT_TRUE(static_cast<bool>(body.second));
  14934. // Rewritten shorter after its length was measured - and, on a server, after
  14935. // that length has already gone out as Content-Length.
  14936. {
  14937. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14938. const std::string content(10, 'A');
  14939. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14940. }
  14941. std::string written;
  14942. DataSink sink;
  14943. sink.write = [&](const char *d, size_t l) {
  14944. written.append(d, l);
  14945. return true;
  14946. };
  14947. // The provider has to report failure. write_content_with_progress() advances
  14948. // its offset only by what was written, so a provider that returns true
  14949. // without completing the length it promised is called again straight away,
  14950. // and again.
  14951. EXPECT_FALSE(body.second(0, body.first, sink));
  14952. EXPECT_EQ(std::string(10, 'A'), written);
  14953. }
  14954. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14955. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14956. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14957. {
  14958. std::ofstream ofs(path, std::ios::binary);
  14959. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14960. }
  14961. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14962. auto body = make_file_body(path);
  14963. ASSERT_EQ(content.size(), body.first);
  14964. ASSERT_TRUE(static_cast<bool>(body.second));
  14965. std::string written;
  14966. DataSink sink;
  14967. sink.write = [&](const char *d, size_t l) {
  14968. written.append(d, l);
  14969. return true;
  14970. };
  14971. EXPECT_TRUE(body.second(0, body.first, sink));
  14972. EXPECT_EQ(content, written);
  14973. }
  14974. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14975. static constexpr unsigned int number_of_tasks{1000000};
  14976. std::atomic_uint count{0};
  14977. std::unique_ptr<TaskQueue> task_queue{
  14978. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14979. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14980. auto queued = task_queue->enqueue(
  14981. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14982. EXPECT_TRUE(queued);
  14983. }
  14984. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14985. task_queue->shutdown();
  14986. #else
  14987. EXPECT_NO_THROW(task_queue->shutdown());
  14988. #endif
  14989. EXPECT_EQ(number_of_tasks, count.load());
  14990. }
  14991. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14992. static constexpr unsigned int number_of_tasks{1000000};
  14993. static constexpr unsigned int qlimit{2};
  14994. unsigned int queued_count{0};
  14995. std::atomic_uint count{0};
  14996. std::unique_ptr<TaskQueue> task_queue{
  14997. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14998. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14999. if (task_queue->enqueue(
  15000. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15001. queued_count++;
  15002. }
  15003. }
  15004. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15005. task_queue->shutdown();
  15006. #else
  15007. EXPECT_NO_THROW(task_queue->shutdown());
  15008. #endif
  15009. EXPECT_EQ(queued_count, count.load());
  15010. EXPECT_TRUE(queued_count <= number_of_tasks);
  15011. EXPECT_TRUE(queued_count >= qlimit);
  15012. }
  15013. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15014. // Use a short idle timeout so a dynamic thread spawns, times out and
  15015. // exits during the test, and the pool keeps working afterwards.
  15016. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15017. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15018. /*idle_timeout_sec=*/1}};
  15019. std::atomic_uint count{0};
  15020. std::condition_variable cv;
  15021. std::mutex mtx;
  15022. bool release = false;
  15023. // Block the base thread so the second task spawns a dynamic thread.
  15024. EXPECT_TRUE(task_queue->enqueue([&] {
  15025. std::unique_lock<std::mutex> lock(mtx);
  15026. while (!release) {
  15027. cv.wait(lock);
  15028. }
  15029. count++;
  15030. }));
  15031. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15032. // Let the dynamic thread finish its task and exceed the idle timeout.
  15033. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15034. {
  15035. std::unique_lock<std::mutex> lock(mtx);
  15036. release = true;
  15037. }
  15038. cv.notify_all();
  15039. // The pool must still accept and run tasks after the dynamic thread exited.
  15040. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15041. task_queue->shutdown();
  15042. EXPECT_EQ(3u, count.load());
  15043. }
  15044. TEST(TaskQueueTest, MaxQueuedRequests) {
  15045. static constexpr unsigned int qlimit{3};
  15046. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15047. std::condition_variable sem_cv;
  15048. std::mutex sem_mtx;
  15049. int credits = 0;
  15050. bool queued;
  15051. /* Fill up the queue with tasks that will block until we give them credits to
  15052. * complete. */
  15053. for (unsigned int n = 0; n <= qlimit;) {
  15054. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15055. std::unique_lock<std::mutex> lock(sem_mtx);
  15056. while (credits <= 0) {
  15057. sem_cv.wait(lock);
  15058. }
  15059. /* Consume the credit and signal the test code if they are all gone. */
  15060. if (--credits == 0) { sem_cv.notify_one(); }
  15061. });
  15062. if (n < qlimit) {
  15063. /* The first qlimit enqueues must succeed. */
  15064. EXPECT_TRUE(queued);
  15065. } else {
  15066. /* The last one will succeed only when the worker thread
  15067. * starts and dequeues the first blocking task. Although
  15068. * not necessary for the correctness of this test, we sleep for
  15069. * a short while to avoid busy waiting. */
  15070. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15071. }
  15072. if (queued) { n++; }
  15073. }
  15074. /* Further enqueues must fail since the queue is full. */
  15075. for (auto i = 0; i < 4; i++) {
  15076. queued = task_queue->enqueue([] {});
  15077. EXPECT_FALSE(queued);
  15078. }
  15079. /* Give the credits to allow the previous tasks to complete. */
  15080. {
  15081. std::unique_lock<std::mutex> lock(sem_mtx);
  15082. credits += qlimit + 1;
  15083. }
  15084. sem_cv.notify_all();
  15085. /* Wait for all the credits to be consumed. */
  15086. {
  15087. std::unique_lock<std::mutex> lock(sem_mtx);
  15088. while (credits > 0) {
  15089. sem_cv.wait(lock);
  15090. }
  15091. }
  15092. /* Check that we are able again to enqueue at least qlimit tasks. */
  15093. for (unsigned int i = 0; i < qlimit; i++) {
  15094. queued = task_queue->enqueue([] {});
  15095. EXPECT_TRUE(queued);
  15096. }
  15097. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15098. task_queue->shutdown();
  15099. #else
  15100. EXPECT_NO_THROW(task_queue->shutdown());
  15101. #endif
  15102. }
  15103. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15104. Server svr;
  15105. std::string method;
  15106. std::string body;
  15107. auto has_content_length = false;
  15108. auto has_transfer_encoding = false;
  15109. std::atomic<int> bad_requests{0};
  15110. // Leftover body bytes get parsed as a malformed request and answered with
  15111. // 400
  15112. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15113. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15114. });
  15115. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15116. res.set_redirect("/down", StatusCode::SeeOther_303);
  15117. });
  15118. svr.Get("/down", [&](const Request &req, Response &res) {
  15119. method = req.method;
  15120. body = req.body;
  15121. has_content_length = req.has_header("Content-Length");
  15122. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15123. res.set_content("ok", "text/plain");
  15124. });
  15125. auto port = svr.bind_to_any_port(HOST);
  15126. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15127. auto se = detail::scope_exit([&] {
  15128. svr.stop();
  15129. thread.join();
  15130. ASSERT_FALSE(svr.is_running());
  15131. });
  15132. svr.wait_until_ready();
  15133. const std::string payload = "SECRET-BODY";
  15134. auto check = [&](Client &cli, const Result &res) {
  15135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15136. EXPECT_EQ(StatusCode::OK_200, res->status);
  15137. EXPECT_EQ("ok", res->body);
  15138. EXPECT_EQ("GET", method);
  15139. EXPECT_TRUE(body.empty());
  15140. EXPECT_FALSE(has_content_length);
  15141. EXPECT_FALSE(has_transfer_encoding);
  15142. // Nothing of the original body may be left on the connection
  15143. auto res2 = cli.Get("/down");
  15144. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15145. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15146. EXPECT_EQ("ok", res2->body);
  15147. EXPECT_EQ(0, bad_requests);
  15148. };
  15149. // With content length
  15150. {
  15151. Client cli(HOST, port);
  15152. cli.set_keep_alive(true);
  15153. cli.set_follow_location(true);
  15154. auto res = cli.Post(
  15155. "/up", payload.size(),
  15156. [&](size_t offset, size_t length, DataSink &sink) {
  15157. return sink.write(payload.data() + offset, length);
  15158. },
  15159. "text/plain");
  15160. check(cli, res);
  15161. }
  15162. // Without content length (chunked)
  15163. {
  15164. Client cli(HOST, port);
  15165. cli.set_keep_alive(true);
  15166. cli.set_follow_location(true);
  15167. auto res = cli.Post(
  15168. "/up",
  15169. [&](size_t /*offset*/, DataSink &sink) {
  15170. sink.write(payload.data(), payload.size());
  15171. sink.done();
  15172. return true;
  15173. },
  15174. "text/plain");
  15175. check(cli, res);
  15176. }
  15177. }
  15178. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15179. Server svr;
  15180. std::string target;
  15181. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15182. // Echo the still-encoded name back in the Location
  15183. const std::string prefix = "/start/";
  15184. res.status = StatusCode::Found_302;
  15185. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15186. });
  15187. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15188. target = req.target;
  15189. res.set_content("ok", "text/plain");
  15190. });
  15191. auto port = svr.bind_to_any_port(HOST);
  15192. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15193. auto se = detail::scope_exit([&] {
  15194. svr.stop();
  15195. thread.join();
  15196. ASSERT_FALSE(svr.is_running());
  15197. });
  15198. svr.wait_until_ready();
  15199. // Decoding the Location path would turn the first four into a path
  15200. // separator, a query delimiter, a fragment delimiter and a different
  15201. // percent-encoded octet. The rest must keep reaching the server as they are.
  15202. const std::vector<std::string> names = {
  15203. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15204. };
  15205. for (auto path_encode : {true, false}) {
  15206. Client cli(HOST, port);
  15207. cli.set_follow_location(true);
  15208. cli.set_path_encode(path_encode);
  15209. for (const auto &name : names) {
  15210. target.clear();
  15211. auto res = cli.Get("/start/" + name);
  15212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15213. EXPECT_EQ(StatusCode::OK_200, res->status);
  15214. EXPECT_EQ("/dest/" + name, target);
  15215. }
  15216. }
  15217. }
  15218. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15219. Server svr;
  15220. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15221. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15222. });
  15223. svr.Get("/hello", [](const Request &req, Response &res) {
  15224. res.set_content(req.get_param_value("key"), "text/plain");
  15225. });
  15226. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15227. auto se = detail::scope_exit([&] {
  15228. svr.stop();
  15229. thread.join();
  15230. ASSERT_FALSE(svr.is_running());
  15231. });
  15232. svr.wait_until_ready();
  15233. {
  15234. Client cli(HOST, PORT);
  15235. cli.set_follow_location(true);
  15236. auto res = cli.Get("/");
  15237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. EXPECT_EQ("val&key2=val2", res->body);
  15240. }
  15241. }
  15242. #endif
  15243. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15244. Server svr;
  15245. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15246. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15247. });
  15248. svr.Get("/hello", [](const Request &req, Response &res) {
  15249. res.set_content(req.get_param_value("key"), "text/plain");
  15250. });
  15251. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15252. auto se = detail::scope_exit([&] {
  15253. svr.stop();
  15254. thread.join();
  15255. ASSERT_FALSE(svr.is_running());
  15256. });
  15257. svr.wait_until_ready();
  15258. {
  15259. Client cli(HOST, PORT);
  15260. cli.set_follow_location(true);
  15261. auto res = cli.Get("/");
  15262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15263. EXPECT_EQ(StatusCode::OK_200, res->status);
  15264. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15265. }
  15266. }
  15267. TEST(RedirectTest, RedirectWithPlusInPath) {
  15268. Server svr;
  15269. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15270. res.set_redirect("/a+b");
  15271. });
  15272. // Route pattern uses regex; escape + as \\+
  15273. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15274. res.set_content(req.path, "text/plain");
  15275. });
  15276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. thread.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. });
  15282. svr.wait_until_ready();
  15283. {
  15284. Client cli(HOST, PORT);
  15285. cli.set_follow_location(true);
  15286. auto res = cli.Get("/");
  15287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15288. EXPECT_EQ(StatusCode::OK_200, res->status);
  15289. EXPECT_EQ("/a+b", res->body);
  15290. }
  15291. }
  15292. TEST(RedirectTest, ResolveRelativeLocation) {
  15293. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15294. const std::vector<std::pair<std::string, std::string>> cases = {
  15295. {"g", "/b/c/g"},
  15296. {"./g", "/b/c/g"},
  15297. {"g/", "/b/c/g/"},
  15298. {"?y", "/b/c/d;p?y"},
  15299. {"g?y", "/b/c/g?y"},
  15300. {"#s", "/b/c/d;p?q#s"},
  15301. {"g#s", "/b/c/g#s"},
  15302. {"g?y#s", "/b/c/g?y#s"},
  15303. {";x", "/b/c/;x"},
  15304. {"g;x", "/b/c/g;x"},
  15305. {".", "/b/c/"},
  15306. {"./", "/b/c/"},
  15307. {"..", "/b/"},
  15308. {"../", "/b/"},
  15309. {"../g", "/b/g"},
  15310. {"../..", "/"},
  15311. {"../../", "/"},
  15312. {"../../g", "/g"},
  15313. {"../../../g", "/g"},
  15314. {"g.", "/b/c/g."},
  15315. {".g", "/b/c/.g"},
  15316. {"g..", "/b/c/g.."},
  15317. {"..g", "/b/c/..g"},
  15318. {"./../g", "/b/g"},
  15319. {"./g/.", "/b/c/g/"},
  15320. {"g/./h", "/b/c/g/h"},
  15321. {"g/../h", "/b/c/h"},
  15322. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15323. {"g;x=1/../y", "/b/c/y"},
  15324. {"g?y/./x", "/b/c/g?y/./x"},
  15325. {"g#s/../x", "/b/c/g#s/../x"},
  15326. // Not relative-path references, so left for parse_url.
  15327. {"/g", "/g"},
  15328. {"//g", "//g"},
  15329. {"http://g/x", "http://g/x"},
  15330. {"g:h", "g:h"},
  15331. };
  15332. for (const auto &c : cases) {
  15333. EXPECT_EQ(c.second,
  15334. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15335. << c.first;
  15336. }
  15337. }
  15338. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15339. Server svr;
  15340. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15341. res.set_redirect(req.get_param_value("to"));
  15342. });
  15343. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15344. res.set_content(req.target, "text/plain");
  15345. });
  15346. svr.Get("/other", [](const Request &req, Response &res) {
  15347. res.set_content(req.target, "text/plain");
  15348. });
  15349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15350. auto se = detail::scope_exit([&] {
  15351. svr.stop();
  15352. thread.join();
  15353. ASSERT_FALSE(svr.is_running());
  15354. });
  15355. svr.wait_until_ready();
  15356. const std::vector<std::pair<std::string, std::string>> cases = {
  15357. {"next", "/dir/next"},
  15358. {"./next?x=1", "/dir/next?x=1"},
  15359. {"../other", "/other"},
  15360. };
  15361. for (const auto &c : cases) {
  15362. Client cli(HOST, PORT);
  15363. cli.set_follow_location(true);
  15364. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15365. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15366. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15367. EXPECT_EQ(c.second, res->body) << c.first;
  15368. }
  15369. }
  15370. #ifdef CPPHTTPLIB_SSL_ENABLED
  15371. TEST(RedirectTest, Issue2185_Online) {
  15372. SSLClient client("github.com");
  15373. client.set_follow_location(true);
  15374. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15375. "Coollab-Windows.zip");
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. EXPECT_EQ(StatusCode::OK_200, res->status);
  15378. EXPECT_EQ(9920427U, res->body.size());
  15379. }
  15380. #endif
  15381. TEST(VulnerabilityTest, CRLFInjection) {
  15382. Server svr;
  15383. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15384. res.set_content("Hello 1", "text/plain");
  15385. });
  15386. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15387. res.set_content("Hello 2", "text/plain");
  15388. });
  15389. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15390. res.set_content("Hello 3", "text/plain");
  15391. });
  15392. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15393. res.set_content("Hello 4", "text/plain");
  15394. });
  15395. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15396. for (const auto &x : req.headers) {
  15397. auto key = x.first;
  15398. EXPECT_STRNE("evil", key.c_str());
  15399. }
  15400. });
  15401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15402. auto se = detail::scope_exit([&] {
  15403. svr.stop();
  15404. thread.join();
  15405. ASSERT_FALSE(svr.is_running());
  15406. });
  15407. svr.wait_until_ready();
  15408. {
  15409. Client cli(HOST, PORT);
  15410. cli.Post("/test1", "A=B",
  15411. "application/x-www-form-urlencoded\r\nevil: hello1");
  15412. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15413. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15414. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15415. }
  15416. }
  15417. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15418. auto server_thread = std::thread([] {
  15419. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15420. default_socket_options(srv);
  15421. sockaddr_in addr{};
  15422. addr.sin_family = AF_INET;
  15423. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15424. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15425. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15426. ::listen(srv, 1);
  15427. sockaddr_in cli_addr{};
  15428. socklen_t cli_len = sizeof(cli_addr);
  15429. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15430. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15431. std::string buf_all;
  15432. char buf[2048];
  15433. ssize_t n;
  15434. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15435. buf_all.append(buf, static_cast<size_t>(n));
  15436. size_t pos;
  15437. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15438. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15439. auto e = request_block.find("\r\n");
  15440. if (e != std::string::npos) {
  15441. auto request_line = request_block.substr(0, e);
  15442. std::string msg =
  15443. "CRLF injection detected in request line: '" + request_line + "'";
  15444. EXPECT_FALSE(true) << msg;
  15445. }
  15446. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15447. ::send(cli,
  15448. #ifdef _WIN32
  15449. static_cast<const char *>(resp.c_str()),
  15450. static_cast<int>(resp.size()),
  15451. #else
  15452. resp.c_str(), resp.size(),
  15453. #endif
  15454. 0);
  15455. buf_all.erase(0, pos + 4);
  15456. }
  15457. }
  15458. detail::close_socket(cli);
  15459. detail::close_socket(srv);
  15460. });
  15461. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15462. auto cli = Client("127.0.0.1", PORT + 1);
  15463. auto headers = Headers{
  15464. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15465. {"Connection", "keep-alive"}};
  15466. auto res = cli.Get("/hi", headers);
  15467. EXPECT_FALSE(res);
  15468. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15469. server_thread.join();
  15470. }
  15471. // A request rejected before any byte reaches the socket must fail right away
  15472. // instead of waiting for a response the server will never send.
  15473. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15474. // The kernel completes the TCP handshake from the listen backlog, so the
  15475. // client connects, but nothing ever reads, responds or closes.
  15476. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15477. default_socket_options(srv);
  15478. sockaddr_in addr{};
  15479. addr.sin_family = AF_INET;
  15480. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15481. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15482. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15483. ASSERT_EQ(0, ::listen(srv, 8));
  15484. auto cli = Client("127.0.0.1", PORT + 1);
  15485. cli.set_read_timeout(10, 0);
  15486. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15487. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15488. std::chrono::steady_clock::now() - start)
  15489. .count();
  15490. };
  15491. {
  15492. Request req;
  15493. req.method = "GE T";
  15494. req.path = "/";
  15495. auto start = std::chrono::steady_clock::now();
  15496. auto res = cli.send(req);
  15497. EXPECT_FALSE(res);
  15498. EXPECT_EQ(Error::Write, res.error());
  15499. EXPECT_LT(elapsed_ms(start), 1000);
  15500. }
  15501. {
  15502. auto start = std::chrono::steady_clock::now();
  15503. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15504. EXPECT_FALSE(res);
  15505. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15506. EXPECT_LT(elapsed_ms(start), 1000);
  15507. }
  15508. EXPECT_FALSE(cli.is_socket_open());
  15509. detail::close_socket(srv);
  15510. }
  15511. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15512. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15513. default_socket_options(srv);
  15514. sockaddr_in addr{};
  15515. addr.sin_family = AF_INET;
  15516. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15517. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15518. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15519. ASSERT_EQ(0, ::listen(srv, 1));
  15520. std::string received;
  15521. auto server_thread = std::thread([&] {
  15522. auto sock = ::accept(srv, nullptr, nullptr);
  15523. if (sock == INVALID_SOCKET) { return; }
  15524. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15525. char buf[2048];
  15526. ssize_t n;
  15527. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15528. received.append(buf, static_cast<size_t>(n));
  15529. }
  15530. detail::close_socket(sock);
  15531. });
  15532. {
  15533. auto cli = Client("127.0.0.1", PORT + 1);
  15534. // "Z" sorts after the default headers, so writing straight to the socket
  15535. // would have sent the request line and those headers before the rejection.
  15536. auto handle =
  15537. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15538. EXPECT_FALSE(handle.is_valid());
  15539. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15540. }
  15541. server_thread.join();
  15542. detail::close_socket(srv);
  15543. EXPECT_TRUE(received.empty()) << received;
  15544. }
  15545. TEST(PathParamsTest, StaticMatch) {
  15546. const auto pattern = "/users/all";
  15547. detail::PathParamsMatcher matcher(pattern);
  15548. Request request;
  15549. request.path = "/users/all";
  15550. ASSERT_TRUE(matcher.match(request));
  15551. std::unordered_map<std::string, std::string> expected_params = {};
  15552. EXPECT_EQ(request.path_params, expected_params);
  15553. }
  15554. TEST(PathParamsTest, StaticMismatch) {
  15555. const auto pattern = "/users/all";
  15556. detail::PathParamsMatcher matcher(pattern);
  15557. Request request;
  15558. request.path = "/users/1";
  15559. ASSERT_FALSE(matcher.match(request));
  15560. }
  15561. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15562. const auto pattern = "/users/:id/subscriptions";
  15563. detail::PathParamsMatcher matcher(pattern);
  15564. Request request;
  15565. request.path = "/users/42/subscriptions";
  15566. ASSERT_TRUE(matcher.match(request));
  15567. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15568. EXPECT_EQ(request.path_params, expected_params);
  15569. }
  15570. TEST(PathParamsTest, SingleParamInTheEnd) {
  15571. const auto pattern = "/users/:id";
  15572. detail::PathParamsMatcher matcher(pattern);
  15573. Request request;
  15574. request.path = "/users/24";
  15575. ASSERT_TRUE(matcher.match(request));
  15576. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15577. EXPECT_EQ(request.path_params, expected_params);
  15578. }
  15579. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15580. const auto pattern = "/users/:id/";
  15581. detail::PathParamsMatcher matcher(pattern);
  15582. Request request;
  15583. request.path = "/users/42/";
  15584. ASSERT_TRUE(matcher.match(request));
  15585. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15586. EXPECT_EQ(request.path_params, expected_params);
  15587. }
  15588. TEST(PathParamsTest, EmptyParam) {
  15589. const auto pattern = "/users/:id/";
  15590. detail::PathParamsMatcher matcher(pattern);
  15591. Request request;
  15592. request.path = "/users//";
  15593. ASSERT_TRUE(matcher.match(request));
  15594. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15595. EXPECT_EQ(request.path_params, expected_params);
  15596. }
  15597. TEST(PathParamsTest, FragmentMismatch) {
  15598. const auto pattern = "/users/:id/";
  15599. detail::PathParamsMatcher matcher(pattern);
  15600. Request request;
  15601. request.path = "/admins/24/";
  15602. ASSERT_FALSE(matcher.match(request));
  15603. }
  15604. TEST(PathParamsTest, ExtraFragments) {
  15605. const auto pattern = "/users/:id";
  15606. detail::PathParamsMatcher matcher(pattern);
  15607. Request request;
  15608. request.path = "/users/42/subscriptions";
  15609. ASSERT_FALSE(matcher.match(request));
  15610. }
  15611. TEST(PathParamsTest, MissingTrailingParam) {
  15612. const auto pattern = "/users/:id";
  15613. detail::PathParamsMatcher matcher(pattern);
  15614. Request request;
  15615. request.path = "/users";
  15616. ASSERT_FALSE(matcher.match(request));
  15617. }
  15618. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15619. const auto pattern = "/users/:id/subscriptions";
  15620. detail::PathParamsMatcher matcher(pattern);
  15621. Request request;
  15622. request.path = "/users/subscriptions";
  15623. ASSERT_FALSE(matcher.match(request));
  15624. }
  15625. TEST(PathParamsTest, MultipleParams) {
  15626. const auto pattern = "/users/:userid/subscriptions/:subid";
  15627. detail::PathParamsMatcher matcher(pattern);
  15628. Request request;
  15629. request.path = "/users/42/subscriptions/2";
  15630. ASSERT_TRUE(matcher.match(request));
  15631. std::unordered_map<std::string, std::string> expected_params = {
  15632. {"userid", "42"}, {"subid", "2"}};
  15633. EXPECT_EQ(request.path_params, expected_params);
  15634. }
  15635. TEST(PathParamsTest, SequenceOfParams) {
  15636. const auto pattern = "/values/:x/:y/:z";
  15637. detail::PathParamsMatcher matcher(pattern);
  15638. Request request;
  15639. request.path = "/values/1/2/3";
  15640. ASSERT_TRUE(matcher.match(request));
  15641. std::unordered_map<std::string, std::string> expected_params = {
  15642. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15643. EXPECT_EQ(request.path_params, expected_params);
  15644. }
  15645. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15646. const auto pattern = "/prefix:suffix";
  15647. detail::PathParamsMatcher matcher(pattern);
  15648. Request request;
  15649. request.path = "/prefix:suffix";
  15650. ASSERT_TRUE(matcher.match(request));
  15651. const std::unordered_map<std::string, std::string> expected_params = {};
  15652. EXPECT_EQ(request.path_params, expected_params);
  15653. }
  15654. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15655. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15656. // calling thread's stack on a long enough path for a quantified pattern;
  15657. // RegexMatcher must refuse to run regex matching on paths beyond
  15658. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15659. detail::RegexMatcher matcher("/files/(.*)");
  15660. Request within_limit;
  15661. within_limit.path = "/files/" + std::string(10, 'A');
  15662. EXPECT_TRUE(matcher.match(within_limit));
  15663. Request over_limit;
  15664. over_limit.path =
  15665. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15666. EXPECT_FALSE(matcher.match(over_limit));
  15667. }
  15668. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15669. Server svr;
  15670. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15671. res.set_content("ok", "text/plain");
  15672. });
  15673. auto port = svr.bind_to_any_port(HOST);
  15674. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15675. auto se = detail::scope_exit([&] {
  15676. svr.stop();
  15677. thread.join();
  15678. ASSERT_FALSE(svr.is_running());
  15679. });
  15680. svr.wait_until_ready();
  15681. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15682. // request URI limit; this used to be able to crash the process.
  15683. std::string path =
  15684. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15685. std::string req = "GET " + path +
  15686. " HTTP/1.1\r\n"
  15687. "Host: " +
  15688. std::string(HOST) + ":" + std::to_string(port) +
  15689. "\r\n"
  15690. "Connection: close\r\n"
  15691. "\r\n";
  15692. std::string response;
  15693. ASSERT_TRUE(send_request(5, req, &response, port));
  15694. EXPECT_NE(std::string::npos, response.find("404"));
  15695. }
  15696. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15697. Server svr;
  15698. auto handler = [](const Request & /*req*/, Response &res) {
  15699. res.set_content("hit", "text/plain");
  15700. };
  15701. // No regex metacharacter, so this one is compared literally
  15702. svr.Get("/literal/route", handler);
  15703. // '.' is a regex metacharacter, so this one must keep regex semantics
  15704. svr.Get("/a.c", handler);
  15705. auto port = svr.bind_to_any_port(HOST);
  15706. std::thread t([&]() { svr.listen_after_bind(); });
  15707. auto se = detail::scope_exit([&] {
  15708. svr.stop();
  15709. t.join();
  15710. ASSERT_FALSE(svr.is_running());
  15711. });
  15712. svr.wait_until_ready();
  15713. Client cli(HOST, port);
  15714. struct {
  15715. const char *path;
  15716. int status;
  15717. } cases[] = {
  15718. {"/literal/route", StatusCode::OK_200},
  15719. {"/literal/routes", StatusCode::NotFound_404},
  15720. {"/literal/rout", StatusCode::NotFound_404},
  15721. {"/abc", StatusCode::OK_200},
  15722. {"/a.c", StatusCode::OK_200},
  15723. };
  15724. for (const auto &x : cases) {
  15725. auto res = cli.Get(x.path);
  15726. ASSERT_TRUE(res) << x.path;
  15727. EXPECT_EQ(x.status, res->status) << x.path;
  15728. }
  15729. }
  15730. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15731. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15732. // from exhausting the stack, so it must only constrain routes that actually
  15733. // run a regular expression. A literal route is matched by comparison and
  15734. // stays usable at any length.
  15735. Server svr;
  15736. const std::string pattern =
  15737. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15738. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15739. res.set_content("hit", "text/plain");
  15740. });
  15741. auto port = svr.bind_to_any_port(HOST);
  15742. std::thread t([&]() { svr.listen_after_bind(); });
  15743. auto se = detail::scope_exit([&] {
  15744. svr.stop();
  15745. t.join();
  15746. ASSERT_FALSE(svr.is_running());
  15747. });
  15748. svr.wait_until_ready();
  15749. Client cli(HOST, port);
  15750. auto res = cli.Get(pattern);
  15751. ASSERT_TRUE(res);
  15752. EXPECT_EQ(StatusCode::OK_200, res->status);
  15753. }
  15754. TEST(ParseUrlTest, VariousPatterns) {
  15755. {
  15756. detail::UrlComponents uc;
  15757. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15758. EXPECT_EQ("http", uc.scheme);
  15759. EXPECT_EQ("example.com", uc.host);
  15760. EXPECT_EQ("8080", uc.port);
  15761. EXPECT_EQ("/path", uc.path);
  15762. EXPECT_EQ("?q=1", uc.query);
  15763. }
  15764. {
  15765. detail::UrlComponents uc;
  15766. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15767. EXPECT_EQ("https", uc.scheme);
  15768. EXPECT_EQ("example.com", uc.host);
  15769. EXPECT_TRUE(uc.port.empty());
  15770. EXPECT_EQ("/path", uc.path);
  15771. }
  15772. {
  15773. detail::UrlComponents uc;
  15774. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15775. EXPECT_EQ("::1", uc.host);
  15776. EXPECT_EQ("8080", uc.port);
  15777. EXPECT_EQ("/path", uc.path);
  15778. }
  15779. {
  15780. detail::UrlComponents uc;
  15781. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15782. }
  15783. {
  15784. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15785. // the path while the connection still targets the bracketed host.
  15786. detail::UrlComponents uc;
  15787. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15788. }
  15789. {
  15790. detail::UrlComponents uc;
  15791. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15792. }
  15793. {
  15794. detail::UrlComponents uc;
  15795. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15796. EXPECT_EQ("::1", uc.host);
  15797. EXPECT_TRUE(uc.port.empty());
  15798. EXPECT_EQ("/path", uc.path);
  15799. }
  15800. {
  15801. detail::UrlComponents uc;
  15802. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15803. EXPECT_TRUE(uc.scheme.empty());
  15804. EXPECT_EQ("example.com", uc.host);
  15805. EXPECT_EQ("/path", uc.path);
  15806. EXPECT_EQ("?q=1", uc.query);
  15807. }
  15808. {
  15809. detail::UrlComponents uc;
  15810. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15811. EXPECT_TRUE(uc.host.empty());
  15812. EXPECT_EQ("/path", uc.path);
  15813. EXPECT_EQ("?q=1", uc.query);
  15814. }
  15815. {
  15816. detail::UrlComponents uc;
  15817. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15818. EXPECT_EQ("example.com", uc.host);
  15819. EXPECT_EQ("8080", uc.port);
  15820. }
  15821. {
  15822. // Unix socket path — must not be parsed as host
  15823. detail::UrlComponents uc;
  15824. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15825. EXPECT_TRUE(uc.host.empty());
  15826. }
  15827. {
  15828. detail::UrlComponents uc;
  15829. ASSERT_TRUE(detail::parse_url("", uc));
  15830. EXPECT_TRUE(uc.host.empty());
  15831. EXPECT_TRUE(uc.path.empty());
  15832. }
  15833. {
  15834. detail::UrlComponents uc;
  15835. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15836. }
  15837. {
  15838. detail::UrlComponents uc;
  15839. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15840. }
  15841. {
  15842. // Accepted by parse_url; callers restrict to http/https
  15843. detail::UrlComponents uc;
  15844. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15845. EXPECT_EQ("ftp", uc.scheme);
  15846. }
  15847. {
  15848. detail::UrlComponents uc;
  15849. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15850. }
  15851. {
  15852. detail::UrlComponents uc;
  15853. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15854. }
  15855. }
  15856. TEST(ParseUrlTest, FragmentHandling) {
  15857. {
  15858. detail::UrlComponents uc;
  15859. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15860. EXPECT_EQ("/path", uc.path);
  15861. EXPECT_TRUE(uc.query.empty());
  15862. }
  15863. {
  15864. detail::UrlComponents uc;
  15865. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15866. EXPECT_TRUE(uc.path.empty());
  15867. EXPECT_TRUE(uc.query.empty());
  15868. }
  15869. }
  15870. TEST(ParseUrlTest, UserinfoHandling) {
  15871. // Userinfo with @ but no colon — host includes @
  15872. detail::UrlComponents uc;
  15873. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15874. EXPECT_EQ("user@host.com", uc.host);
  15875. EXPECT_EQ("/path", uc.path);
  15876. }
  15877. TEST(ParseUrlTest, IPv6EdgeCases) {
  15878. {
  15879. detail::UrlComponents uc;
  15880. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15881. EXPECT_TRUE(uc.scheme.empty());
  15882. EXPECT_EQ("::1", uc.host);
  15883. EXPECT_EQ("8080", uc.port);
  15884. }
  15885. {
  15886. // Zone ID '%25' is not in [a-fA-F0-9:]
  15887. detail::UrlComponents uc;
  15888. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15889. }
  15890. }
  15891. TEST(ParseUrlTest, SchemeEdgeCases) {
  15892. {
  15893. detail::UrlComponents uc;
  15894. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15895. }
  15896. {
  15897. detail::UrlComponents uc;
  15898. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15899. }
  15900. {
  15901. detail::UrlComponents uc;
  15902. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15903. }
  15904. }
  15905. TEST(ParseUrlTest, PortEdgeCases) {
  15906. {
  15907. detail::UrlComponents uc;
  15908. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15909. EXPECT_TRUE(uc.port.empty());
  15910. EXPECT_EQ("/path", uc.path);
  15911. }
  15912. {
  15913. // parse_url accepts any port string; validation is done by parse_port
  15914. detail::UrlComponents uc;
  15915. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15916. EXPECT_EQ("abc", uc.port);
  15917. }
  15918. }
  15919. TEST(ParseUrlTest, WebSocketPatterns) {
  15920. {
  15921. detail::UrlComponents uc;
  15922. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15923. EXPECT_EQ("ws", uc.scheme);
  15924. EXPECT_EQ("echo.example.com", uc.host);
  15925. EXPECT_EQ("8080", uc.port);
  15926. EXPECT_EQ("/ws", uc.path);
  15927. }
  15928. {
  15929. detail::UrlComponents uc;
  15930. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15931. EXPECT_EQ("wss", uc.scheme);
  15932. EXPECT_EQ("echo.example.com", uc.host);
  15933. EXPECT_TRUE(uc.port.empty());
  15934. EXPECT_EQ("/ws", uc.path);
  15935. }
  15936. }
  15937. TEST(ParseUrlTest, QueryOnly) {
  15938. detail::UrlComponents uc;
  15939. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15940. EXPECT_TRUE(uc.host.empty());
  15941. EXPECT_TRUE(uc.path.empty());
  15942. EXPECT_EQ("?q=1&r=2", uc.query);
  15943. }
  15944. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15945. detail::UrlComponents uc;
  15946. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15947. EXPECT_TRUE(uc.scheme.empty());
  15948. EXPECT_EQ("example.com", uc.host);
  15949. EXPECT_EQ("443", uc.port);
  15950. EXPECT_EQ("/path", uc.path);
  15951. }
  15952. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15953. // If ipv6 regex working, regex match codepath is taken.
  15954. // else port will default to 80 in Client impl
  15955. int clientImplMagicPort = 80;
  15956. int port = 4321;
  15957. // above ports must be different to avoid false negative
  15958. EXPECT_NE(clientImplMagicPort, port);
  15959. std::string ipV6TestURL = "http://[ff06::c3]";
  15960. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15961. CLIENT_PRIVATE_KEY_FILE);
  15962. EXPECT_EQ(cli.port(), port);
  15963. }
  15964. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15965. auto file_path = "./www/dir/index.html";
  15966. auto dir_path = "./www/dir";
  15967. detail::FileStat stat_file(file_path);
  15968. EXPECT_TRUE(stat_file.is_file());
  15969. EXPECT_FALSE(stat_file.is_dir());
  15970. detail::FileStat stat_dir(dir_path);
  15971. EXPECT_FALSE(stat_dir.is_file());
  15972. EXPECT_TRUE(stat_dir.is_dir());
  15973. }
  15974. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15975. // IPv4 with default HTTP port (80)
  15976. EXPECT_EQ("example.com",
  15977. detail::make_host_and_port_string("example.com", 80, false));
  15978. // IPv4 with default HTTPS port (443)
  15979. EXPECT_EQ("example.com",
  15980. detail::make_host_and_port_string("example.com", 443, true));
  15981. // IPv4 with non-default HTTP port
  15982. EXPECT_EQ("example.com:8080",
  15983. detail::make_host_and_port_string("example.com", 8080, false));
  15984. // IPv4 with non-default HTTPS port
  15985. EXPECT_EQ("example.com:8443",
  15986. detail::make_host_and_port_string("example.com", 8443, true));
  15987. // IPv6 with default HTTP port (80)
  15988. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15989. // IPv6 with default HTTPS port (443)
  15990. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15991. // IPv6 with non-default HTTP port
  15992. EXPECT_EQ("[::1]:8080",
  15993. detail::make_host_and_port_string("::1", 8080, false));
  15994. // IPv6 with non-default HTTPS port
  15995. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15996. // IPv6 full address with default port
  15997. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15998. detail::make_host_and_port_string(
  15999. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16000. // IPv6 full address with non-default port
  16001. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16002. detail::make_host_and_port_string(
  16003. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16004. // IPv6 localhost with non-default port
  16005. EXPECT_EQ("[::1]:3000",
  16006. detail::make_host_and_port_string("::1", 3000, false));
  16007. // IPv6 with zone ID (link-local address) with default port
  16008. EXPECT_EQ("[fe80::1%eth0]",
  16009. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16010. // IPv6 with zone ID (link-local address) with non-default port
  16011. EXPECT_EQ("[fe80::1%eth0]:8080",
  16012. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16013. // Edge case: Port 443 with is_ssl=false (should add port)
  16014. EXPECT_EQ("example.com:443",
  16015. detail::make_host_and_port_string("example.com", 443, false));
  16016. // Edge case: Port 80 with is_ssl=true (should add port)
  16017. EXPECT_EQ("example.com:80",
  16018. detail::make_host_and_port_string("example.com", 80, true));
  16019. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16020. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16021. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16022. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16023. // Security fix: Already bracketed IPv6 should not get double brackets
  16024. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16025. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16026. EXPECT_EQ("[::1]:8080",
  16027. detail::make_host_and_port_string("[::1]", 8080, false));
  16028. EXPECT_EQ("[2001:db8::1]:8080",
  16029. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16030. EXPECT_EQ("[fe80::1%eth0]",
  16031. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16032. EXPECT_EQ("[fe80::1%eth0]:8080",
  16033. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16034. // Edge case: Empty host (should return as-is)
  16035. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16036. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16037. // This is a known limitation but shouldn't crash
  16038. EXPECT_EQ("[host:name]",
  16039. detail::make_host_and_port_string("host:name", 80, false));
  16040. // Port number edge cases (no validation, but should not crash)
  16041. EXPECT_EQ("example.com:0",
  16042. detail::make_host_and_port_string("example.com", 0, false));
  16043. EXPECT_EQ("example.com:-1",
  16044. detail::make_host_and_port_string("example.com", -1, false));
  16045. EXPECT_EQ("example.com:65535",
  16046. detail::make_host_and_port_string("example.com", 65535, false));
  16047. EXPECT_EQ("example.com:65536",
  16048. detail::make_host_and_port_string("example.com", 65536, false));
  16049. }
  16050. #ifdef CPPHTTPLIB_SSL_ENABLED
  16051. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16052. httplib::SSLClient cli("roblox.com", 443);
  16053. cli.set_follow_location(true);
  16054. auto res = cli.Get("/");
  16055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16056. EXPECT_EQ(StatusCode::OK_200, res->status);
  16057. }
  16058. #endif
  16059. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16060. Server svr;
  16061. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16062. EXPECT_EQ(res.status, 400);
  16063. });
  16064. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16065. auto se = detail::scope_exit([&] {
  16066. svr.stop();
  16067. thread.join();
  16068. ASSERT_FALSE(svr.is_running());
  16069. });
  16070. svr.wait_until_ready();
  16071. Client cli(HOST, PORT);
  16072. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16073. }
  16074. TEST(InvalidHeaderCharsTest, is_field_name) {
  16075. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16076. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16077. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16078. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16079. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16080. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16081. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16082. EXPECT_FALSE(detail::fields::is_field_name(""));
  16083. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16084. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16085. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16086. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16087. }
  16088. TEST(InvalidHeaderCharsTest, is_field_value) {
  16089. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16090. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16091. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16092. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16093. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16094. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16095. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16096. EXPECT_TRUE(detail::fields::is_field_value(""));
  16097. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16098. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16099. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16100. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16101. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16102. }
  16103. TEST(InvalidHeaderCharsTest, OnServer) {
  16104. Server svr;
  16105. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16106. std::string header = "Not Set";
  16107. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16108. res.set_header(header, "value");
  16109. res.set_content("Page Content Page Content", "text/plain");
  16110. });
  16111. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16112. std::string header = "Not Set";
  16113. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16114. res.set_header("X-Test", header);
  16115. res.set_content("Page Content Page Content", "text/plain");
  16116. });
  16117. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16118. auto se = detail::scope_exit([&] {
  16119. svr.stop();
  16120. thread.join();
  16121. ASSERT_FALSE(svr.is_running());
  16122. });
  16123. svr.wait_until_ready();
  16124. Client cli(HOST, PORT);
  16125. {
  16126. auto res = cli.Get(
  16127. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16129. EXPECT_EQ("Page Content Page Content", res->body);
  16130. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16131. }
  16132. {
  16133. auto res = cli.Get(
  16134. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16136. EXPECT_EQ("Page Content Page Content", res->body);
  16137. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16138. }
  16139. }
  16140. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16141. auto handled = false;
  16142. Server svr;
  16143. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16144. thread t = thread([&] { svr.listen(HOST, PORT); });
  16145. auto se = detail::scope_exit([&] {
  16146. svr.stop();
  16147. t.join();
  16148. ASSERT_FALSE(svr.is_running());
  16149. ASSERT_FALSE(handled);
  16150. });
  16151. svr.wait_until_ready();
  16152. auto req = "POST /test HTTP/1.1\r\n"
  16153. "Content-Length: x\r\n"
  16154. "\r\n";
  16155. std::string response;
  16156. ASSERT_TRUE(send_request(1, req, &response));
  16157. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16158. response.substr(0, response.find("\r\n")));
  16159. }
  16160. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16161. // case-insensitive, and a server that receives a 100-continue expectation in
  16162. // an HTTP/1.0 request MUST ignore it.
  16163. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16164. std::string response;
  16165. ASSERT_TRUE(send_request(1, req, &response, port));
  16166. *got_100 = response.find("100 Continue") != std::string::npos;
  16167. }
  16168. class ExpectTokenTest : public ::testing::Test {
  16169. protected:
  16170. void SetUp() override {
  16171. svr_.Post("/p", [](const Request &, Response &res) {
  16172. res.set_content("ok", "text/plain");
  16173. });
  16174. port_ = svr_.bind_to_any_port(HOST);
  16175. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16176. svr_.wait_until_ready();
  16177. }
  16178. void TearDown() override {
  16179. svr_.stop();
  16180. if (thread_.joinable()) { thread_.join(); }
  16181. }
  16182. std::string request(const char *version, const char *expect_value) const {
  16183. return std::string("POST /p ") + version +
  16184. "\r\n"
  16185. "Host: localhost\r\n"
  16186. "Content-Length: 2\r\n"
  16187. "Connection: close\r\n"
  16188. "Expect: " +
  16189. expect_value +
  16190. "\r\n"
  16191. "\r\n"
  16192. "hi";
  16193. }
  16194. Server svr_;
  16195. int port_ = 0;
  16196. thread thread_;
  16197. };
  16198. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16199. bool got_100 = false;
  16200. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16201. EXPECT_TRUE(got_100);
  16202. }
  16203. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16204. bool got_100 = true;
  16205. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16206. EXPECT_FALSE(got_100);
  16207. }
  16208. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16209. bool got_100 = false;
  16210. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16211. EXPECT_TRUE(got_100);
  16212. }
  16213. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16214. bool got_100 = false;
  16215. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16216. EXPECT_TRUE(got_100);
  16217. }
  16218. // `100 Continue` is sent only when the server starts reading the body, so a
  16219. // request rejected before that never invites the client to send it. The
  16220. // requests below carry the expectation but withhold the body, as a client
  16221. // waiting for `100 Continue` would.
  16222. // A POST that expects `100 Continue` and withholds its two-byte body.
  16223. static std::string expect_headers_only(const std::string &path) {
  16224. return "POST " + path +
  16225. " HTTP/1.1\r\n"
  16226. "Host: localhost\r\n"
  16227. "Content-Length: 2\r\n"
  16228. "Expect: 100-continue\r\n"
  16229. "\r\n";
  16230. }
  16231. class ExpectLazyContinueTest : public ::testing::Test {
  16232. protected:
  16233. void SetUp() override {
  16234. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16235. if (req.path == "/pre-routing") {
  16236. res.status = StatusCode::Unauthorized_401;
  16237. return Server::HandlerResponse::Handled;
  16238. }
  16239. return Server::HandlerResponse::Unhandled;
  16240. });
  16241. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16242. if (req.matched_route == "/pre-request") {
  16243. res.status = StatusCode::Forbidden_403;
  16244. return Server::HandlerResponse::Handled;
  16245. }
  16246. return Server::HandlerResponse::Unhandled;
  16247. });
  16248. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16249. res.set_content("ok", "text/plain");
  16250. });
  16251. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16252. res.set_content("ok", "text/plain");
  16253. });
  16254. svr_.Post("/reader-used", [](const Request &, Response &res,
  16255. const ContentReader &content_reader) {
  16256. std::string body;
  16257. content_reader([&](const char *data, size_t len) {
  16258. body.append(data, len);
  16259. return true;
  16260. });
  16261. res.set_content(body, "text/plain");
  16262. });
  16263. svr_.Post("/reader-unused",
  16264. [](const Request &, Response &res, const ContentReader &) {
  16265. res.set_content("ignored", "text/plain");
  16266. });
  16267. port_ = svr_.bind_to_any_port(HOST);
  16268. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16269. svr_.wait_until_ready();
  16270. }
  16271. void TearDown() override {
  16272. svr_.stop();
  16273. if (thread_.joinable()) { thread_.join(); }
  16274. }
  16275. // Sends `req` and reads until the server closes the connection. Returns
  16276. // false if the read had to wait for the client-side timeout instead.
  16277. bool send_until_closed(const std::string &req, std::string *resp) const {
  16278. auto start = std::chrono::steady_clock::now();
  16279. if (!send_request(3, req, resp, port_)) { return false; }
  16280. auto elapsed = std::chrono::steady_clock::now() - start;
  16281. return elapsed < std::chrono::seconds(2);
  16282. }
  16283. // The final response comes without `100 Continue`, and the server closes
  16284. // the connection since the body may or may not follow.
  16285. void expect_final_without_interim(const std::string &path,
  16286. const char *status_line) const {
  16287. std::string resp;
  16288. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16289. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16290. EXPECT_EQ(0u, resp.find(status_line));
  16291. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16292. }
  16293. Server svr_;
  16294. int port_ = 0;
  16295. thread thread_;
  16296. };
  16297. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16298. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16299. }
  16300. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16301. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16302. }
  16303. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16304. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16305. }
  16306. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16307. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16308. }
  16309. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16310. // The body follows once `100 Continue` has had time to arrive.
  16311. auto req = expect_headers_only("/reader-used");
  16312. req.insert(req.size() - 2, "Connection: close\r\n");
  16313. std::string resp;
  16314. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16315. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16316. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16317. EXPECT_NE(std::string::npos, resp.find("hi"));
  16318. }
  16319. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16320. // Large enough for the client to add `Expect: 100-continue` itself.
  16321. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16322. std::atomic<bool> body_sent{false};
  16323. Client cli(HOST, port_);
  16324. auto res = cli.Post(
  16325. "/pre-request", length,
  16326. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16327. body_sent = true;
  16328. std::string chunk(len, 'x');
  16329. sink.write(chunk.data(), chunk.size());
  16330. return true;
  16331. },
  16332. "application/octet-stream");
  16333. ASSERT_TRUE(res);
  16334. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16335. EXPECT_FALSE(body_sent);
  16336. }
  16337. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16338. Server svr;
  16339. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16340. return StatusCode::ExpectationFailed_417;
  16341. });
  16342. svr.Post("/p", [](const Request &, Response &res) {
  16343. res.set_content("ok", "text/plain");
  16344. });
  16345. auto port = svr.bind_to_any_port(HOST);
  16346. thread t = thread([&] { svr.listen_after_bind(); });
  16347. auto se = detail::scope_exit([&] {
  16348. svr.stop();
  16349. t.join();
  16350. });
  16351. svr.wait_until_ready();
  16352. std::string resp;
  16353. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16354. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16355. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16356. // Exactly one response: the route handler must not run after the 417.
  16357. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16358. }
  16359. #ifndef _WIN32
  16360. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16361. static constexpr char reject[] = "Unauthorized";
  16362. static constexpr char accept[] = "Upload accepted";
  16363. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16364. Server svr;
  16365. svr.set_expect_100_continue_handler(
  16366. [](const Request & /*req*/, Response &res) {
  16367. res.status = StatusCode::Unauthorized_401;
  16368. res.set_content(reject, "text/plain");
  16369. return res.status;
  16370. });
  16371. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16372. res.set_content(accept, "text/plain");
  16373. });
  16374. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16375. auto se = detail::scope_exit([&] {
  16376. svr.stop();
  16377. thread.join();
  16378. ASSERT_FALSE(svr.is_running());
  16379. });
  16380. svr.wait_until_ready();
  16381. {
  16382. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16383. curl_easy_init(), &curl_easy_cleanup};
  16384. ASSERT_NE(curl, nullptr);
  16385. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16386. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16387. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16388. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16389. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16390. &curl_slist_free_all};
  16391. ASSERT_NE(list, nullptr);
  16392. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16393. struct read_data {
  16394. size_t read_size;
  16395. size_t total_size;
  16396. } data = {0, total_size};
  16397. using read_callback_t =
  16398. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16399. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16400. void *userdata) -> size_t {
  16401. read_data *d = (read_data *)userdata;
  16402. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16403. std::fill_n(ptr, size * nmemb, 'A');
  16404. d->read_size += size * nmemb;
  16405. return size * nmemb;
  16406. };
  16407. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16408. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16409. std::vector<char> buffer;
  16410. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16411. using write_callback_t =
  16412. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16413. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16414. void *userdata) -> size_t {
  16415. std::vector<char> *buf = (std::vector<char> *)userdata;
  16416. buf->reserve(buf->size() + size * nmemb + 1);
  16417. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16418. return size * nmemb;
  16419. };
  16420. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16421. {
  16422. const auto res = curl_easy_perform(curl.get());
  16423. ASSERT_EQ(res, CURLE_OK);
  16424. }
  16425. {
  16426. auto response_code = long{};
  16427. const auto res =
  16428. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16429. ASSERT_EQ(res, CURLE_OK);
  16430. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16431. }
  16432. {
  16433. auto dl = curl_off_t{};
  16434. const auto res =
  16435. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16436. ASSERT_EQ(res, CURLE_OK);
  16437. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16438. }
  16439. {
  16440. buffer.push_back('\0');
  16441. ASSERT_STRCASEEQ(buffer.data(), reject);
  16442. }
  16443. }
  16444. }
  16445. #endif
  16446. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16447. // Regression test for #2458.
  16448. //
  16449. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16450. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16451. // ticket can make the client socket spuriously readable during the
  16452. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16453. // the client withholds the body and then blocks reading a response that never
  16454. // comes, failing with `Failed to read connection`.
  16455. //
  16456. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16457. // within the timeout. This raw OpenSSL server deliberately never sends
  16458. // `100 Continue`; the client must still deliver the body and receive 200.
  16459. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16460. signal(SIGPIPE, SIG_IGN);
  16461. const auto port = PORT + 4;
  16462. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16463. ASSERT_NE(srv, INVALID_SOCKET);
  16464. int opt = 1;
  16465. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16466. sockaddr_in addr{};
  16467. addr.sin_family = AF_INET;
  16468. addr.sin_port = htons(static_cast<uint16_t>(port));
  16469. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16470. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16471. ASSERT_EQ(0, ::listen(srv, 1));
  16472. std::atomic<size_t> server_body_bytes{0};
  16473. auto server_thread = std::thread([&] {
  16474. sockaddr_in cli_addr{};
  16475. socklen_t cli_len = sizeof(cli_addr);
  16476. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16477. if (cli == INVALID_SOCKET) { return; }
  16478. // Bound the lifetime of the server side so a buggy client (which never
  16479. // sends the body) cannot make this thread block forever on join.
  16480. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16481. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16482. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16483. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16484. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16485. SSL *ssl = SSL_new(ctx);
  16486. SSL_set_fd(ssl, static_cast<int>(cli));
  16487. if (SSL_accept(ssl) > 0) {
  16488. // Read the request headers. Reading here also flushes the TLS 1.3
  16489. // session tickets to the client. Deliberately do NOT send
  16490. // `100 Continue`.
  16491. std::string buf;
  16492. char tmp[1024];
  16493. while (buf.find("\r\n\r\n") == std::string::npos) {
  16494. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16495. if (n <= 0) { break; }
  16496. buf.append(tmp, static_cast<size_t>(n));
  16497. }
  16498. // A correct client sends the body now; count what arrives.
  16499. auto pos = buf.find("\r\n\r\n");
  16500. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16501. while (body < 4096) {
  16502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16503. if (n <= 0) { break; }
  16504. body += static_cast<size_t>(n);
  16505. }
  16506. server_body_bytes = body;
  16507. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16508. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16509. SSL_shutdown(ssl);
  16510. }
  16511. SSL_free(ssl);
  16512. detail::close_socket(cli);
  16513. SSL_CTX_free(ctx);
  16514. });
  16515. auto se = detail::scope_exit([&] {
  16516. server_thread.join();
  16517. detail::close_socket(srv);
  16518. });
  16519. SSLClient cli("127.0.0.1", port);
  16520. cli.enable_server_certificate_verification(false);
  16521. cli.set_connection_timeout(5, 0);
  16522. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16523. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16524. std::string body(4096, 'A');
  16525. auto res = cli.Put("/api/test", body, "application/json");
  16526. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16527. EXPECT_EQ(StatusCode::OK_200, res->status);
  16528. EXPECT_EQ(body.size(), server_body_bytes.load());
  16529. }
  16530. #endif
  16531. template <typename S, typename C>
  16532. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16533. svr.Get("/stream", [&](const Request &, Response &res) {
  16534. auto data = new std::string("01234567890123456789");
  16535. res.set_content_provider(
  16536. data->size(), "text/plain",
  16537. [&, data](size_t offset, size_t length, DataSink &sink) {
  16538. const size_t DATA_CHUNK_SIZE = 4;
  16539. const auto &d = *data;
  16540. std::this_thread::sleep_for(std::chrono::seconds(1));
  16541. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16542. return true;
  16543. },
  16544. [data](bool success) {
  16545. EXPECT_FALSE(success);
  16546. delete data;
  16547. });
  16548. });
  16549. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16550. auto i = new size_t(0);
  16551. res.set_content_provider(
  16552. "text/plain",
  16553. [i](size_t, DataSink &sink) {
  16554. if (*i < 5) {
  16555. std::this_thread::sleep_for(std::chrono::seconds(1));
  16556. sink.write("abcd", 4);
  16557. (*i)++;
  16558. } else {
  16559. sink.done();
  16560. }
  16561. return true;
  16562. },
  16563. [i](bool success) {
  16564. EXPECT_FALSE(success);
  16565. delete i;
  16566. });
  16567. });
  16568. svr.Get("/chunked", [&](const Request &, Response &res) {
  16569. auto i = new size_t(0);
  16570. res.set_chunked_content_provider(
  16571. "text/plain",
  16572. [i](size_t, DataSink &sink) {
  16573. if (*i < 5) {
  16574. std::this_thread::sleep_for(std::chrono::seconds(1));
  16575. sink.os << "abcd";
  16576. (*i)++;
  16577. } else {
  16578. sink.done();
  16579. }
  16580. return true;
  16581. },
  16582. [i](bool success) {
  16583. EXPECT_FALSE(success);
  16584. delete i;
  16585. });
  16586. });
  16587. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16588. auto se = detail::scope_exit([&] {
  16589. svr.stop();
  16590. listen_thread.join();
  16591. ASSERT_FALSE(svr.is_running());
  16592. });
  16593. svr.wait_until_ready();
  16594. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16595. {
  16596. auto start = std::chrono::steady_clock::now();
  16597. auto res = cli.Get("/stream");
  16598. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16599. std::chrono::steady_clock::now() - start)
  16600. .count();
  16601. ASSERT_FALSE(res);
  16602. EXPECT_EQ(Error::Read, res.error());
  16603. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16604. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16605. }
  16606. {
  16607. auto start = std::chrono::steady_clock::now();
  16608. auto res = cli.Get("/stream_without_length");
  16609. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16610. std::chrono::steady_clock::now() - start)
  16611. .count();
  16612. ASSERT_FALSE(res);
  16613. EXPECT_EQ(Error::Read, res.error());
  16614. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16615. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16616. }
  16617. {
  16618. auto start = std::chrono::steady_clock::now();
  16619. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16620. EXPECT_EQ("abcd", string(data, data_length));
  16621. return true;
  16622. });
  16623. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16624. std::chrono::steady_clock::now() - start)
  16625. .count();
  16626. ASSERT_FALSE(res);
  16627. EXPECT_EQ(Error::Read, res.error());
  16628. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16629. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16630. }
  16631. }
  16632. TEST(MaxTimeoutTest, ContentStream) {
  16633. time_t timeout = 2000;
  16634. time_t threshold = 200;
  16635. Server svr;
  16636. Client cli("localhost", PORT);
  16637. max_timeout_test(svr, cli, timeout, threshold);
  16638. }
  16639. #ifdef CPPHTTPLIB_SSL_ENABLED
  16640. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16641. time_t timeout = 2000;
  16642. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16644. SSLClient cli("localhost", PORT);
  16645. cli.enable_server_certificate_verification(false);
  16646. max_timeout_test(svr, cli, timeout, threshold);
  16647. }
  16648. #endif
  16649. class EventDispatcher {
  16650. public:
  16651. EventDispatcher() {}
  16652. bool wait_event(DataSink *sink) {
  16653. unique_lock<mutex> lk(m_);
  16654. int id = id_;
  16655. // Wait with timeout to prevent hanging if client disconnects
  16656. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16657. [&] { return cid_ == id; })) {
  16658. return false; // Timeout occurred
  16659. }
  16660. sink->write(message_.data(), message_.size());
  16661. return true;
  16662. }
  16663. void send_event(const string &message) {
  16664. lock_guard<mutex> lk(m_);
  16665. cid_ = id_++;
  16666. message_ = message;
  16667. cv_.notify_all();
  16668. }
  16669. private:
  16670. mutex m_;
  16671. condition_variable cv_;
  16672. atomic_int id_{0};
  16673. atomic_int cid_{-1};
  16674. string message_;
  16675. };
  16676. TEST(ClientInThreadTest, Issue2068) {
  16677. EventDispatcher ed;
  16678. Server svr;
  16679. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16680. res.set_chunked_content_provider("text/event-stream",
  16681. [&](size_t /*offset*/, DataSink &sink) {
  16682. return ed.wait_event(&sink);
  16683. });
  16684. });
  16685. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16686. svr.wait_until_ready();
  16687. thread event_thread([&] {
  16688. int id = 0;
  16689. while (svr.is_running()) {
  16690. this_thread::sleep_for(chrono::milliseconds(500));
  16691. std::stringstream ss;
  16692. ss << "data: " << id << "\n\n";
  16693. ed.send_event(ss.str());
  16694. id++;
  16695. }
  16696. });
  16697. auto se = detail::scope_exit([&] {
  16698. svr.stop();
  16699. listen_thread.join();
  16700. event_thread.join();
  16701. ASSERT_FALSE(svr.is_running());
  16702. });
  16703. {
  16704. auto client = detail::make_unique<Client>(HOST, PORT);
  16705. client->set_read_timeout(std::chrono::minutes(10));
  16706. std::atomic<bool> stop{false};
  16707. std::thread t([&] {
  16708. client->Get("/event1",
  16709. [&](const char *, size_t) -> bool { return !stop; });
  16710. });
  16711. std::this_thread::sleep_for(std::chrono::seconds(2));
  16712. stop = true;
  16713. client->stop();
  16714. t.join();
  16715. // Reset client after thread has finished
  16716. client.reset();
  16717. }
  16718. }
  16719. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16720. auto handled = false;
  16721. Server svr;
  16722. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16723. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16724. auto se = detail::scope_exit([&] {
  16725. svr.stop();
  16726. t.join();
  16727. ASSERT_FALSE(svr.is_running());
  16728. ASSERT_FALSE(handled);
  16729. });
  16730. svr.wait_until_ready();
  16731. // Two Content-Length headers with different values — must be rejected
  16732. auto req = "POST /test HTTP/1.1\r\n"
  16733. "Content-Length: 5\r\n"
  16734. "Content-Length: 10\r\n"
  16735. "\r\n"
  16736. "hello";
  16737. std::string response;
  16738. ASSERT_TRUE(send_request(1, req, &response));
  16739. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16740. response.substr(0, response.find("\r\n")));
  16741. }
  16742. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16743. auto handled = false;
  16744. Server svr;
  16745. svr.Post("/test", [&](const Request &, Response &res) {
  16746. handled = true;
  16747. res.set_content("ok", "text/plain");
  16748. });
  16749. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16750. auto se = detail::scope_exit([&] {
  16751. svr.stop();
  16752. t.join();
  16753. ASSERT_FALSE(svr.is_running());
  16754. ASSERT_TRUE(handled);
  16755. });
  16756. svr.wait_until_ready();
  16757. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16758. auto req = "POST /test HTTP/1.1\r\n"
  16759. "Content-Length: 5\r\n"
  16760. "Content-Length: 5\r\n"
  16761. "\r\n"
  16762. "hello";
  16763. std::string response;
  16764. ASSERT_TRUE(send_request(1, req, &response));
  16765. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16766. }
  16767. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16768. Server svr;
  16769. svr.Get("/test", [](const Request &, Response &res) {
  16770. res.set_content("ok", "text/plain");
  16771. });
  16772. auto port = svr.bind_to_any_port(HOST);
  16773. thread t = thread([&] { svr.listen_after_bind(); });
  16774. auto se = detail::scope_exit([&] {
  16775. svr.stop();
  16776. t.join();
  16777. ASSERT_FALSE(svr.is_running());
  16778. });
  16779. svr.wait_until_ready();
  16780. auto status_line = [&](const std::string &host_lines) {
  16781. std::string res;
  16782. send_request(
  16783. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16784. &res, port);
  16785. return res.substr(0, res.find("\r\n"));
  16786. };
  16787. const char *accepted[] = {
  16788. "Host: localhost\r\n",
  16789. "Host: a.example:8080\r\n",
  16790. "Host: my_service\r\n",
  16791. "Host: [::1]:8080\r\n",
  16792. "Host: [fe80::1%25eth0]\r\n",
  16793. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16794. };
  16795. for (auto host_lines : accepted) {
  16796. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16797. }
  16798. const char *rejected[] = {
  16799. "Host: a.example\r\nHost: b.example\r\n",
  16800. "Host: a.example\r\nHost: a.example\r\n",
  16801. "Host: a@b.example\r\n",
  16802. "Host: a.example/b\r\n",
  16803. "Host: a.example\\b\r\n",
  16804. "Host: a.example?b\r\n",
  16805. "Host: a.example#b\r\n",
  16806. "Host: a.example b.example\r\n",
  16807. };
  16808. for (auto host_lines : rejected) {
  16809. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16810. << host_lines;
  16811. }
  16812. }
  16813. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16814. Server svr;
  16815. svr.Get("/", [](const Request &req, Response &res) {
  16816. EXPECT_EQ(2U, req.trailers.size());
  16817. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16818. // Denied
  16819. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16820. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16821. // Accepted
  16822. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16823. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16824. EXPECT_TRUE(req.has_trailer("X-World"));
  16825. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16826. res.set_content("ok", "text/plain");
  16827. });
  16828. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16829. auto se = detail::scope_exit([&] {
  16830. svr.stop();
  16831. t.join();
  16832. ASSERT_FALSE(svr.is_running());
  16833. });
  16834. svr.wait_until_ready();
  16835. const std::string req = "GET / HTTP/1.1\r\n"
  16836. "Transfer-Encoding: chunked\r\n"
  16837. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16838. "\r\n"
  16839. "0\r\n"
  16840. "Content-Length: 10\r\n"
  16841. "Host: internal.local\r\n"
  16842. "Content-Type: malicious/content\r\n"
  16843. "Cookie: any\r\n"
  16844. "Set-Cookie: any\r\n"
  16845. "X-Forwarded-For: attacker.com\r\n"
  16846. "X-Real-Ip: 1.1.1.1\r\n"
  16847. "X-Hello: hello\r\n"
  16848. "X-World: world\r\n"
  16849. "\r\n";
  16850. std::string res;
  16851. ASSERT_TRUE(send_request(1, req, &res));
  16852. }
  16853. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16854. // several field lines, and the combined value is what has to be parsed. A
  16855. // Trailer field split across lines therefore declares every name it lists;
  16856. // reading only the first line silently drops the trailers the later lines
  16857. // declare. The prohibited-trailer filter still applies to every line.
  16858. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16859. Server svr;
  16860. size_t observed_trailer_count = 0;
  16861. std::string observed_hello;
  16862. std::string observed_world;
  16863. bool observed_content_length = true;
  16864. svr.Get("/", [&](const Request &req, Response &res) {
  16865. observed_trailer_count = req.trailers.size();
  16866. observed_hello = req.get_trailer_value("X-Hello");
  16867. observed_world = req.get_trailer_value("X-World");
  16868. observed_content_length = req.has_trailer("Content-Length");
  16869. res.set_content("ok", "text/plain");
  16870. });
  16871. auto port = svr.bind_to_any_port(HOST);
  16872. thread t = thread([&]() { svr.listen_after_bind(); });
  16873. auto se = detail::scope_exit([&] {
  16874. svr.stop();
  16875. t.join();
  16876. ASSERT_FALSE(svr.is_running());
  16877. });
  16878. svr.wait_until_ready();
  16879. const std::string req = "GET / HTTP/1.1\r\n"
  16880. "Transfer-Encoding: chunked\r\n"
  16881. "Trailer: X-Hello\r\n"
  16882. "Trailer: X-World, Content-Length\r\n"
  16883. "\r\n"
  16884. "0\r\n"
  16885. "X-Hello: hello\r\n"
  16886. "X-World: world\r\n"
  16887. "Content-Length: 10\r\n"
  16888. "\r\n";
  16889. std::string res;
  16890. ASSERT_TRUE(send_request(1, req, &res, port));
  16891. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16892. // Accepted: both field lines contribute to the declared set
  16893. EXPECT_EQ(2U, observed_trailer_count);
  16894. EXPECT_EQ(observed_hello, "hello");
  16895. EXPECT_EQ(observed_world, "world");
  16896. // Denied: a prohibited name stays prohibited on a later field line
  16897. EXPECT_FALSE(observed_content_length);
  16898. }
  16899. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16900. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16901. // unbounded run of fields that are never declared, because the counter would
  16902. // only advance for declared fields.
  16903. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16904. Server svr;
  16905. bool handler_called = false;
  16906. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16907. handler_called = true;
  16908. res.set_content("ok", "text/plain");
  16909. });
  16910. auto port = svr.bind_to_any_port(HOST);
  16911. thread t = thread([&]() { svr.listen_after_bind(); });
  16912. auto se = detail::scope_exit([&] {
  16913. svr.stop();
  16914. t.join();
  16915. ASSERT_FALSE(svr.is_running());
  16916. });
  16917. svr.wait_until_ready();
  16918. // Declare nothing, then send far more undeclared trailer fields than the
  16919. // header-count limit. Parsing must stop and reject the request rather than
  16920. // read every line.
  16921. std::string req = "GET / HTTP/1.1\r\n"
  16922. "Transfer-Encoding: chunked\r\n"
  16923. "\r\n"
  16924. "0\r\n";
  16925. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16926. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16927. }
  16928. req += "\r\n";
  16929. std::string res;
  16930. ASSERT_TRUE(send_request(1, req, &res, port));
  16931. // The request is rejected before the handler runs.
  16932. EXPECT_FALSE(handler_called);
  16933. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16934. }
  16935. // The set of declared trailer names is capped so a peer cannot grow it without
  16936. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16937. // declared past the cap is not honored, even if the field is actually sent.
  16938. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16939. Server svr;
  16940. // One name inside the cap and one past it, so the test tracks the cap rather
  16941. // than a fixed count.
  16942. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16943. const std::string within_cap_name = "X-T-0";
  16944. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16945. bool observed_within_cap = false;
  16946. bool observed_past_cap = false;
  16947. svr.Get("/", [&](const Request &req, Response &res) {
  16948. observed_within_cap = req.has_trailer(within_cap_name);
  16949. observed_past_cap = req.has_trailer(past_cap_name);
  16950. res.set_content("ok", "text/plain");
  16951. });
  16952. auto port = svr.bind_to_any_port(HOST);
  16953. thread t = thread([&]() { svr.listen_after_bind(); });
  16954. auto se = detail::scope_exit([&] {
  16955. svr.stop();
  16956. t.join();
  16957. ASSERT_FALSE(svr.is_running());
  16958. });
  16959. svr.wait_until_ready();
  16960. // Declare more trailer names than the cap in a single Trailer field, then
  16961. // actually send the first (within the cap) and the last (past it).
  16962. std::string trailer_decl = "Trailer: ";
  16963. for (int i = 0; i < declared_count; i++) {
  16964. if (i != 0) { trailer_decl += ", "; }
  16965. trailer_decl += "X-T-" + std::to_string(i);
  16966. }
  16967. trailer_decl += "\r\n";
  16968. const std::string req = "GET / HTTP/1.1\r\n"
  16969. "Transfer-Encoding: chunked\r\n" +
  16970. trailer_decl +
  16971. "\r\n"
  16972. "0\r\n" +
  16973. within_cap_name + ": a\r\n" + past_cap_name +
  16974. ": b\r\n"
  16975. "\r\n";
  16976. std::string res;
  16977. ASSERT_TRUE(send_request(1, req, &res, port));
  16978. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16979. // A name within the cap is honored; one declared past the cap is dropped.
  16980. EXPECT_TRUE(observed_within_cap);
  16981. EXPECT_FALSE(observed_past_cap);
  16982. }
  16983. // A direct client that is not listed in trusted_proxies must not be able to
  16984. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16985. // the peer address on the actual TCP connection determines whether the
  16986. // header is honored.
  16987. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16988. Server svr;
  16989. // Deliberately does NOT include the loopback address the test client
  16990. // actually connects from, so the direct connection is not a trusted proxy.
  16991. svr.set_trusted_proxies({"203.0.113.66"});
  16992. std::string observed_remote_addr;
  16993. svr.Get("/ip", [&](const Request &req, Response &res) {
  16994. observed_remote_addr = req.remote_addr;
  16995. res.set_content("ok", "text/plain");
  16996. });
  16997. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16998. auto se = detail::scope_exit([&] {
  16999. svr.stop();
  17000. t.join();
  17001. ASSERT_FALSE(svr.is_running());
  17002. });
  17003. svr.wait_until_ready();
  17004. Client cli(HOST, PORT);
  17005. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17007. EXPECT_EQ(StatusCode::OK_200, res->status);
  17008. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17009. // ignored entirely and the real connection-level address retained.
  17010. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17011. observed_remote_addr == "127.0.0.1");
  17012. }
  17013. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17014. Server svr;
  17015. std::string observed_remote_addr;
  17016. std::string observed_xff;
  17017. svr.Get("/ip", [&](const Request &req, Response &res) {
  17018. observed_remote_addr = req.remote_addr;
  17019. observed_xff = req.get_header_value("X-Forwarded-For");
  17020. res.set_content("ok", "text/plain");
  17021. });
  17022. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17023. auto se = detail::scope_exit([&] {
  17024. svr.stop();
  17025. t.join();
  17026. ASSERT_FALSE(svr.is_running());
  17027. });
  17028. svr.wait_until_ready();
  17029. Client cli(HOST, PORT);
  17030. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17032. EXPECT_EQ(StatusCode::OK_200, res->status);
  17033. EXPECT_EQ(observed_xff, "203.0.113.66");
  17034. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17035. observed_remote_addr == "127.0.0.1");
  17036. }
  17037. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17038. Server svr;
  17039. svr.set_trusted_proxies({"203.0.113.66"});
  17040. std::string observed_remote_addr;
  17041. std::string observed_xff;
  17042. svr.Get("/ip", [&](const Request &req, Response &res) {
  17043. observed_remote_addr = req.remote_addr;
  17044. observed_xff = req.get_header_value("X-Forwarded-For");
  17045. res.set_content("ok", "text/plain");
  17046. });
  17047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17048. auto se = detail::scope_exit([&] {
  17049. svr.stop();
  17050. t.join();
  17051. ASSERT_FALSE(svr.is_running());
  17052. });
  17053. svr.wait_until_ready();
  17054. Client cli(HOST, PORT);
  17055. auto res = cli.Get("/ip");
  17056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17057. EXPECT_EQ(StatusCode::OK_200, res->status);
  17058. EXPECT_EQ(observed_xff, "");
  17059. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17060. observed_remote_addr == "127.0.0.1");
  17061. }
  17062. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17063. Server svr;
  17064. // Include the loopback address the test client actually connects from, so
  17065. // the direct connection itself is recognized as the trusted proxy hop.
  17066. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17067. std::string observed_remote_addr;
  17068. std::string observed_xff;
  17069. svr.Get("/ip", [&](const Request &req, Response &res) {
  17070. observed_remote_addr = req.remote_addr;
  17071. observed_xff = req.get_header_value("X-Forwarded-For");
  17072. res.set_content("ok", "text/plain");
  17073. });
  17074. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17075. auto se = detail::scope_exit([&] {
  17076. svr.stop();
  17077. t.join();
  17078. ASSERT_FALSE(svr.is_running());
  17079. });
  17080. svr.wait_until_ready();
  17081. Client cli(HOST, PORT);
  17082. auto res = cli.Get(
  17083. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17085. EXPECT_EQ(StatusCode::OK_200, res->status);
  17086. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17087. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17088. }
  17089. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17090. Server svr;
  17091. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17092. std::string observed_remote_addr;
  17093. std::string observed_xff;
  17094. svr.Get("/ip", [&](const Request &req, Response &res) {
  17095. observed_remote_addr = req.remote_addr;
  17096. observed_xff = req.get_header_value("X-Forwarded-For");
  17097. res.set_content("ok", "text/plain");
  17098. });
  17099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17100. auto se = detail::scope_exit([&] {
  17101. svr.stop();
  17102. t.join();
  17103. ASSERT_FALSE(svr.is_running());
  17104. });
  17105. svr.wait_until_ready();
  17106. Client cli(HOST, PORT);
  17107. auto res = cli.Get(
  17108. "/ip",
  17109. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17111. EXPECT_EQ(StatusCode::OK_200, res->status);
  17112. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17113. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17114. }
  17115. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17116. Server svr;
  17117. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17118. std::string observed_remote_addr;
  17119. std::string observed_xff;
  17120. svr.Get("/ip", [&](const Request &req, Response &res) {
  17121. observed_remote_addr = req.remote_addr;
  17122. observed_xff = req.get_header_value("X-Forwarded-For");
  17123. res.set_content("ok", "text/plain");
  17124. });
  17125. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17126. auto se = detail::scope_exit([&] {
  17127. svr.stop();
  17128. t.join();
  17129. ASSERT_FALSE(svr.is_running());
  17130. });
  17131. svr.wait_until_ready();
  17132. Client cli(HOST, PORT);
  17133. auto res = cli.Get(
  17134. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17136. EXPECT_EQ(StatusCode::OK_200, res->status);
  17137. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17138. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17139. // and must not be selected.
  17140. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17141. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17142. }
  17143. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17144. Server svr;
  17145. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17146. std::string observed_remote_addr;
  17147. svr.Get("/ip", [&](const Request &req, Response &res) {
  17148. observed_remote_addr = req.remote_addr;
  17149. res.set_content("ok", "text/plain");
  17150. });
  17151. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17152. auto se = detail::scope_exit([&] {
  17153. svr.stop();
  17154. t.join();
  17155. ASSERT_FALSE(svr.is_running());
  17156. });
  17157. svr.wait_until_ready();
  17158. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17159. // a forged address and the trusted proxy's own address; the forged value must
  17160. // not win over the address the trusted proxy actually recorded.
  17161. Client cli(HOST, PORT);
  17162. auto res = cli.Get(
  17163. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17165. EXPECT_EQ(StatusCode::OK_200, res->status);
  17166. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17167. }
  17168. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17169. Server svr;
  17170. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17171. std::string observed_remote_addr;
  17172. std::string observed_xff;
  17173. svr.Get("/ip", [&](const Request &req, Response &res) {
  17174. observed_remote_addr = req.remote_addr;
  17175. observed_xff = req.get_header_value("X-Forwarded-For");
  17176. res.set_content("ok", "text/plain");
  17177. });
  17178. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17179. auto se = detail::scope_exit([&] {
  17180. svr.stop();
  17181. t.join();
  17182. ASSERT_FALSE(svr.is_running());
  17183. });
  17184. svr.wait_until_ready();
  17185. Client cli(HOST, PORT);
  17186. auto res = cli.Get(
  17187. "/ip",
  17188. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17190. EXPECT_EQ(StatusCode::OK_200, res->status);
  17191. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17192. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17193. }
  17194. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17195. Server svr;
  17196. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17197. std::string observed_remote_addr;
  17198. std::string observed_xff;
  17199. svr.Get("/ip", [&](const Request &req, Response &res) {
  17200. observed_remote_addr = req.remote_addr;
  17201. observed_xff = req.get_header_value("X-Forwarded-For");
  17202. res.set_content("ok", "text/plain");
  17203. });
  17204. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17205. auto se = detail::scope_exit([&] {
  17206. svr.stop();
  17207. t.join();
  17208. ASSERT_FALSE(svr.is_running());
  17209. });
  17210. svr.wait_until_ready();
  17211. std::string raw_req =
  17212. "GET /ip HTTP/1.1\r\n"
  17213. "Host: localhost\r\n"
  17214. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17215. "Connection: close\r\n"
  17216. "\r\n";
  17217. std::string out;
  17218. ASSERT_TRUE(send_request(5, raw_req, &out));
  17219. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17220. // Header parser trims surrounding whitespace of the header value
  17221. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17222. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17223. }
  17224. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17225. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17226. // their own X-Forwarded-For as a separate field line rather than extending the
  17227. // one the client sent, so every occurrence has to be taken into account.
  17228. // Reading only the first one hands back the address the client chose.
  17229. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17230. Server svr;
  17231. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17232. std::string observed_remote_addr;
  17233. size_t observed_xff_count = 0;
  17234. svr.Get("/ip", [&](const Request &req, Response &res) {
  17235. observed_remote_addr = req.remote_addr;
  17236. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17237. res.set_content("ok", "text/plain");
  17238. });
  17239. auto port = svr.bind_to_any_port(HOST);
  17240. thread t = thread([&]() { svr.listen_after_bind(); });
  17241. auto se = detail::scope_exit([&] {
  17242. svr.stop();
  17243. t.join();
  17244. ASSERT_FALSE(svr.is_running());
  17245. });
  17246. svr.wait_until_ready();
  17247. // The client supplies the first field line; the trusted proxy appends the
  17248. // address it observed as a second one.
  17249. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17250. "Host: localhost\r\n"
  17251. "X-Forwarded-For: 1.2.3.4\r\n"
  17252. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17253. "Connection: close\r\n"
  17254. "\r\n";
  17255. std::string out;
  17256. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17257. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17258. EXPECT_EQ(observed_xff_count, 2U);
  17259. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17260. // The same chain spread over one field line per hop derives the same client
  17261. // address, i.e. the split and the comma-joined representations agree.
  17262. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17263. "Host: localhost\r\n"
  17264. "X-Forwarded-For: 1.2.3.4\r\n"
  17265. "X-Forwarded-For: 198.51.100.23\r\n"
  17266. "X-Forwarded-For: 192.0.2.45\r\n"
  17267. "Connection: close\r\n"
  17268. "\r\n";
  17269. out.clear();
  17270. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17271. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17272. EXPECT_EQ(observed_xff_count, 3U);
  17273. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17274. }
  17275. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17276. // crash the server (it used to call front() on an empty vector inside
  17277. // get_client_ip). The connection-level remote address must be retained instead.
  17278. static void run_malformed_xff_test(const std::string &xff_value) {
  17279. Server svr;
  17280. svr.set_trusted_proxies({"192.0.2.45"});
  17281. std::string observed_remote_addr;
  17282. svr.Get("/ip", [&](const Request &req, Response &res) {
  17283. observed_remote_addr = req.remote_addr;
  17284. res.set_content("ok", "text/plain");
  17285. });
  17286. int port = 0;
  17287. thread t = thread([&]() {
  17288. port = svr.bind_to_any_port(HOST);
  17289. svr.listen_after_bind();
  17290. });
  17291. auto se = detail::scope_exit([&] {
  17292. svr.stop();
  17293. t.join();
  17294. ASSERT_FALSE(svr.is_running());
  17295. });
  17296. svr.wait_until_ready();
  17297. Client cli(HOST, port);
  17298. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17300. EXPECT_EQ(StatusCode::OK_200, res->status);
  17301. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17302. observed_remote_addr == "127.0.0.1");
  17303. }
  17304. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17305. run_malformed_xff_test("");
  17306. }
  17307. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17308. run_malformed_xff_test(",");
  17309. }
  17310. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17311. run_malformed_xff_test(", , ,");
  17312. }
  17313. // The same rule applies to Accept: a request whose acceptable types are spread
  17314. // over several field lines must be negotiated against all of them.
  17315. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17316. // case-insensitive connection options. Comparing the whole field value against
  17317. // one option misses a client that sends several of them, and misses every
  17318. // casing but the one written in the comparison.
  17319. //
  17320. // Sends req, reads the response, then reuses the same socket for a second
  17321. // request to find out whether the server kept the connection.
  17322. static void probe_connection_reuse(int port, const std::string &req,
  17323. bool *announced_close, bool *reusable) {
  17324. auto error = Error::Success;
  17325. auto sock = detail::create_client_socket(
  17326. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17327. /*connection_timeout_sec=*/5, 0,
  17328. /*read_timeout_sec=*/1, 0,
  17329. /*write_timeout_sec=*/5, 0, std::string(), error);
  17330. ASSERT_NE(sock, INVALID_SOCKET);
  17331. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17332. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17333. "Host: localhost\r\n"
  17334. "Connection: close\r\n"
  17335. "\r\n";
  17336. std::string first_response;
  17337. std::string second_response;
  17338. detail::process_client_socket(
  17339. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17340. [&](Stream &strm) {
  17341. if (strm.write(req.data(), req.size()) !=
  17342. static_cast<ssize_t>(req.size())) {
  17343. return false;
  17344. }
  17345. char buf[512];
  17346. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17347. // Headers plus the two-byte body of the handler below
  17348. while (reader.getline()) {
  17349. first_response += reader.ptr();
  17350. if (first_response.find("ok") != std::string::npos) { break; }
  17351. }
  17352. if (strm.write(second.data(), second.size()) !=
  17353. static_cast<ssize_t>(second.size())) {
  17354. return true;
  17355. }
  17356. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17357. while (reader2.getline()) {
  17358. second_response += reader2.ptr();
  17359. if (second_response.find("ok") != std::string::npos) { break; }
  17360. }
  17361. return true;
  17362. });
  17363. *announced_close =
  17364. first_response.find("Connection: close") != std::string::npos;
  17365. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17366. }
  17367. class ConnectionTokenTest : public ::testing::Test {
  17368. protected:
  17369. void SetUp() override {
  17370. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17371. res.set_content("ok", "text/plain");
  17372. });
  17373. port_ = svr_.bind_to_any_port(HOST);
  17374. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17375. svr_.wait_until_ready();
  17376. }
  17377. void TearDown() override {
  17378. svr_.stop();
  17379. if (thread_.joinable()) { thread_.join(); }
  17380. }
  17381. Server svr_;
  17382. int port_ = 0;
  17383. thread thread_;
  17384. };
  17385. // "close" alongside another option still closes the connection, and the
  17386. // response says so rather than leaving the peer to discover it.
  17387. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17388. bool announced_close = false;
  17389. bool reusable = true;
  17390. probe_connection_reuse(port_,
  17391. "GET /keepalive HTTP/1.1\r\n"
  17392. "Host: localhost\r\n"
  17393. "Connection: keep-alive, close\r\n"
  17394. "\r\n",
  17395. &announced_close, &reusable);
  17396. EXPECT_TRUE(announced_close);
  17397. EXPECT_FALSE(reusable);
  17398. }
  17399. // "close" split over two field lines is the same list, so it is honored too.
  17400. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17401. bool announced_close = false;
  17402. bool reusable = true;
  17403. probe_connection_reuse(port_,
  17404. "GET /keepalive HTTP/1.1\r\n"
  17405. "Host: localhost\r\n"
  17406. "Connection: keep-alive\r\n"
  17407. "Connection: close\r\n"
  17408. "\r\n",
  17409. &announced_close, &reusable);
  17410. EXPECT_TRUE(announced_close);
  17411. EXPECT_FALSE(reusable);
  17412. }
  17413. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17414. // keep-alive in the spelling everyone actually sends keeps its connection.
  17415. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17416. bool announced_close = false;
  17417. bool reusable = false;
  17418. probe_connection_reuse(port_,
  17419. "GET /keepalive HTTP/1.0\r\n"
  17420. "Host: localhost\r\n"
  17421. "Connection: keep-alive\r\n"
  17422. "\r\n",
  17423. &announced_close, &reusable);
  17424. EXPECT_FALSE(announced_close);
  17425. EXPECT_TRUE(reusable);
  17426. }
  17427. // A token the value merely contains is not the token itself.
  17428. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17429. bool announced_close = false;
  17430. bool reusable = false;
  17431. probe_connection_reuse(port_,
  17432. "GET /keepalive HTTP/1.1\r\n"
  17433. "Host: localhost\r\n"
  17434. "Connection: notclose\r\n"
  17435. "\r\n",
  17436. &announced_close, &reusable);
  17437. EXPECT_FALSE(announced_close);
  17438. EXPECT_TRUE(reusable);
  17439. }
  17440. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17441. Server svr;
  17442. std::vector<std::string> observed_types;
  17443. svr.Get("/", [&](const Request &req, Response &res) {
  17444. observed_types = req.accept_content_types;
  17445. res.set_content("ok", "text/plain");
  17446. });
  17447. auto port = svr.bind_to_any_port(HOST);
  17448. thread t = thread([&]() { svr.listen_after_bind(); });
  17449. auto se = detail::scope_exit([&] {
  17450. svr.stop();
  17451. t.join();
  17452. ASSERT_FALSE(svr.is_running());
  17453. });
  17454. svr.wait_until_ready();
  17455. Client cli(HOST, port);
  17456. Headers headers;
  17457. headers.emplace("Accept", "text/plain;q=0.5");
  17458. headers.emplace("Accept", "application/json");
  17459. auto res = cli.Get("/", headers);
  17460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17461. EXPECT_EQ(StatusCode::OK_200, res->status);
  17462. // Sorted by q-value, so the second field line's type comes first
  17463. ASSERT_EQ(2U, observed_types.size());
  17464. EXPECT_EQ("application/json", observed_types[0]);
  17465. EXPECT_EQ("text/plain", observed_types[1]);
  17466. }
  17467. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17468. // empty field line must not contribute a bare comma to the combined value.
  17469. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17470. Server svr;
  17471. std::vector<std::string> observed_types;
  17472. svr.Get("/", [&](const Request &req, Response &res) {
  17473. observed_types = req.accept_content_types;
  17474. res.set_content("ok", "text/plain");
  17475. });
  17476. auto port = svr.bind_to_any_port(HOST);
  17477. thread t = thread([&]() { svr.listen_after_bind(); });
  17478. auto se = detail::scope_exit([&] {
  17479. svr.stop();
  17480. t.join();
  17481. ASSERT_FALSE(svr.is_running());
  17482. });
  17483. svr.wait_until_ready();
  17484. // Empty first field line, then a real one
  17485. std::string raw_req = "GET / HTTP/1.1\r\n"
  17486. "Host: localhost\r\n"
  17487. "Accept:\r\n"
  17488. "Accept: application/json\r\n"
  17489. "Connection: close\r\n"
  17490. "\r\n";
  17491. std::string out;
  17492. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17493. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17494. ASSERT_EQ(1U, observed_types.size());
  17495. EXPECT_EQ("application/json", observed_types[0]);
  17496. }
  17497. // The skip in get_combined_header_value() is what keeps an empty field line
  17498. // from contributing a bare comma. Only a trailing empty field line exercises
  17499. // it: a leading one is already covered by the "combined is still empty" check,
  17500. // and parse_accept_header() now ignores the empty element either way, so the
  17501. // request-level test above can no longer tell the two apart.
  17502. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17503. Headers headers;
  17504. headers.emplace("Accept", "text/html");
  17505. headers.emplace("Accept", "");
  17506. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17507. headers.clear();
  17508. headers.emplace("Accept", "");
  17509. headers.emplace("Accept", "application/json");
  17510. EXPECT_EQ("application/json",
  17511. detail::get_combined_header_value(headers, "Accept"));
  17512. }
  17513. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17514. // An encoding offered on a later Accept-Encoding field line is still offered.
  17515. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17516. Server svr;
  17517. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17518. res.set_content(std::string(1024, 'x'), "text/plain");
  17519. });
  17520. auto port = svr.bind_to_any_port(HOST);
  17521. thread t = thread([&]() { svr.listen_after_bind(); });
  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. cli.set_decompress(false);
  17530. Headers headers;
  17531. headers.emplace("Accept-Encoding", "identity");
  17532. headers.emplace("Accept-Encoding", "gzip");
  17533. auto res = cli.Get("/", headers);
  17534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17535. EXPECT_EQ(StatusCode::OK_200, res->status);
  17536. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17537. }
  17538. #endif
  17539. #ifndef _WIN32
  17540. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17541. Server svr;
  17542. svr.Post("/post", [&](const Request &req, Response &res) {
  17543. res.set_content(req.body, "text/plain");
  17544. });
  17545. svr.Put("/put", [&](const Request &req, Response &res) {
  17546. res.set_content(req.body, "text/plain");
  17547. });
  17548. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17549. res.set_content(req.body, "text/plain");
  17550. });
  17551. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17552. res.set_content(req.body, "text/plain");
  17553. });
  17554. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17555. auto se = detail::scope_exit([&] {
  17556. svr.stop();
  17557. t.join();
  17558. ASSERT_FALSE(svr.is_running());
  17559. });
  17560. svr.wait_until_ready();
  17561. std::string resp;
  17562. // POST without Content-Length
  17563. ASSERT_TRUE(send_request(5,
  17564. "POST /post HTTP/1.1\r\n"
  17565. "Host: localhost\r\n"
  17566. "Connection: close\r\n"
  17567. "\r\n",
  17568. &resp));
  17569. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17570. // PUT without Content-Length
  17571. resp.clear();
  17572. ASSERT_TRUE(send_request(5,
  17573. "PUT /put HTTP/1.1\r\n"
  17574. "Host: localhost\r\n"
  17575. "Connection: close\r\n"
  17576. "\r\n",
  17577. &resp));
  17578. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17579. // PATCH without Content-Length
  17580. resp.clear();
  17581. ASSERT_TRUE(send_request(5,
  17582. "PATCH /patch HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Connection: close\r\n"
  17585. "\r\n",
  17586. &resp));
  17587. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17588. // DELETE without Content-Length
  17589. resp.clear();
  17590. ASSERT_TRUE(send_request(5,
  17591. "DELETE /delete HTTP/1.1\r\n"
  17592. "Host: localhost\r\n"
  17593. "Connection: close\r\n"
  17594. "\r\n",
  17595. &resp));
  17596. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17597. }
  17598. #endif
  17599. //==============================================================================
  17600. // open_stream() Tests
  17601. //==============================================================================
  17602. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17603. std::string result;
  17604. char buf[8192];
  17605. ssize_t n;
  17606. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17607. result.append(buf, static_cast<size_t>(n));
  17608. }
  17609. return result;
  17610. }
  17611. // Mock stream for unit tests
  17612. class MockStream : public Stream {
  17613. public:
  17614. std::string data;
  17615. size_t pos = 0;
  17616. ssize_t error_after = -1; // -1 = no error
  17617. explicit MockStream(const std::string &d, ssize_t err = -1)
  17618. : data(d), error_after(err) {}
  17619. bool is_readable() const override { return true; }
  17620. bool wait_readable() const override { return true; }
  17621. bool wait_writable() const override { return true; }
  17622. ssize_t read(char *ptr, size_t size) override {
  17623. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17624. if (pos >= data.size()) return 0;
  17625. size_t limit =
  17626. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17627. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17628. std::memcpy(ptr, data.data() + pos, to_read);
  17629. pos += to_read;
  17630. return static_cast<ssize_t>(to_read);
  17631. }
  17632. ssize_t write(const char *, size_t) override { return -1; }
  17633. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17634. ip = "127.0.0.1";
  17635. port = 0;
  17636. }
  17637. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17638. ip = "127.0.0.1";
  17639. port = 0;
  17640. }
  17641. socket_t socket() const override { return INVALID_SOCKET; }
  17642. time_t duration() const override { return 0; }
  17643. };
  17644. TEST(StreamHandleTest, Basic) {
  17645. ClientImpl::StreamHandle handle;
  17646. EXPECT_FALSE(handle.is_valid());
  17647. handle.response = detail::make_unique<Response>();
  17648. handle.error = Error::Connection;
  17649. EXPECT_FALSE(handle.is_valid());
  17650. handle.error = Error::Success;
  17651. EXPECT_TRUE(handle.is_valid());
  17652. }
  17653. TEST(BodyReaderTest, Basic) {
  17654. MockStream stream("Hello, World!");
  17655. detail::BodyReader reader;
  17656. reader.stream = &stream;
  17657. reader.content_length = 13;
  17658. char buf[32];
  17659. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17660. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17661. EXPECT_TRUE(reader.eof);
  17662. }
  17663. TEST(BodyReaderTest, NoStream) {
  17664. detail::BodyReader reader;
  17665. char buf[32];
  17666. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17667. EXPECT_EQ(Error::Connection, reader.last_error);
  17668. }
  17669. TEST(BodyReaderTest, Error) {
  17670. MockStream stream("Hello, World!", 5);
  17671. detail::BodyReader reader;
  17672. reader.stream = &stream;
  17673. reader.content_length = 13;
  17674. char buf[32];
  17675. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17676. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17677. EXPECT_EQ(Error::Read, reader.last_error);
  17678. }
  17679. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17680. // Mock-based StreamHandle tests relying on private internals are removed.
  17681. class OpenStreamTest : public ::testing::Test {
  17682. protected:
  17683. void SetUp() override {
  17684. svr_.Get("/hello", [](const Request &, Response &res) {
  17685. res.set_content("Hello World!", "text/plain");
  17686. });
  17687. svr_.Get("/large", [](const Request &, Response &res) {
  17688. res.set_content(std::string(10000, 'X'), "text/plain");
  17689. });
  17690. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17691. res.set_content("Hello World!", "image/jpeg");
  17692. res.set_header("Content-Encoding", "UTF-8");
  17693. });
  17694. svr_.Get("/chunked", [](const Request &, Response &res) {
  17695. res.set_chunked_content_provider("text/plain",
  17696. [](size_t offset, DataSink &sink) {
  17697. if (offset < 15) {
  17698. sink.write("chunk", 5);
  17699. return true;
  17700. }
  17701. sink.done();
  17702. return true;
  17703. });
  17704. });
  17705. svr_.Get("/compressible", [](const Request &, Response &res) {
  17706. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17707. DataSink &sink) {
  17708. if (offset < 100 * 1024) {
  17709. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17710. sink.write(chunk.data(), chunk.size());
  17711. return true;
  17712. }
  17713. sink.done();
  17714. return true;
  17715. });
  17716. });
  17717. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17718. [](const Request & /*req*/, Response &res) {
  17719. auto i = new int(0);
  17720. res.set_header("Trailer", "Content-Length, X-Allowed");
  17721. res.set_chunked_content_provider(
  17722. "text/plain",
  17723. [i](size_t /*offset*/, DataSink &sink) {
  17724. switch (*i) {
  17725. case 0: sink.os << "123"; break;
  17726. case 1: sink.os << "456"; break;
  17727. case 2: sink.os << "789"; break;
  17728. case 3: {
  17729. sink.done_with_trailer(
  17730. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17731. } break;
  17732. }
  17733. (*i)++;
  17734. return true;
  17735. },
  17736. [i](bool success) {
  17737. EXPECT_TRUE(success);
  17738. delete i;
  17739. });
  17740. });
  17741. // Echo headers endpoint for header-related tests
  17742. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17743. std::string body;
  17744. for (const auto &h : req.headers) {
  17745. body.append(h.first);
  17746. body.push_back(':');
  17747. body.append(h.second);
  17748. body.push_back('\n');
  17749. }
  17750. res.set_content(body, "text/plain");
  17751. });
  17752. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17753. std::string body;
  17754. for (const auto &h : req.headers) {
  17755. body.append(h.first);
  17756. body.push_back(':');
  17757. body.append(h.second);
  17758. body.push_back('\n');
  17759. }
  17760. res.set_content(body, "text/plain");
  17761. });
  17762. port_ = svr_.bind_to_any_port("127.0.0.1");
  17763. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17764. svr_.wait_until_ready();
  17765. }
  17766. void TearDown() override {
  17767. svr_.stop();
  17768. if (thread_.joinable()) thread_.join();
  17769. }
  17770. Server svr_;
  17771. std::thread thread_;
  17772. int port_ = 0;
  17773. };
  17774. TEST_F(OpenStreamTest, Basic) {
  17775. Client cli("127.0.0.1", port_);
  17776. auto handle = cli.open_stream("GET", "/hello");
  17777. EXPECT_TRUE(handle.is_valid());
  17778. EXPECT_EQ("Hello World!", read_all(handle));
  17779. }
  17780. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17781. Client cli("127.0.0.1", port_);
  17782. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17783. ASSERT_TRUE(handle.is_valid());
  17784. EXPECT_EQ("Hello World!", read_all(handle));
  17785. }
  17786. TEST_F(OpenStreamTest, SmallBuffer) {
  17787. Client cli("127.0.0.1", port_);
  17788. auto handle = cli.open_stream("GET", "/hello");
  17789. std::string result;
  17790. char buf[4];
  17791. ssize_t n;
  17792. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17793. result.append(buf, static_cast<size_t>(n));
  17794. EXPECT_EQ("Hello World!", result);
  17795. }
  17796. TEST_F(OpenStreamTest, DefaultHeaders) {
  17797. Client cli("127.0.0.1", port_);
  17798. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17799. {
  17800. auto handle = cli.open_stream("GET", "/echo-headers");
  17801. ASSERT_TRUE(handle.is_valid());
  17802. auto body = read_all(handle);
  17803. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17804. std::string::npos);
  17805. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17806. std::string::npos);
  17807. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17808. }
  17809. // open_stream POST with body and no explicit content_type should NOT add
  17810. // text/plain Content-Type (behavior differs from non-streaming path), but
  17811. // should include Content-Length
  17812. {
  17813. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17814. ASSERT_TRUE(handle.is_valid());
  17815. auto body = read_all(handle);
  17816. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17817. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17818. }
  17819. // open_stream POST with explicit Content-Type should preserve it
  17820. {
  17821. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17822. {{"Content-Type", "application/custom"}},
  17823. "{}", "application/custom");
  17824. ASSERT_TRUE(handle.is_valid());
  17825. auto body = read_all(handle);
  17826. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17827. }
  17828. // User-specified User-Agent must not be overwritten for stream API
  17829. {
  17830. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17831. {{"User-Agent", "MyAgent/1.2"}});
  17832. ASSERT_TRUE(handle.is_valid());
  17833. auto body = read_all(handle);
  17834. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17835. }
  17836. }
  17837. TEST_F(OpenStreamTest, Large) {
  17838. Client cli("127.0.0.1", port_);
  17839. auto handle = cli.open_stream("GET", "/large");
  17840. EXPECT_EQ(10000u, read_all(handle).size());
  17841. }
  17842. TEST_F(OpenStreamTest, ConnectionError) {
  17843. Client cli("127.0.0.1", 9999);
  17844. auto handle = cli.open_stream("GET", "/hello");
  17845. EXPECT_FALSE(handle.is_valid());
  17846. }
  17847. TEST_F(OpenStreamTest, Chunked) {
  17848. Client cli("127.0.0.1", port_);
  17849. auto handle = cli.open_stream("GET", "/chunked");
  17850. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17851. "Transfer-Encoding") == "chunked");
  17852. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17853. }
  17854. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17855. Client cli("127.0.0.1", port_);
  17856. auto handle =
  17857. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17858. ASSERT_TRUE(handle.is_valid());
  17859. // Consume body to allow trailers to be received/parsed
  17860. auto body = read_all(handle);
  17861. // Explicitly parse trailers (ensure trailers are available for assertion)
  17862. handle.parse_trailers_if_needed();
  17863. EXPECT_EQ(std::string("123456789"), body);
  17864. // The response should include a Trailer header declaring both names
  17865. ASSERT_TRUE(handle.response);
  17866. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17867. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17868. handle.response->get_header_value("Trailer"));
  17869. // Prohibited trailer must not be present
  17870. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17871. // Allowed trailer should be present
  17872. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17873. EXPECT_EQ(std::string("yes"),
  17874. handle.response->get_trailer_value("X-Allowed"));
  17875. // Verify trailers are NOT present as regular headers
  17876. EXPECT_EQ(std::string(""),
  17877. handle.response->get_header_value("Content-Length"));
  17878. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17879. }
  17880. static std::thread serve_single_response(std::promise<int> &port_promise,
  17881. const std::string &response) {
  17882. return std::thread([&port_promise, response] {
  17883. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17884. default_socket_options(srv);
  17885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17887. sockaddr_in addr{};
  17888. addr.sin_family = AF_INET;
  17889. addr.sin_port = htons(0); // Let OS assign a free port
  17890. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17891. int opt = 1;
  17892. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17893. #ifdef _WIN32
  17894. reinterpret_cast<const char *>(&opt),
  17895. #else
  17896. &opt,
  17897. #endif
  17898. sizeof(opt));
  17899. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17900. ::listen(srv, 1) != 0) {
  17901. port_promise.set_value(-1);
  17902. detail::close_socket(srv);
  17903. return;
  17904. }
  17905. socklen_t addr_len = sizeof(addr);
  17906. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17907. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17908. sockaddr_in cli_addr{};
  17909. socklen_t cli_len = sizeof(cli_addr);
  17910. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17911. if (cli != INVALID_SOCKET) {
  17912. // Read the complete HTTP request (until the blank line that terminates
  17913. // headers) before sending the response. If the server closes the socket
  17914. // while the client's request data is still unread in the kernel receive
  17915. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17916. // connection on both sides: it discards the client's receive buffer
  17917. // (which already holds our response) and causes any in-progress write on
  17918. // the client to fail with ECONNRESET. Reading all request data first
  17919. // ensures close() emits a graceful FIN.
  17920. {
  17921. char rbuf[256];
  17922. std::string req;
  17923. while (req.find("\r\n\r\n") == std::string::npos) {
  17924. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17925. if (n <= 0) { break; }
  17926. req.append(rbuf, static_cast<size_t>(n));
  17927. }
  17928. }
  17929. ::send(cli,
  17930. #ifdef _WIN32
  17931. static_cast<const char *>(response.c_str()),
  17932. static_cast<int>(response.size()),
  17933. #else
  17934. response.c_str(), response.size(),
  17935. #endif
  17936. 0);
  17937. detail::close_socket(cli);
  17938. }
  17939. detail::close_socket(srv);
  17940. });
  17941. }
  17942. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17943. #ifndef _WIN32
  17944. signal(SIGPIPE, SIG_IGN);
  17945. #endif
  17946. std::promise<int> port_promise;
  17947. auto port_future = port_promise.get_future();
  17948. auto server_thread =
  17949. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17950. "Content-Type: text/plain\r\n"
  17951. "Content-Length: not-a-number\r\n"
  17952. "Connection: close\r\n"
  17953. "\r\n"
  17954. "hello");
  17955. auto port = port_future.get();
  17956. ASSERT_GT(port, 0);
  17957. Client cli("127.0.0.1", port);
  17958. auto handle = cli.open_stream("GET", "/");
  17959. EXPECT_FALSE(handle.is_valid());
  17960. server_thread.join();
  17961. }
  17962. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17963. #ifndef _WIN32
  17964. signal(SIGPIPE, SIG_IGN);
  17965. #endif
  17966. std::promise<int> port_promise;
  17967. auto port_future = port_promise.get_future();
  17968. auto server_thread = serve_single_response(
  17969. port_promise, "HTTP/1.1 200 OK\r\n"
  17970. "Content-Type: text/plain\r\n"
  17971. "Content-Length: 99999999999999999999999999\r\n"
  17972. "Connection: close\r\n"
  17973. "\r\n"
  17974. "hello");
  17975. auto port = port_future.get();
  17976. ASSERT_GT(port, 0);
  17977. // Historically std::stoull would throw std::out_of_range here and crash
  17978. // the process, then parsing silently clamped to a bogus framing length and
  17979. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17980. // so the stream fails to open, matching the not-a-number case above. The
  17981. // process still must NOT terminate.
  17982. Client cli("127.0.0.1", port);
  17983. auto handle = cli.open_stream("GET", "/");
  17984. EXPECT_FALSE(handle.is_valid());
  17985. server_thread.join();
  17986. }
  17987. // Serves `response` to the single request `fn` makes with a fresh client.
  17988. template <typename Fn>
  17989. static void with_single_response(const std::string &response, Fn fn) {
  17990. #ifndef _WIN32
  17991. signal(SIGPIPE, SIG_IGN);
  17992. #endif
  17993. std::promise<int> port_promise;
  17994. auto port_future = port_promise.get_future();
  17995. auto server_thread = serve_single_response(port_promise, response);
  17996. auto se = detail::scope_exit([&] { server_thread.join(); });
  17997. auto port = port_future.get();
  17998. ASSERT_GT(port, 0);
  17999. Client cli("127.0.0.1", port);
  18000. fn(cli);
  18001. }
  18002. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18003. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18004. // the chunked coding and drop Content-Length, so a front-end that trusts
  18005. // Content-Length would disagree about where the body ends (response
  18006. // smuggling). The client must reject such a response.
  18007. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18008. for (const char *te : {"chunked", "gzip, chunked"}) {
  18009. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18010. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18011. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18012. "5\r\nhello\r\n0\r\n\r\n";
  18013. with_single_response(response, [&](Client &cli) {
  18014. auto res = cli.Get("/");
  18015. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18016. EXPECT_EQ(Error::Read, res.error()) << te;
  18017. });
  18018. with_single_response(response, [&](Client &cli) {
  18019. auto handle = cli.open_stream("GET", "/");
  18020. EXPECT_FALSE(handle.is_valid()) << te;
  18021. EXPECT_EQ(Error::Read, handle.error) << te;
  18022. });
  18023. }
  18024. }
  18025. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18026. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18027. // closing the connection (unlike a request, which must be rejected).
  18028. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18029. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18030. "Transfer-Encoding: chunked\r\n"
  18031. "Connection: close\r\n"
  18032. "\r\n"
  18033. "5\r\nhello\r\n0\r\n\r\n",
  18034. "HTTP/1.1 200 OK\r\n"
  18035. "Transfer-Encoding: gzip\r\n"
  18036. "Connection: close\r\n"
  18037. "\r\n"
  18038. "hello"}) {
  18039. with_single_response(response, [&](Client &cli) {
  18040. auto res = cli.Get("/");
  18041. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18042. EXPECT_EQ("hello", res->body);
  18043. });
  18044. with_single_response(response, [&](Client &cli) {
  18045. auto handle = cli.open_stream("GET", "/");
  18046. ASSERT_TRUE(handle.is_valid()) << response;
  18047. EXPECT_EQ("hello", read_all(handle));
  18048. });
  18049. }
  18050. }
  18051. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18052. // framing headers describe nothing to read and must not be rejected.
  18053. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18054. const std::string framing = "Content-Length: 5\r\n"
  18055. "Transfer-Encoding: chunked\r\n"
  18056. "Connection: close\r\n"
  18057. "\r\n";
  18058. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18059. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18060. });
  18061. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18062. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18063. });
  18064. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18065. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18066. with_single_response(response, [&](Client &cli) {
  18067. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18068. });
  18069. with_single_response(response, [&](Client &cli) {
  18070. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18071. });
  18072. }
  18073. }
  18074. // A payload max length of 0 means no limit, however the body is framed.
  18075. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18076. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18077. "Transfer-Encoding: chunked\r\n"
  18078. "\r\n"
  18079. "5\r\nhello\r\n0\r\n\r\n",
  18080. "HTTP/1.1 200 OK\r\n"
  18081. "Connection: close\r\n"
  18082. "\r\n"
  18083. "hello"}) {
  18084. with_single_response(response, [&](Client &cli) {
  18085. cli.set_payload_max_length(0);
  18086. auto res = cli.Get("/");
  18087. ASSERT_TRUE(res) << response;
  18088. EXPECT_EQ("hello", res->body) << response;
  18089. });
  18090. }
  18091. }
  18092. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18093. Server svr;
  18094. svr.set_payload_max_length(0);
  18095. svr.Post("/echo", [](const Request &req, Response &res) {
  18096. res.set_content(req.body, "text/plain");
  18097. });
  18098. auto port = svr.bind_to_any_port(HOST);
  18099. thread t = thread([&] { svr.listen_after_bind(); });
  18100. auto se = detail::scope_exit([&] {
  18101. svr.stop();
  18102. t.join();
  18103. ASSERT_FALSE(svr.is_running());
  18104. });
  18105. svr.wait_until_ready();
  18106. Client cli(HOST, port);
  18107. auto res = cli.Post(
  18108. "/echo",
  18109. [](size_t /*offset*/, DataSink &sink) {
  18110. sink.write("hello", 5);
  18111. sink.done();
  18112. return true;
  18113. },
  18114. "text/plain");
  18115. ASSERT_TRUE(res);
  18116. EXPECT_EQ(StatusCode::OK_200, res->status);
  18117. EXPECT_EQ("hello", res->body);
  18118. }
  18119. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18120. TEST_F(OpenStreamTest, Gzip) {
  18121. Client cli("127.0.0.1", port_);
  18122. auto handle = cli.open_stream("GET", "/compressible", {},
  18123. {{"Accept-Encoding", "gzip"}});
  18124. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18125. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18126. }
  18127. #endif
  18128. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18129. TEST_F(OpenStreamTest, Brotli) {
  18130. Client cli("127.0.0.1", port_);
  18131. auto handle =
  18132. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18133. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18134. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18135. }
  18136. #endif
  18137. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18138. TEST_F(OpenStreamTest, Zstd) {
  18139. Client cli("127.0.0.1", port_);
  18140. auto handle = cli.open_stream("GET", "/compressible", {},
  18141. {{"Accept-Encoding", "zstd"}});
  18142. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18143. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18144. }
  18145. #endif
  18146. #ifdef CPPHTTPLIB_SSL_ENABLED
  18147. class SSLOpenStreamTest : public ::testing::Test {
  18148. protected:
  18149. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18150. void SetUp() override {
  18151. svr_.Get("/hello", [](const Request &, Response &res) {
  18152. res.set_content("Hello SSL World!", "text/plain");
  18153. });
  18154. svr_.Get("/chunked", [](const Request &, Response &res) {
  18155. res.set_chunked_content_provider("text/plain",
  18156. [](size_t offset, DataSink &sink) {
  18157. if (offset < 15) {
  18158. sink.write("chunk", 5);
  18159. return true;
  18160. }
  18161. sink.done();
  18162. return true;
  18163. });
  18164. });
  18165. svr_.Post("/echo", [](const Request &req, Response &res) {
  18166. res.set_content(req.body, req.get_header_value("Content-Type"));
  18167. });
  18168. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18169. std::string body = req.body;
  18170. res.set_chunked_content_provider(
  18171. "text/plain", [body](size_t offset, DataSink &sink) {
  18172. if (offset < body.size()) {
  18173. sink.write(body.data() + offset, body.size() - offset);
  18174. }
  18175. sink.done();
  18176. return true;
  18177. });
  18178. });
  18179. port_ = svr_.bind_to_any_port("127.0.0.1");
  18180. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18181. svr_.wait_until_ready();
  18182. }
  18183. void TearDown() override {
  18184. svr_.stop();
  18185. if (thread_.joinable()) thread_.join();
  18186. }
  18187. SSLServer svr_;
  18188. std::thread thread_;
  18189. int port_ = 0;
  18190. };
  18191. TEST_F(SSLOpenStreamTest, Basic) {
  18192. SSLClient cli("127.0.0.1", port_);
  18193. cli.enable_server_certificate_verification(false);
  18194. auto handle = cli.open_stream("GET", "/hello");
  18195. ASSERT_TRUE(handle.is_valid());
  18196. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18197. }
  18198. TEST_F(SSLOpenStreamTest, Chunked) {
  18199. SSLClient cli("127.0.0.1", port_);
  18200. cli.enable_server_certificate_verification(false);
  18201. auto handle = cli.open_stream("GET", "/chunked");
  18202. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18203. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18204. "Transfer-Encoding") == "chunked");
  18205. auto body = read_all(handle);
  18206. EXPECT_EQ("chunkchunkchunk", body);
  18207. }
  18208. TEST_F(SSLOpenStreamTest, Post) {
  18209. SSLClient cli("127.0.0.1", port_);
  18210. cli.enable_server_certificate_verification(false);
  18211. auto handle =
  18212. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18213. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18214. EXPECT_EQ(200, handle.response->status);
  18215. auto body = read_all(handle);
  18216. EXPECT_EQ("Hello SSL POST", body);
  18217. }
  18218. TEST_F(SSLOpenStreamTest, PostChunked) {
  18219. SSLClient cli("127.0.0.1", port_);
  18220. cli.enable_server_certificate_verification(false);
  18221. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18222. "Chunked SSL Data", "text/plain");
  18223. ASSERT_TRUE(handle.is_valid());
  18224. EXPECT_EQ(200, handle.response->status);
  18225. auto body = read_all(handle);
  18226. EXPECT_EQ("Chunked SSL Data", body);
  18227. }
  18228. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18229. // Content-Length is terminated by the server closing the connection. When the
  18230. // SSL peer sends a close_notify after the body, the client must treat it as a
  18231. // clean EOF and return a successful response rather than an error.
  18232. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18234. ASSERT_TRUE(svr.is_valid());
  18235. svr.set_keep_alive_max_count(1);
  18236. const std::string expected_body = "Hello from connection-close response!";
  18237. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18238. res.set_content_provider("text/plain",
  18239. [&](size_t offset, DataSink &sink) -> bool {
  18240. if (offset < expected_body.size()) {
  18241. sink.write(expected_body.data() + offset,
  18242. expected_body.size() - offset);
  18243. }
  18244. sink.done();
  18245. return true;
  18246. });
  18247. });
  18248. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18249. auto se = detail::scope_exit([&] {
  18250. svr.stop();
  18251. listen_thread.join();
  18252. ASSERT_FALSE(svr.is_running());
  18253. });
  18254. svr.wait_until_ready();
  18255. SSLClient cli(HOST, PORT);
  18256. cli.enable_server_certificate_verification(false);
  18257. auto res = cli.Get("/no-content-length");
  18258. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18259. EXPECT_EQ(StatusCode::OK_200, res->status);
  18260. EXPECT_EQ(expected_body, res->body);
  18261. }
  18262. #endif // CPPHTTPLIB_SSL_ENABLED
  18263. //==============================================================================
  18264. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18265. // results for various scenarios.
  18266. //==============================================================================
  18267. TEST(ParityTest, GetVsOpenStream) {
  18268. Server svr;
  18269. const std::string path = "/parity";
  18270. const std::string content = "Parity test content: hello world";
  18271. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18272. res.set_content(content, "text/plain");
  18273. });
  18274. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18275. auto se = detail::scope_exit([&] {
  18276. svr.stop();
  18277. t.join();
  18278. ASSERT_FALSE(svr.is_running());
  18279. });
  18280. svr.wait_until_ready();
  18281. Client cli(HOST, PORT);
  18282. // Non-stream path
  18283. auto r1 = cli.Get(path);
  18284. ASSERT_TRUE(r1);
  18285. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18286. // Stream path
  18287. auto h = cli.open_stream("GET", path);
  18288. ASSERT_TRUE(h.is_valid());
  18289. EXPECT_EQ(r1->body, read_all(h));
  18290. }
  18291. // Helper to compress data with provided compressor type T
  18292. template <typename Compressor>
  18293. static std::string compress_payload_for_parity(const std::string &in) {
  18294. std::string out;
  18295. Compressor compressor;
  18296. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18297. [&](const char *data, size_t n) {
  18298. out.append(data, n);
  18299. return true;
  18300. });
  18301. EXPECT_TRUE(ok);
  18302. return out;
  18303. }
  18304. // Helper function for compression parity tests
  18305. template <typename Compressor>
  18306. static void test_compression_parity(const std::string &original,
  18307. const std::string &path,
  18308. const std::string &encoding) {
  18309. const std::string compressed =
  18310. compress_payload_for_parity<Compressor>(original);
  18311. Server svr;
  18312. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18313. res.set_content(compressed, "application/octet-stream");
  18314. res.set_header("Content-Encoding", encoding);
  18315. });
  18316. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18317. auto se = detail::scope_exit([&] {
  18318. svr.stop();
  18319. t.join();
  18320. ASSERT_FALSE(svr.is_running());
  18321. });
  18322. svr.wait_until_ready();
  18323. Client cli(HOST, PORT);
  18324. // Non-streaming
  18325. {
  18326. auto res = cli.Get(path);
  18327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18328. EXPECT_EQ(StatusCode::OK_200, res->status);
  18329. EXPECT_EQ(original, res->body);
  18330. }
  18331. // Streaming
  18332. {
  18333. auto h = cli.open_stream("GET", path);
  18334. ASSERT_TRUE(h.is_valid());
  18335. EXPECT_EQ(original, read_all(h));
  18336. }
  18337. }
  18338. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18339. TEST(ParityTest, Gzip) {
  18340. test_compression_parity<detail::gzip_compressor>(
  18341. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18342. }
  18343. #endif
  18344. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18345. TEST(ParityTest, Brotli) {
  18346. test_compression_parity<detail::brotli_compressor>(
  18347. "Hello, brotli parity test payload", "/parity-br", "br");
  18348. }
  18349. #endif
  18350. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18351. TEST(ParityTest, Zstd) {
  18352. test_compression_parity<detail::zstd_compressor>(
  18353. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18354. }
  18355. #endif
  18356. //==============================================================================
  18357. // New Stream API Tests
  18358. //==============================================================================
  18359. inline std::string read_body(httplib::stream::Result &result) {
  18360. std::string body;
  18361. while (result.next()) {
  18362. body.append(result.data(), result.size());
  18363. }
  18364. return body;
  18365. }
  18366. TEST(ClientConnectionTest, Basic) {
  18367. httplib::ClientConnection conn;
  18368. EXPECT_FALSE(conn.is_open());
  18369. conn.sock = 1;
  18370. EXPECT_TRUE(conn.is_open());
  18371. httplib::ClientConnection conn2(std::move(conn));
  18372. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18373. conn2.sock = INVALID_SOCKET;
  18374. }
  18375. // Unified test server for all stream::* tests
  18376. class StreamApiTest : public ::testing::Test {
  18377. protected:
  18378. void SetUp() override {
  18379. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18380. res.set_content("Hello World!", "text/plain");
  18381. });
  18382. svr_.Get("/echo-params",
  18383. [](const httplib::Request &req, httplib::Response &res) {
  18384. std::string r;
  18385. for (const auto &p : req.params) {
  18386. if (!r.empty()) r += "&";
  18387. r += p.first + "=" + p.second;
  18388. }
  18389. res.set_content(r, "text/plain");
  18390. });
  18391. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18392. res.set_content(req.body, req.get_header_value("Content-Type"));
  18393. });
  18394. svr_.Post("/echo-headers",
  18395. [](const httplib::Request &req, httplib::Response &res) {
  18396. std::string r;
  18397. for (const auto &h : req.headers)
  18398. r += h.first + ": " + h.second + "\n";
  18399. res.set_content(r, "text/plain");
  18400. });
  18401. svr_.Post("/echo-params",
  18402. [](const httplib::Request &req, httplib::Response &res) {
  18403. std::string r = "params:";
  18404. for (const auto &p : req.params)
  18405. r += p.first + "=" + p.second + ";";
  18406. res.set_content(r + " body:" + req.body, "text/plain");
  18407. });
  18408. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18409. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18410. });
  18411. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18412. res.set_content("PUT:" + req.body, "text/plain");
  18413. });
  18414. svr_.Patch("/echo",
  18415. [](const httplib::Request &req, httplib::Response &res) {
  18416. res.set_content("PATCH:" + req.body, "text/plain");
  18417. });
  18418. svr_.Delete(
  18419. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18420. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18421. "text/plain");
  18422. });
  18423. svr_.Get("/head-test",
  18424. [](const httplib::Request &, httplib::Response &res) {
  18425. res.set_content("body for HEAD", "text/plain");
  18426. });
  18427. svr_.Options("/options",
  18428. [](const httplib::Request &, httplib::Response &res) {
  18429. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18430. });
  18431. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18432. svr_.wait_until_ready();
  18433. }
  18434. void TearDown() override {
  18435. svr_.stop();
  18436. if (thread_.joinable()) thread_.join();
  18437. }
  18438. httplib::Server svr_;
  18439. std::thread thread_;
  18440. };
  18441. // stream::Get tests
  18442. TEST_F(StreamApiTest, GetBasic) {
  18443. httplib::Client cli(HOST, PORT);
  18444. auto result = httplib::stream::Get(cli, "/hello");
  18445. ASSERT_TRUE(result.is_valid());
  18446. EXPECT_EQ(200, result.status());
  18447. EXPECT_EQ("Hello World!", read_body(result));
  18448. }
  18449. TEST_F(StreamApiTest, GetWithParams) {
  18450. httplib::Client cli(HOST, PORT);
  18451. httplib::Params params{{"foo", "bar"}};
  18452. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18453. ASSERT_TRUE(result.is_valid());
  18454. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18455. }
  18456. TEST_F(StreamApiTest, GetConnectionError) {
  18457. httplib::Client cli(HOST, 9999);
  18458. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18459. }
  18460. TEST_F(StreamApiTest, Get404) {
  18461. httplib::Client cli(HOST, PORT);
  18462. auto result = httplib::stream::Get(cli, "/nonexistent");
  18463. EXPECT_TRUE(result.is_valid());
  18464. EXPECT_EQ(404, result.status());
  18465. }
  18466. // stream::Post tests
  18467. TEST_F(StreamApiTest, PostBasic) {
  18468. httplib::Client cli(HOST, PORT);
  18469. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18470. "application/json");
  18471. ASSERT_TRUE(result.is_valid());
  18472. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18473. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18474. }
  18475. TEST_F(StreamApiTest, PostWithHeaders) {
  18476. httplib::Client cli(HOST, PORT);
  18477. httplib::Headers headers{{"X-Custom", "value"}};
  18478. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18479. "text/plain");
  18480. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18481. }
  18482. TEST_F(StreamApiTest, PostWithParams) {
  18483. httplib::Client cli(HOST, PORT);
  18484. httplib::Params params{{"k", "v"}};
  18485. auto result =
  18486. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18487. auto body = read_body(result);
  18488. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18489. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18490. }
  18491. TEST_F(StreamApiTest, PostLarge) {
  18492. httplib::Client cli(HOST, PORT);
  18493. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18494. size_t total = 0;
  18495. while (result.next()) {
  18496. total += result.size();
  18497. }
  18498. EXPECT_EQ(100u * 1024u, total);
  18499. }
  18500. // stream::Put/Patch tests
  18501. TEST_F(StreamApiTest, PutAndPatch) {
  18502. httplib::Client cli(HOST, PORT);
  18503. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18504. EXPECT_EQ("PUT:test", read_body(put));
  18505. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18506. EXPECT_EQ("PATCH:test", read_body(patch));
  18507. }
  18508. // stream::Delete tests
  18509. TEST_F(StreamApiTest, Delete) {
  18510. httplib::Client cli(HOST, PORT);
  18511. auto del1 = httplib::stream::Delete(cli, "/resource");
  18512. EXPECT_EQ("Deleted", read_body(del1));
  18513. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18514. EXPECT_EQ("Deleted:data", read_body(del2));
  18515. }
  18516. // stream::Head/Options tests
  18517. TEST_F(StreamApiTest, HeadAndOptions) {
  18518. httplib::Client cli(HOST, PORT);
  18519. auto head = httplib::stream::Head(cli, "/head-test");
  18520. EXPECT_TRUE(head.is_valid());
  18521. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18522. auto opts = httplib::stream::Options(cli, "/options");
  18523. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18524. }
  18525. // SSL stream::* tests
  18526. #ifdef CPPHTTPLIB_SSL_ENABLED
  18527. class SSLStreamApiTest : public ::testing::Test {
  18528. protected:
  18529. void SetUp() override {
  18530. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18531. res.set_content("Hello SSL!", "text/plain");
  18532. });
  18533. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18534. res.set_content(req.body, "text/plain");
  18535. });
  18536. port_ = svr_.bind_to_any_port("127.0.0.1");
  18537. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18538. svr_.wait_until_ready();
  18539. }
  18540. void TearDown() override {
  18541. svr_.stop();
  18542. if (thread_.joinable()) thread_.join();
  18543. }
  18544. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18545. std::thread thread_;
  18546. int port_ = 0;
  18547. };
  18548. TEST_F(SSLStreamApiTest, GetAndPost) {
  18549. httplib::SSLClient cli("127.0.0.1", port_);
  18550. cli.enable_server_certificate_verification(false);
  18551. auto get = httplib::stream::Get(cli, "/hello");
  18552. EXPECT_EQ("Hello SSL!", read_body(get));
  18553. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18554. EXPECT_EQ("test", read_body(post));
  18555. }
  18556. #endif
  18557. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18558. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18559. // BodyReader
  18560. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18561. // Test that read timeout during streaming is detected
  18562. // Use a large content-length response where server delays mid-stream
  18563. Server svr;
  18564. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18565. // Send a large response with delay in the middle
  18566. res.set_content_provider(
  18567. 1000, // content_length
  18568. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18569. if (offset < 100) {
  18570. // Send first 100 bytes immediately
  18571. std::string data(100, 'A');
  18572. sink.write(data.c_str(), data.size());
  18573. return true;
  18574. }
  18575. // Then delay longer than client timeout
  18576. std::this_thread::sleep_for(std::chrono::seconds(3));
  18577. std::string data(900, 'B');
  18578. sink.write(data.c_str(), data.size());
  18579. return true;
  18580. });
  18581. });
  18582. auto port = 8091;
  18583. std::thread t([&]() { svr.listen("localhost", port); });
  18584. svr.wait_until_ready();
  18585. Client cli("localhost", port);
  18586. cli.set_read_timeout(1, 0); // 1 second timeout
  18587. auto handle = cli.open_stream("GET", "/slow-stream");
  18588. ASSERT_TRUE(handle.is_valid());
  18589. char buf[256];
  18590. ssize_t total = 0;
  18591. ssize_t n;
  18592. bool got_error = false;
  18593. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18594. total += n;
  18595. }
  18596. if (n < 0) {
  18597. got_error = true;
  18598. // Should be timeout or read error
  18599. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18600. handle.get_read_error() == Error::Read)
  18601. << "Actual error: " << to_string(handle.get_read_error());
  18602. }
  18603. // Either we got an error, or we got less data than expected
  18604. EXPECT_TRUE(got_error || total < 1000)
  18605. << "Expected timeout but got all " << total << " bytes";
  18606. svr.stop();
  18607. t.join();
  18608. }
  18609. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18610. // Test connection closed detection via BodyReader
  18611. Server svr;
  18612. std::atomic<bool> close_now{false};
  18613. svr.Get("/will-close", [&](const Request &, Response &res) {
  18614. res.set_content_provider(
  18615. 10000, // Large content_length that we won't fully send
  18616. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18617. if (offset < 100) {
  18618. std::string data(100, 'X');
  18619. sink.write(data.c_str(), data.size());
  18620. return true;
  18621. }
  18622. // Wait for signal then abort
  18623. while (!close_now) {
  18624. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18625. }
  18626. return false; // Abort - server will close connection
  18627. });
  18628. });
  18629. auto port = 8092;
  18630. std::thread t([&]() { svr.listen("localhost", port); });
  18631. svr.wait_until_ready();
  18632. Client cli("localhost", port);
  18633. auto handle = cli.open_stream("GET", "/will-close");
  18634. ASSERT_TRUE(handle.is_valid());
  18635. char buf[256];
  18636. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18637. EXPECT_GT(n, 0) << "First read should succeed";
  18638. // Signal server to close
  18639. close_now = true;
  18640. // Keep reading until error or EOF
  18641. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18642. // Keep reading
  18643. }
  18644. // Should get an error since content_length wasn't satisfied
  18645. if (n < 0) {
  18646. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18647. handle.get_read_error() == Error::Read)
  18648. << "Actual error: " << to_string(handle.get_read_error());
  18649. }
  18650. svr.stop();
  18651. t.join();
  18652. }
  18653. #ifdef CPPHTTPLIB_SSL_ENABLED
  18654. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18655. // Test that read timeout during SSL streaming is detected
  18656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18657. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18658. res.set_content_provider(
  18659. 1000, "text/plain",
  18660. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18661. if (offset < 100) {
  18662. std::string data(100, 'A');
  18663. sink.write(data.c_str(), data.size());
  18664. return true;
  18665. }
  18666. std::this_thread::sleep_for(std::chrono::seconds(3));
  18667. std::string data(900, 'B');
  18668. sink.write(data.c_str(), data.size());
  18669. return true;
  18670. });
  18671. });
  18672. auto port = 8093;
  18673. std::thread t([&]() { svr.listen("localhost", port); });
  18674. svr.wait_until_ready();
  18675. SSLClient cli("localhost", port);
  18676. cli.enable_server_certificate_verification(false);
  18677. cli.set_read_timeout(1, 0); // 1 second timeout
  18678. auto handle = cli.open_stream("GET", "/slow-stream");
  18679. ASSERT_TRUE(handle.is_valid());
  18680. char buf[256];
  18681. ssize_t total = 0;
  18682. ssize_t n;
  18683. bool got_error = false;
  18684. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18685. total += n;
  18686. }
  18687. if (n < 0) {
  18688. got_error = true;
  18689. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18690. handle.get_read_error() == Error::Read)
  18691. << "Actual error: " << to_string(handle.get_read_error());
  18692. }
  18693. EXPECT_TRUE(got_error || total < 1000)
  18694. << "Expected timeout but got all " << total << " bytes";
  18695. svr.stop();
  18696. t.join();
  18697. }
  18698. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18699. // Test SSL connection closed detection
  18700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18701. std::atomic<bool> close_now{false};
  18702. svr.Get("/will-close", [&](const Request &, Response &res) {
  18703. res.set_content_provider(
  18704. 10000, "text/plain",
  18705. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18706. if (offset < 100) {
  18707. std::string data(100, 'X');
  18708. sink.write(data.c_str(), data.size());
  18709. return true;
  18710. }
  18711. while (!close_now) {
  18712. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18713. }
  18714. return false;
  18715. });
  18716. });
  18717. auto port = 8094;
  18718. std::thread t([&]() { svr.listen("localhost", port); });
  18719. svr.wait_until_ready();
  18720. SSLClient cli("localhost", port);
  18721. cli.enable_server_certificate_verification(false);
  18722. auto handle = cli.open_stream("GET", "/will-close");
  18723. ASSERT_TRUE(handle.is_valid());
  18724. char buf[256];
  18725. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18726. EXPECT_GT(n, 0);
  18727. // Signal server to close
  18728. close_now = true;
  18729. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18730. // Keep reading
  18731. }
  18732. if (n < 0) {
  18733. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18734. handle.get_read_error() == Error::Read)
  18735. << "Actual error: " << to_string(handle.get_read_error());
  18736. }
  18737. svr.stop();
  18738. t.join();
  18739. }
  18740. #endif
  18741. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18742. using namespace httplib;
  18743. // Create a test file
  18744. const char *fname = "etag_testfile.txt";
  18745. const char *content = "etag-content";
  18746. {
  18747. std::ofstream ofs(fname);
  18748. ofs << content;
  18749. ASSERT_TRUE(ofs.good());
  18750. }
  18751. Server svr;
  18752. svr.set_mount_point("/static", ".");
  18753. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18754. svr.wait_until_ready();
  18755. Client cli(HOST, PORT);
  18756. // First request: should get 200 with ETag header
  18757. auto res1 = cli.Get("/static/etag_testfile.txt");
  18758. ASSERT_TRUE(res1);
  18759. ASSERT_EQ(200, res1->status);
  18760. ASSERT_TRUE(res1->has_header("ETag"));
  18761. std::string etag = res1->get_header_value("ETag");
  18762. EXPECT_FALSE(etag.empty());
  18763. // Verify ETag format: W/"hex-hex"
  18764. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18765. EXPECT_EQ('W', etag[0]);
  18766. EXPECT_EQ('/', etag[1]);
  18767. EXPECT_EQ('"', etag[2]);
  18768. EXPECT_EQ('"', etag.back());
  18769. // Exact match: expect 304 Not Modified
  18770. Headers h2 = {{"If-None-Match", etag}};
  18771. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18772. ASSERT_TRUE(res2);
  18773. EXPECT_EQ(304, res2->status);
  18774. // Wildcard match: expect 304 Not Modified
  18775. Headers h3 = {{"If-None-Match", "*"}};
  18776. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18777. ASSERT_TRUE(res3);
  18778. EXPECT_EQ(304, res3->status);
  18779. // Non-matching ETag: expect 200
  18780. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18781. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18782. ASSERT_TRUE(res4);
  18783. EXPECT_EQ(200, res4->status);
  18784. // Multiple ETags with one matching: expect 304
  18785. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18786. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18787. ASSERT_TRUE(res5);
  18788. EXPECT_EQ(304, res5->status);
  18789. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18790. // that equivalent to the single comma-separated list above, so the match on
  18791. // the second line must still be found.
  18792. Headers h6;
  18793. h6.emplace("If-None-Match", "W/\"other\"");
  18794. h6.emplace("If-None-Match", etag);
  18795. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18796. ASSERT_TRUE(res6);
  18797. EXPECT_EQ(304, res6->status);
  18798. svr.stop();
  18799. t.join();
  18800. std::remove(fname);
  18801. }
  18802. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18803. using namespace httplib;
  18804. Server svr;
  18805. svr.set_mount_point("/static", ".");
  18806. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18807. svr.wait_until_ready();
  18808. Client cli(HOST, PORT);
  18809. // Send If-None-Match: * to a non-existent file
  18810. Headers h = {{"If-None-Match", "*"}};
  18811. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18813. EXPECT_EQ(404, res->status);
  18814. svr.stop();
  18815. t.join();
  18816. }
  18817. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18818. using namespace httplib;
  18819. // Create a test file
  18820. const char *fname = "etag_boundary_testfile.txt";
  18821. const char *content = "boundary-test";
  18822. {
  18823. std::ofstream ofs(fname);
  18824. ofs << content;
  18825. ASSERT_TRUE(ofs.good());
  18826. }
  18827. Server svr;
  18828. svr.set_mount_point("/static", ".");
  18829. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18830. svr.wait_until_ready();
  18831. Client cli(HOST, PORT);
  18832. // Get the actual ETag
  18833. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18834. ASSERT_TRUE(res1);
  18835. ASSERT_EQ(200, res1->status);
  18836. ASSERT_TRUE(res1->has_header("ETag"));
  18837. std::string etag = res1->get_header_value("ETag");
  18838. // Test 1: Very long ETag value (longer than actual ETag)
  18839. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18840. Headers h1 = {{"If-None-Match", "W/"
  18841. "\"very-long-etag-value-that-is-much-longer-"
  18842. "than-the-actual-etag-value\""}};
  18843. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18844. ASSERT_TRUE(res2);
  18845. EXPECT_EQ(200, res2->status); // Should not match
  18846. // Test 2: Long string followed by wildcard
  18847. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18848. // string)
  18849. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18850. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18851. ASSERT_TRUE(res3);
  18852. EXPECT_EQ(304, res3->status); // Should match on "*"
  18853. // Test 3: Wildcard followed by long string
  18854. // Should match on "*" immediately and return 304
  18855. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18856. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18857. ASSERT_TRUE(res4);
  18858. EXPECT_EQ(304, res4->status); // Should match on "*"
  18859. // Test 4: Multiple long non-matching values
  18860. // Should NOT match and return 200 (test that all comparisons are safe)
  18861. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18862. "W/\"second-long-non-matching-value\", "
  18863. "W/\"third-long-non-matching-value\""}};
  18864. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18865. ASSERT_TRUE(res5);
  18866. EXPECT_EQ(200, res5->status); // Should not match
  18867. // Test 5: Single character that is not "*" (edge case)
  18868. Headers h5 = {{"If-None-Match", "X"}};
  18869. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18870. ASSERT_TRUE(res6);
  18871. EXPECT_EQ(200, res6->status); // Should not match
  18872. svr.stop();
  18873. t.join();
  18874. std::remove(fname);
  18875. }
  18876. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18877. using namespace httplib;
  18878. // Create a test file
  18879. const char *fname = "ims_testfile.txt";
  18880. const char *content = "if-modified-since-test";
  18881. {
  18882. std::ofstream ofs(fname);
  18883. ofs << content;
  18884. ASSERT_TRUE(ofs.good());
  18885. }
  18886. Server svr;
  18887. svr.set_mount_point("/static", ".");
  18888. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18889. svr.wait_until_ready();
  18890. Client cli(HOST, PORT);
  18891. // First request: should get 200 with Last-Modified header
  18892. auto res1 = cli.Get("/static/ims_testfile.txt");
  18893. ASSERT_TRUE(res1);
  18894. ASSERT_EQ(200, res1->status);
  18895. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18896. std::string last_modified = res1->get_header_value("Last-Modified");
  18897. EXPECT_FALSE(last_modified.empty());
  18898. // If-Modified-Since with same time: expect 304
  18899. Headers h2 = {{"If-Modified-Since", last_modified}};
  18900. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18901. ASSERT_TRUE(res2);
  18902. EXPECT_EQ(304, res2->status);
  18903. // If-Modified-Since with future time: expect 304
  18904. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18905. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18906. ASSERT_TRUE(res3);
  18907. EXPECT_EQ(304, res3->status);
  18908. // If-Modified-Since with past time: expect 200
  18909. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18910. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18911. ASSERT_TRUE(res4);
  18912. EXPECT_EQ(200, res4->status);
  18913. // If-None-Match takes precedence over If-Modified-Since
  18914. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18915. ASSERT_TRUE(res1->has_header("ETag"));
  18916. std::string etag = res1->get_header_value("ETag");
  18917. Headers h5 = {{"If-None-Match", etag},
  18918. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18919. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18920. ASSERT_TRUE(res5);
  18921. EXPECT_EQ(304, res5->status);
  18922. svr.stop();
  18923. t.join();
  18924. std::remove(fname);
  18925. }
  18926. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18927. using namespace httplib;
  18928. Server svr;
  18929. // Endpoint that returns compressible content
  18930. svr.Get("/compressible", [](const Request &, Response &res) {
  18931. // Return a large enough body to trigger compression
  18932. std::string body(1000, 'a');
  18933. res.set_content(body, "text/plain");
  18934. });
  18935. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18936. svr.wait_until_ready();
  18937. Client cli(HOST, PORT);
  18938. // Request with gzip support: should get Vary header when compressed
  18939. cli.set_compress(true);
  18940. auto res1 = cli.Get("/compressible");
  18941. ASSERT_TRUE(res1);
  18942. EXPECT_EQ(200, res1->status);
  18943. // If Content-Encoding is set, Vary should also be set
  18944. if (res1->has_header("Content-Encoding")) {
  18945. EXPECT_TRUE(res1->has_header("Vary"));
  18946. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18947. }
  18948. // Request without Accept-Encoding header: should not have compression
  18949. Headers h_no_compress;
  18950. auto res2 = cli.Get("/compressible", h_no_compress);
  18951. ASSERT_TRUE(res2);
  18952. EXPECT_EQ(200, res2->status);
  18953. // Verify Vary header is present when compression is applied
  18954. // (the exact behavior depends on server configuration)
  18955. svr.stop();
  18956. t.join();
  18957. }
  18958. TEST(ETagTest, IfRangeWithETag) {
  18959. using namespace httplib;
  18960. // Create a test file with known content
  18961. const char *fname = "if_range_testfile.txt";
  18962. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18963. {
  18964. std::ofstream ofs(fname);
  18965. ofs << content;
  18966. ASSERT_TRUE(ofs.good());
  18967. }
  18968. Server svr;
  18969. svr.set_mount_point("/static", ".");
  18970. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18971. svr.wait_until_ready();
  18972. Client cli(HOST, PORT);
  18973. // First request: get ETag
  18974. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18975. ASSERT_TRUE(res1);
  18976. ASSERT_EQ(200, res1->status);
  18977. ASSERT_TRUE(res1->has_header("ETag"));
  18978. std::string etag = res1->get_header_value("ETag");
  18979. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18980. // Since our server generates weak ETags (W/"..."), If-Range with our
  18981. // ETag should NOT result in partial content - it should return full content.
  18982. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18983. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18984. ASSERT_TRUE(res2);
  18985. // Weak ETag in If-Range -> full content (200), not partial (206)
  18986. EXPECT_EQ(200, res2->status);
  18987. EXPECT_EQ(content, res2->body);
  18988. EXPECT_FALSE(res2->has_header("Content-Range"));
  18989. // Range request with non-matching If-Range (ETag): should get 200 (full
  18990. // content)
  18991. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18992. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18993. ASSERT_TRUE(res3);
  18994. EXPECT_EQ(200, res3->status);
  18995. EXPECT_EQ(content, res3->body);
  18996. EXPECT_FALSE(res3->has_header("Content-Range"));
  18997. // Range request with strong ETag (hypothetical - our server doesn't generate
  18998. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18999. // should return full content)
  19000. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19001. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19002. ASSERT_TRUE(res4);
  19003. EXPECT_EQ(200, res4->status);
  19004. EXPECT_EQ(content, res4->body);
  19005. EXPECT_FALSE(res4->has_header("Content-Range"));
  19006. svr.stop();
  19007. t.join();
  19008. std::remove(fname);
  19009. }
  19010. TEST(ETagTest, IfRangeWithDate) {
  19011. using namespace httplib;
  19012. // Create a test file
  19013. const char *fname = "if_range_date_testfile.txt";
  19014. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19015. {
  19016. std::ofstream ofs(fname);
  19017. ofs << content;
  19018. ASSERT_TRUE(ofs.good());
  19019. }
  19020. Server svr;
  19021. svr.set_mount_point("/static", ".");
  19022. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19023. svr.wait_until_ready();
  19024. Client cli(HOST, PORT);
  19025. // First request: get Last-Modified
  19026. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19027. ASSERT_TRUE(res1);
  19028. ASSERT_EQ(200, res1->status);
  19029. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19030. std::string last_modified = res1->get_header_value("Last-Modified");
  19031. // Range request with matching If-Range (date): should get 206
  19032. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19033. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19034. ASSERT_TRUE(res2);
  19035. EXPECT_EQ(206, res2->status);
  19036. EXPECT_EQ("FGHIJ", res2->body);
  19037. // Range request with old If-Range date: should get 200 (full content)
  19038. Headers h3 = {{"Range", "bytes=5-9"},
  19039. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19040. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19041. ASSERT_TRUE(res3);
  19042. EXPECT_EQ(200, res3->status);
  19043. EXPECT_EQ(content, res3->body);
  19044. // Range request with future If-Range date: should get 206
  19045. Headers h4 = {{"Range", "bytes=0-4"},
  19046. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19047. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19048. ASSERT_TRUE(res4);
  19049. EXPECT_EQ(206, res4->status);
  19050. EXPECT_EQ("ABCDE", res4->body);
  19051. svr.stop();
  19052. t.join();
  19053. std::remove(fname);
  19054. }
  19055. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19056. using namespace httplib;
  19057. const char *fname = "etag_malformed.txt";
  19058. const char *content = "malformed-etag";
  19059. {
  19060. std::ofstream ofs(fname);
  19061. ofs << content;
  19062. ASSERT_TRUE(ofs.good());
  19063. }
  19064. Server svr;
  19065. svr.set_mount_point("/static", ".");
  19066. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19067. svr.wait_until_ready();
  19068. Client cli(HOST, PORT);
  19069. // baseline: should get 200 and an ETag
  19070. auto res1 = cli.Get("/static/etag_malformed.txt");
  19071. ASSERT_TRUE(res1);
  19072. ASSERT_EQ(200, res1->status);
  19073. ASSERT_TRUE(res1->has_header("ETag"));
  19074. // Malformed ETag value (missing quotes) should be treated as non-matching
  19075. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19076. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19077. ASSERT_TRUE(res_bad);
  19078. EXPECT_EQ(200, res_bad->status);
  19079. // Whitespace-only header value should be considered invalid / non-matching
  19080. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19081. "Host: localhost\r\n"
  19082. "If-None-Match: \r\n"
  19083. "Connection: close\r\n"
  19084. "\r\n";
  19085. std::string out;
  19086. ASSERT_TRUE(send_request(5, raw_req, &out));
  19087. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19088. svr.stop();
  19089. t.join();
  19090. std::remove(fname);
  19091. }
  19092. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19093. using namespace httplib;
  19094. const char *fname = "ims_invalid_format.txt";
  19095. const char *content = "ims-bad-format";
  19096. {
  19097. std::ofstream ofs(fname);
  19098. ofs << content;
  19099. ASSERT_TRUE(ofs.good());
  19100. }
  19101. Server svr;
  19102. svr.set_mount_point("/static", ".");
  19103. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19104. svr.wait_until_ready();
  19105. Client cli(HOST, PORT);
  19106. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19107. ASSERT_TRUE(res1);
  19108. ASSERT_EQ(200, res1->status);
  19109. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19110. // If-Modified-Since with invalid format should not result in 304
  19111. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19112. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19113. ASSERT_TRUE(res_bad);
  19114. EXPECT_EQ(200, res_bad->status);
  19115. // If-Range with invalid date format should be treated as mismatch -> full
  19116. // content (200)
  19117. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19118. {"If-Range", "invalid-date"}};
  19119. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19120. ASSERT_TRUE(res_ifrange);
  19121. EXPECT_EQ(200, res_ifrange->status);
  19122. svr.stop();
  19123. t.join();
  19124. std::remove(fname);
  19125. }
  19126. TEST(ETagTest, IfRangeWithMalformedETag) {
  19127. using namespace httplib;
  19128. const char *fname = "ifrange_malformed.txt";
  19129. const std::string content = "0123456789";
  19130. {
  19131. std::ofstream ofs(fname);
  19132. ofs << content;
  19133. ASSERT_TRUE(ofs.good());
  19134. }
  19135. Server svr;
  19136. svr.set_mount_point("/static", ".");
  19137. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19138. svr.wait_until_ready();
  19139. Client cli(HOST, PORT);
  19140. // First request: get ETag
  19141. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19142. ASSERT_TRUE(res1);
  19143. ASSERT_EQ(200, res1->status);
  19144. ASSERT_TRUE(res1->has_header("ETag"));
  19145. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19146. // full content (200)
  19147. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19148. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19149. ASSERT_TRUE(res2);
  19150. EXPECT_EQ(200, res2->status);
  19151. EXPECT_EQ(content, res2->body);
  19152. svr.stop();
  19153. t.join();
  19154. std::remove(fname);
  19155. }
  19156. TEST(ETagTest, ExtremeLargeDateValues) {
  19157. using namespace httplib;
  19158. const char *fname = "ims_extreme_date.txt";
  19159. const char *content = "ims-extreme-date";
  19160. {
  19161. std::ofstream ofs(fname);
  19162. ofs << content;
  19163. ASSERT_TRUE(ofs.good());
  19164. }
  19165. Server svr;
  19166. svr.set_mount_point("/static", ".");
  19167. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19168. svr.wait_until_ready();
  19169. Client cli(HOST, PORT);
  19170. auto res1 = cli.Get(std::string("/static/") + fname);
  19171. ASSERT_TRUE(res1);
  19172. ASSERT_EQ(200, res1->status);
  19173. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19174. // Extremely large year that may overflow date parsing routines.
  19175. Headers h_large_date = {
  19176. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19177. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19178. ASSERT_TRUE(res_bad);
  19179. // Expect server to treat this as invalid/mismatch and return full content
  19180. EXPECT_EQ(200, res_bad->status);
  19181. // If-Range with extremely large date should be treated as mismatch -> full
  19182. // content (200)
  19183. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19184. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19185. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19186. ASSERT_TRUE(res_ifrange);
  19187. EXPECT_EQ(200, res_ifrange->status);
  19188. svr.stop();
  19189. t.join();
  19190. std::remove(fname);
  19191. }
  19192. TEST(ETagTest, NegativeFileModificationTime) {
  19193. using namespace httplib;
  19194. const char *fname = "ims_negative_mtime.txt";
  19195. const std::string content = "negative-mtime";
  19196. {
  19197. std::ofstream ofs(fname);
  19198. ofs << content;
  19199. ASSERT_TRUE(ofs.good());
  19200. }
  19201. // Try to set file mtime to a negative value. This may fail on some
  19202. // platforms/filesystems; if it fails, the test will still verify server
  19203. // behaves safely by performing a regular conditional request.
  19204. #if defined(__APPLE__) || defined(__linux__)
  19205. bool set_negative = false;
  19206. do {
  19207. struct timeval times[2];
  19208. // access time: now
  19209. times[0].tv_sec = time(nullptr);
  19210. times[0].tv_usec = 0;
  19211. // modification time: negative (e.g., -1)
  19212. times[1].tv_sec = -1;
  19213. times[1].tv_usec = 0;
  19214. if (utimes(fname, times) == 0) { set_negative = true; }
  19215. } while (0);
  19216. #else
  19217. bool set_negative = false;
  19218. #endif
  19219. Server svr;
  19220. svr.set_mount_point("/static", ".");
  19221. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19222. svr.wait_until_ready();
  19223. Client cli(HOST, PORT);
  19224. auto res1 = cli.Get(std::string("/static/") + fname);
  19225. ASSERT_TRUE(res1);
  19226. ASSERT_EQ(200, res1->status);
  19227. bool has_last_modified = res1->has_header("Last-Modified");
  19228. std::string last_modified;
  19229. if (has_last_modified) {
  19230. last_modified = res1->get_header_value("Last-Modified");
  19231. }
  19232. if (set_negative) {
  19233. // If we successfully set a negative mtime, ensure server returns a
  19234. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19235. // with an old date and ensure server handles it without crash.
  19236. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19237. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19238. ASSERT_TRUE(res2);
  19239. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19240. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19241. } else {
  19242. // Could not set negative mtime on this platform; fall back to verifying
  19243. // that normal invalid/malformed dates are treated safely (non-304).
  19244. Headers h_bad_date = {
  19245. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19246. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19247. ASSERT_TRUE(res_bad);
  19248. EXPECT_EQ(200, res_bad->status);
  19249. }
  19250. svr.stop();
  19251. t.join();
  19252. std::remove(fname);
  19253. }
  19254. //==============================================================================
  19255. // Integration Tests with Server
  19256. //==============================================================================
  19257. class SSEIntegrationTest : public ::testing::Test {
  19258. protected:
  19259. void SetUp() override {
  19260. stop_server_.store(false);
  19261. events_.clear();
  19262. server_ = httplib::detail::make_unique<Server>();
  19263. setup_server();
  19264. start_server();
  19265. }
  19266. void TearDown() override {
  19267. stop_server_.store(true);
  19268. event_cv_.notify_all();
  19269. server_->stop();
  19270. if (server_thread_.joinable()) { server_thread_.join(); }
  19271. }
  19272. void setup_server() {
  19273. // Simple SSE endpoint
  19274. server_->Get("/events", [this](const Request &req, Response &res) {
  19275. auto last_id = req.get_header_value("Last-Event-ID");
  19276. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19277. res.set_chunked_content_provider(
  19278. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19279. std::unique_lock<std::mutex> lock(event_mutex_);
  19280. if (event_cv_.wait_for(
  19281. lock, std::chrono::milliseconds(200), [this] {
  19282. return !events_.empty() || stop_server_.load();
  19283. })) {
  19284. if (stop_server_.load()) { return false; }
  19285. if (!events_.empty()) {
  19286. std::string event = events_.front();
  19287. events_.erase(events_.begin());
  19288. sink.write(event.data(), event.size());
  19289. return true;
  19290. }
  19291. }
  19292. return !stop_server_.load();
  19293. });
  19294. });
  19295. // Endpoint that returns error
  19296. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19297. res.status = 500;
  19298. res.set_content("Internal Server Error", "text/plain");
  19299. });
  19300. // Endpoint for custom event types
  19301. server_->Get("/custom-events", [](const Request &, Response &res) {
  19302. res.set_chunked_content_provider(
  19303. "text/event-stream", [](size_t offset, DataSink &sink) {
  19304. if (offset == 0) {
  19305. std::string event = "event: update\ndata: updated\n\n"
  19306. "event: delete\ndata: deleted\n\n";
  19307. sink.write(event.data(), event.size());
  19308. }
  19309. return false; // End stream after sending
  19310. });
  19311. });
  19312. }
  19313. void start_server() {
  19314. port_ = server_->bind_to_any_port(HOST);
  19315. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19316. // Wait for server to start
  19317. while (!server_->is_running()) {
  19318. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19319. }
  19320. }
  19321. int get_port() const { return port_; }
  19322. void send_event(const std::string &event) {
  19323. std::lock_guard<std::mutex> lock(event_mutex_);
  19324. events_.push_back(event);
  19325. event_cv_.notify_all();
  19326. }
  19327. std::unique_ptr<Server> server_;
  19328. std::thread server_thread_;
  19329. std::mutex event_mutex_;
  19330. std::condition_variable event_cv_;
  19331. std::vector<std::string> events_;
  19332. std::atomic<bool> stop_server_{false};
  19333. std::string last_received_event_id_;
  19334. int port_ = 0;
  19335. };
  19336. //==============================================================================
  19337. // SSE Parsing Tests
  19338. //==============================================================================
  19339. class SSEParsingTest : public SSEIntegrationTest {
  19340. protected:
  19341. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19342. // A trailing sentinel event tells when the whole stream has been parsed.
  19343. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19344. auto body = stream + "event: end\ndata: end\n\n";
  19345. server_->Get("/parse", [body](const Request &, Response &res) {
  19346. res.set_content(body, "text/event-stream");
  19347. });
  19348. return collect("/parse");
  19349. }
  19350. // Runs SSEClient against path until an "end" event arrives and returns the
  19351. // messages dispatched before it
  19352. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19353. Client client(HOST, get_port());
  19354. sse::SSEClient sse(client, path);
  19355. std::mutex mutex;
  19356. std::condition_variable cv;
  19357. std::vector<sse::SSEMessage> messages;
  19358. auto done = false;
  19359. sse.on_message([&](const sse::SSEMessage &msg) {
  19360. std::lock_guard<std::mutex> lock(mutex);
  19361. // Ignore a replay from a reconnect that races with stop()
  19362. if (!done) { messages.push_back(msg); }
  19363. });
  19364. sse.on_event("end", [&](const sse::SSEMessage &) {
  19365. std::lock_guard<std::mutex> lock(mutex);
  19366. done = true;
  19367. cv.notify_all();
  19368. });
  19369. sse.set_reconnect_interval(100);
  19370. sse.start_async();
  19371. {
  19372. std::unique_lock<std::mutex> lock(mutex);
  19373. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19374. }
  19375. sse.stop();
  19376. EXPECT_TRUE(done);
  19377. return messages;
  19378. }
  19379. };
  19380. TEST_F(SSEParsingTest, SingleLineData) {
  19381. auto msgs = parse("data: hello\n\n");
  19382. ASSERT_EQ(msgs.size(), 1u);
  19383. EXPECT_EQ(msgs[0].data, "hello");
  19384. EXPECT_EQ(msgs[0].event, "message");
  19385. }
  19386. TEST_F(SSEParsingTest, MultiLineData) {
  19387. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19388. ASSERT_EQ(msgs.size(), 1u);
  19389. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19390. }
  19391. TEST_F(SSEParsingTest, CustomEventType) {
  19392. auto msgs = parse("event: update\ndata: payload\n\n");
  19393. ASSERT_EQ(msgs.size(), 1u);
  19394. EXPECT_EQ(msgs[0].event, "update");
  19395. EXPECT_EQ(msgs[0].data, "payload");
  19396. }
  19397. TEST_F(SSEParsingTest, EventIdHandling) {
  19398. auto msgs = parse("id: 12345\ndata: test\n\n");
  19399. ASSERT_EQ(msgs.size(), 1u);
  19400. EXPECT_EQ(msgs[0].id, "12345");
  19401. }
  19402. TEST_F(SSEParsingTest, EmptyEventId) {
  19403. auto msgs = parse("id:\ndata: test\n\n");
  19404. ASSERT_EQ(msgs.size(), 1u);
  19405. EXPECT_EQ(msgs[0].id, "");
  19406. }
  19407. TEST_F(SSEParsingTest, CommentsIgnored) {
  19408. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19409. ASSERT_EQ(msgs.size(), 1u);
  19410. EXPECT_EQ(msgs[0].data, "hello");
  19411. EXPECT_EQ(msgs[0].event, "message");
  19412. }
  19413. TEST_F(SSEParsingTest, ColonInValue) {
  19414. auto msgs = parse("data: hello:world:test\n\n");
  19415. ASSERT_EQ(msgs.size(), 1u);
  19416. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19417. }
  19418. TEST_F(SSEParsingTest, FieldNameOnly) {
  19419. // A line without a colon is a field name with an empty value
  19420. auto msgs = parse("data\n\n");
  19421. ASSERT_EQ(msgs.size(), 1u);
  19422. EXPECT_EQ(msgs[0].data, "");
  19423. }
  19424. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19425. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19426. ASSERT_EQ(msgs.size(), 1u);
  19427. EXPECT_EQ(msgs[0].event, "update");
  19428. EXPECT_EQ(msgs[0].data, "hello");
  19429. }
  19430. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19431. auto msgs = parse("data\r\n\r\n");
  19432. ASSERT_EQ(msgs.size(), 1u);
  19433. EXPECT_EQ(msgs[0].data, "");
  19434. }
  19435. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19436. auto msgs = parse("event: update\rdata: hello\r\r");
  19437. ASSERT_EQ(msgs.size(), 1u);
  19438. EXPECT_EQ(msgs[0].event, "update");
  19439. EXPECT_EQ(msgs[0].data, "hello");
  19440. }
  19441. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19442. // Chunk boundaries fall inside every \r\n and right before the first one
  19443. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19444. "\n\r", "\nevent: end\ndata: end\n\n"};
  19445. server_->Get("/split", [chunks](const Request &, Response &res) {
  19446. auto i = std::make_shared<size_t>(0);
  19447. res.set_chunked_content_provider(
  19448. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19449. if (*i == chunks.size()) {
  19450. sink.done();
  19451. } else {
  19452. sink.write(chunks[*i].data(), chunks[*i].size());
  19453. (*i)++;
  19454. }
  19455. return true;
  19456. });
  19457. });
  19458. auto msgs = collect("/split");
  19459. ASSERT_EQ(msgs.size(), 1u);
  19460. EXPECT_EQ(msgs[0].event, "update");
  19461. EXPECT_EQ(msgs[0].data, "hello");
  19462. }
  19463. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19464. // Only a BOM at the start of the stream is ignored
  19465. auto msgs = parse("\xEF\xBB\xBF"
  19466. "data: first\n\n"
  19467. "\xEF\xBB\xBF"
  19468. "data: second\n\n");
  19469. ASSERT_EQ(msgs.size(), 1u);
  19470. EXPECT_EQ(msgs[0].data, "first");
  19471. }
  19472. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19473. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19474. ASSERT_EQ(msgs.size(), 1u);
  19475. EXPECT_EQ(msgs[0].data, "hello");
  19476. EXPECT_EQ(msgs[0].event, "message");
  19477. }
  19478. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19479. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19480. ASSERT_EQ(msgs.size(), 2u);
  19481. EXPECT_EQ(msgs[0].data, "hello");
  19482. EXPECT_EQ(msgs[1].data, "hello");
  19483. }
  19484. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19485. // An event without data is not dispatched, and its type must not leak
  19486. // into the next event
  19487. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19488. ASSERT_EQ(msgs.size(), 1u);
  19489. EXPECT_EQ(msgs[0].event, "message");
  19490. EXPECT_EQ(msgs[0].data, "hello");
  19491. }
  19492. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19493. // The first connection sends only an id; the second echoes back the
  19494. // Last-Event-ID it was reconnected with
  19495. std::atomic<int> connection_count{0};
  19496. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19497. if (connection_count++ == 0) {
  19498. res.set_content("id: 42\n\n", "text/event-stream");
  19499. } else {
  19500. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19501. "\n\nevent: end\ndata: end\n\n",
  19502. "text/event-stream");
  19503. }
  19504. });
  19505. auto msgs = collect("/id-only");
  19506. ASSERT_EQ(msgs.size(), 1u);
  19507. EXPECT_EQ(msgs[0].data, "42");
  19508. }
  19509. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19510. // The first connection sets an id and then clears it with an empty one; the
  19511. // second reports whether it was reconnected with a Last-Event-ID
  19512. std::atomic<int> connection_count{0};
  19513. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19514. if (connection_count++ == 0) {
  19515. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19516. "text/event-stream");
  19517. } else {
  19518. res.set_content(
  19519. std::string("data: ") +
  19520. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19521. "\n\nevent: end\ndata: end\n\n",
  19522. "text/event-stream");
  19523. }
  19524. });
  19525. auto msgs = collect("/id-clear");
  19526. ASSERT_EQ(msgs.size(), 3u);
  19527. EXPECT_EQ(msgs[0].id, "1");
  19528. EXPECT_EQ(msgs[1].id, "");
  19529. EXPECT_EQ(msgs[2].data, "not sent");
  19530. }
  19531. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19532. // The first connection sets an id and then sends ids that cannot be carried
  19533. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19534. // with
  19535. std::atomic<int> connection_count{0};
  19536. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19537. if (connection_count++ == 0) {
  19538. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19539. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19540. "text/event-stream");
  19541. } else {
  19542. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19543. "\n\nevent: end\ndata: end\n\n",
  19544. "text/event-stream");
  19545. }
  19546. });
  19547. auto msgs = collect("/id-unsendable");
  19548. ASSERT_EQ(msgs.size(), 1u);
  19549. EXPECT_EQ(msgs[0].data, "42");
  19550. }
  19551. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19552. auto msgs = parse("event: notification\nid: evt-42\n"
  19553. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19554. ASSERT_EQ(msgs.size(), 1u);
  19555. EXPECT_EQ(msgs[0].event, "notification");
  19556. EXPECT_EQ(msgs[0].id, "evt-42");
  19557. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19558. }
  19559. TEST(SSEMessageTest, Clear) {
  19560. sse::SSEMessage msg;
  19561. msg.event = "custom";
  19562. msg.data = "some data";
  19563. msg.id = "123";
  19564. msg.clear();
  19565. EXPECT_EQ(msg.event, "message");
  19566. EXPECT_EQ(msg.data, "");
  19567. EXPECT_EQ(msg.id, "");
  19568. }
  19569. //==============================================================================
  19570. // SSE Integration Tests
  19571. //==============================================================================
  19572. // Test: Successful connection and on_open callback
  19573. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19574. // Add a simple endpoint that sends one event and closes
  19575. server_->Get("/simple-event", [](const Request &, Response &res) {
  19576. res.set_chunked_content_provider(
  19577. "text/event-stream", [](size_t offset, DataSink &sink) {
  19578. if (offset == 0) {
  19579. std::string event = "data: hello\n\n";
  19580. sink.write(event.data(), event.size());
  19581. }
  19582. return false; // Close stream after sending
  19583. });
  19584. });
  19585. Client client("localhost", get_port());
  19586. sse::SSEClient sse(client, "/simple-event");
  19587. std::atomic<bool> open_called{false};
  19588. std::atomic<bool> message_received{false};
  19589. sse.on_open([&open_called]() { open_called.store(true); });
  19590. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19591. if (msg.data == "hello") { message_received.store(true); }
  19592. });
  19593. sse.set_reconnect_interval(100);
  19594. sse.set_max_reconnect_attempts(1);
  19595. // Start async
  19596. sse.start_async();
  19597. // Wait for message to be processed
  19598. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19599. sse.stop();
  19600. EXPECT_TRUE(open_called.load());
  19601. EXPECT_TRUE(message_received.load());
  19602. }
  19603. // Test: on_message callback
  19604. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19605. // Endpoint that sends multiple events then closes
  19606. server_->Get("/multi-event", [](const Request &, Response &res) {
  19607. res.set_chunked_content_provider(
  19608. "text/event-stream", [](size_t offset, DataSink &sink) {
  19609. if (offset == 0) {
  19610. std::string events = "data: message1\n\ndata: message2\n\n";
  19611. sink.write(events.data(), events.size());
  19612. }
  19613. return false;
  19614. });
  19615. });
  19616. Client client("localhost", get_port());
  19617. sse::SSEClient sse(client, "/multi-event");
  19618. std::vector<std::string> received_messages;
  19619. std::mutex messages_mutex;
  19620. sse.on_message([&](const sse::SSEMessage &msg) {
  19621. std::lock_guard<std::mutex> lock(messages_mutex);
  19622. received_messages.push_back(msg.data);
  19623. });
  19624. sse.set_reconnect_interval(100);
  19625. sse.set_max_reconnect_attempts(1);
  19626. sse.start_async();
  19627. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19628. sse.stop();
  19629. std::lock_guard<std::mutex> lock(messages_mutex);
  19630. EXPECT_GE(received_messages.size(), 2u);
  19631. if (received_messages.size() >= 2) {
  19632. EXPECT_EQ(received_messages[0], "message1");
  19633. EXPECT_EQ(received_messages[1], "message2");
  19634. }
  19635. }
  19636. // Test: on_event for specific types
  19637. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19638. Client client("localhost", get_port());
  19639. sse::SSEClient sse(client, "/custom-events");
  19640. std::atomic<bool> update_received{false};
  19641. std::atomic<bool> delete_received{false};
  19642. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19643. if (msg.data == "updated") { update_received.store(true); }
  19644. });
  19645. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19646. if (msg.data == "deleted") { delete_received.store(true); }
  19647. });
  19648. sse.set_max_reconnect_attempts(1);
  19649. sse.start_async();
  19650. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19651. sse.stop();
  19652. EXPECT_TRUE(update_received.load());
  19653. EXPECT_TRUE(delete_received.load());
  19654. }
  19655. // Test: on_error callback on connection failure
  19656. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19657. // Connect to a non-existent port
  19658. Client client("localhost", 59999);
  19659. sse::SSEClient sse(client, "/events");
  19660. std::atomic<bool> error_called{false};
  19661. Error received_error = Error::Success;
  19662. sse.on_error([&](Error err) {
  19663. error_called.store(true);
  19664. received_error = err;
  19665. });
  19666. sse.set_reconnect_interval(50);
  19667. sse.set_max_reconnect_attempts(1);
  19668. sse.start_async();
  19669. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19670. sse.stop();
  19671. EXPECT_TRUE(error_called.load());
  19672. EXPECT_NE(received_error, Error::Success);
  19673. }
  19674. // Test: Last-Event-ID header sent on reconnect
  19675. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19676. // Endpoint that sends event with ID
  19677. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19678. res.set_chunked_content_provider(
  19679. "text/event-stream", [](size_t offset, DataSink &sink) {
  19680. if (offset == 0) {
  19681. std::string event = "id: evt-123\ndata: test\n\n";
  19682. sink.write(event.data(), event.size());
  19683. }
  19684. return false;
  19685. });
  19686. });
  19687. Client client("localhost", get_port());
  19688. sse::SSEClient sse(client, "/event-with-id");
  19689. std::atomic<bool> id_received{false};
  19690. sse.on_message([&](const sse::SSEMessage &msg) {
  19691. if (!msg.id.empty()) { id_received.store(true); }
  19692. });
  19693. sse.set_reconnect_interval(100);
  19694. sse.set_max_reconnect_attempts(1);
  19695. sse.start_async();
  19696. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19697. sse.stop();
  19698. EXPECT_TRUE(id_received.load());
  19699. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19700. }
  19701. // Test: Manual stop
  19702. TEST_F(SSEIntegrationTest, ManualStop) {
  19703. // Endpoint that sends one event and stays open briefly
  19704. std::atomic<bool> handler_running{true};
  19705. server_->Get("/stay-open", [&handler_running](const Request &,
  19706. Response &res) {
  19707. res.set_chunked_content_provider(
  19708. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19709. if (offset == 0) {
  19710. std::string event = "data: connected\n\n";
  19711. sink.write(event.data(), event.size());
  19712. }
  19713. // Keep connection open while handler_running is true
  19714. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19715. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19716. }
  19717. return false;
  19718. });
  19719. });
  19720. Client client("localhost", get_port());
  19721. sse::SSEClient sse(client, "/stay-open");
  19722. std::atomic<bool> connected{false};
  19723. sse.on_open([&connected]() { connected.store(true); });
  19724. sse.set_reconnect_interval(100);
  19725. sse.set_max_reconnect_attempts(1);
  19726. sse.start_async();
  19727. // Wait for connection to establish
  19728. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19729. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19730. }
  19731. EXPECT_TRUE(connected.load());
  19732. EXPECT_TRUE(sse.is_connected());
  19733. // Signal handler to stop
  19734. handler_running.store(false);
  19735. // Stop SSE client
  19736. sse.stop();
  19737. EXPECT_FALSE(sse.is_connected());
  19738. }
  19739. // Test: SSEClient with custom headers
  19740. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19741. // Setup a server endpoint that checks for custom header
  19742. std::atomic<bool> header_received{false};
  19743. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19744. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19745. header_received.store(true);
  19746. }
  19747. res.set_chunked_content_provider("text/event-stream",
  19748. [](size_t, DataSink &) { return false; });
  19749. });
  19750. Client client("localhost", get_port());
  19751. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19752. sse::SSEClient sse(client, "/header-check", headers);
  19753. sse.set_max_reconnect_attempts(1);
  19754. sse.start_async();
  19755. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19756. sse.stop();
  19757. EXPECT_TRUE(header_received.load());
  19758. }
  19759. // Test: Reconnect interval configuration
  19760. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19761. Client client("localhost", get_port());
  19762. sse::SSEClient sse(client, "/events");
  19763. auto &result = sse.set_reconnect_interval(500);
  19764. // Builder pattern should return reference to self
  19765. EXPECT_EQ(&result, &sse);
  19766. }
  19767. // Test: Max reconnect attempts
  19768. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19769. // Connect to non-existent port to force reconnects
  19770. Client client("localhost", 59998);
  19771. sse::SSEClient sse(client, "/events");
  19772. std::atomic<int> error_count{0};
  19773. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19774. sse.set_reconnect_interval(50);
  19775. sse.set_max_reconnect_attempts(2);
  19776. auto start = std::chrono::steady_clock::now();
  19777. sse.start(); // Blocking call
  19778. auto end = std::chrono::steady_clock::now();
  19779. // Should have stopped after 2 failed attempts
  19780. EXPECT_GE(error_count.load(), 2);
  19781. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19782. auto duration =
  19783. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19784. #ifdef _WIN32
  19785. // Windows is much slower for socket connection failures
  19786. EXPECT_LT(duration.count(), 7000);
  19787. #else
  19788. EXPECT_LT(duration.count(), 1000);
  19789. #endif
  19790. }
  19791. // Test: Multi-line data in integration
  19792. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19793. // Endpoint with multi-line data
  19794. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19795. res.set_chunked_content_provider(
  19796. "text/event-stream", [](size_t offset, DataSink &sink) {
  19797. if (offset == 0) {
  19798. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19799. sink.write(event.data(), event.size());
  19800. }
  19801. return false;
  19802. });
  19803. });
  19804. Client client("localhost", get_port());
  19805. sse::SSEClient sse(client, "/multiline-data");
  19806. std::string received_data;
  19807. std::mutex data_mutex;
  19808. sse.on_message([&](const sse::SSEMessage &msg) {
  19809. std::lock_guard<std::mutex> lock(data_mutex);
  19810. received_data = msg.data;
  19811. });
  19812. sse.set_reconnect_interval(100);
  19813. sse.set_max_reconnect_attempts(1);
  19814. sse.start_async();
  19815. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19816. sse.stop();
  19817. std::lock_guard<std::mutex> lock(data_mutex);
  19818. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19819. }
  19820. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19821. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19822. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19823. DataSink &sink) {
  19824. if (offset == 0) {
  19825. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19826. sink.write(events.data(), events.size());
  19827. }
  19828. return false;
  19829. });
  19830. });
  19831. Client client("localhost", get_port());
  19832. sse::SSEClient sse(client, "/empty-data-lines");
  19833. std::mutex mutex;
  19834. std::condition_variable cv;
  19835. std::vector<std::string> received;
  19836. sse.on_message([&](const sse::SSEMessage &msg) {
  19837. std::lock_guard<std::mutex> lock(mutex);
  19838. received.push_back(msg.data);
  19839. cv.notify_all();
  19840. });
  19841. sse.set_max_reconnect_attempts(1);
  19842. sse.start_async();
  19843. {
  19844. std::unique_lock<std::mutex> lock(mutex);
  19845. cv.wait_for(lock, std::chrono::seconds(2),
  19846. [&] { return received.size() >= 3; });
  19847. }
  19848. sse.stop();
  19849. ASSERT_GE(received.size(), 3u);
  19850. EXPECT_EQ(received[0], "");
  19851. EXPECT_EQ(received[1], "\nhello");
  19852. EXPECT_EQ(received[2], "");
  19853. }
  19854. // Test: Auto-reconnect after server disconnection
  19855. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19856. std::atomic<int> connection_count{0};
  19857. std::atomic<int> message_count{0};
  19858. // Endpoint that sends one event and closes, forcing reconnect
  19859. server_->Get("/reconnect-test",
  19860. [&connection_count](const Request &, Response &res) {
  19861. connection_count.fetch_add(1);
  19862. res.set_chunked_content_provider(
  19863. "text/event-stream", [](size_t offset, DataSink &sink) {
  19864. if (offset == 0) {
  19865. std::string event = "data: hello\n\n";
  19866. sink.write(event.data(), event.size());
  19867. }
  19868. return false; // Close connection after sending
  19869. });
  19870. });
  19871. Client client("localhost", get_port());
  19872. sse::SSEClient sse(client, "/reconnect-test");
  19873. sse.on_message([&message_count](const sse::SSEMessage &) {
  19874. message_count.fetch_add(1);
  19875. });
  19876. sse.set_reconnect_interval(100);
  19877. sse.set_max_reconnect_attempts(3);
  19878. sse.start_async();
  19879. // Wait long enough for multiple reconnects
  19880. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19881. sse.stop();
  19882. // Should have connected multiple times (initial + reconnects)
  19883. EXPECT_GE(connection_count.load(), 2);
  19884. // Should have received messages from multiple connections
  19885. EXPECT_GE(message_count.load(), 2);
  19886. }
  19887. // Test: A retry field that is not all ASCII digits is ignored
  19888. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19889. std::atomic<int> connection_count{0};
  19890. server_->Get("/bad-retry",
  19891. [&connection_count](const Request &, Response &res) {
  19892. connection_count.fetch_add(1);
  19893. res.set_chunked_content_provider(
  19894. "text/event-stream", [](size_t offset, DataSink &sink) {
  19895. if (offset == 0) {
  19896. std::string event = "retry: -1\ndata: hello\n\n";
  19897. sink.write(event.data(), event.size());
  19898. }
  19899. return false;
  19900. });
  19901. });
  19902. Client client("localhost", get_port());
  19903. sse::SSEClient sse(client, "/bad-retry");
  19904. sse.set_reconnect_interval(10000);
  19905. sse.start_async();
  19906. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19907. sse.stop();
  19908. EXPECT_EQ(connection_count.load(), 1);
  19909. }
  19910. // Test: A retry field of all ASCII digits sets the reconnection time
  19911. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19912. std::mutex mutex;
  19913. std::condition_variable cv;
  19914. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19915. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19916. {
  19917. std::lock_guard<std::mutex> lock(mutex);
  19918. connected_at.push_back(std::chrono::steady_clock::now());
  19919. cv.notify_all();
  19920. }
  19921. res.set_chunked_content_provider(
  19922. "text/event-stream", [](size_t offset, DataSink &sink) {
  19923. if (offset == 0) {
  19924. std::string event = "retry: 0\ndata: hello\n\n";
  19925. sink.write(event.data(), event.size());
  19926. }
  19927. return false;
  19928. });
  19929. });
  19930. Client client("localhost", get_port());
  19931. sse::SSEClient sse(client, "/zero-retry");
  19932. sse.set_reconnect_interval(10000);
  19933. sse.start_async();
  19934. {
  19935. std::unique_lock<std::mutex> lock(mutex);
  19936. cv.wait_for(lock, std::chrono::seconds(5),
  19937. [&] { return connected_at.size() >= 2; });
  19938. }
  19939. sse.stop();
  19940. // The server-supplied interval is applied, but never below 100ms, so
  19941. // "retry: 0" does not cause a busy reconnect loop
  19942. std::lock_guard<std::mutex> lock(mutex);
  19943. ASSERT_GE(connected_at.size(), 2u);
  19944. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  19945. connected_at[1] - connected_at[0])
  19946. .count();
  19947. EXPECT_GE(interval_ms, 100);
  19948. }
  19949. // Test: Last-Event-ID sent on reconnect
  19950. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19951. std::atomic<int> connection_count{0};
  19952. std::vector<std::string> received_last_event_ids;
  19953. std::mutex id_mutex;
  19954. // Endpoint that checks Last-Event-ID header and sends event with ID
  19955. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19956. int conn = connection_count.fetch_add(1);
  19957. // Capture the Last-Event-ID header from each connection
  19958. {
  19959. std::lock_guard<std::mutex> lock(id_mutex);
  19960. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19961. }
  19962. res.set_chunked_content_provider(
  19963. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19964. if (offset == 0) {
  19965. std::string event =
  19966. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19967. sink.write(event.data(), event.size());
  19968. }
  19969. return false;
  19970. });
  19971. });
  19972. Client client("localhost", get_port());
  19973. sse::SSEClient sse(client, "/reconnect-with-id");
  19974. sse.set_reconnect_interval(100);
  19975. sse.set_max_reconnect_attempts(3);
  19976. sse.start_async();
  19977. // Wait for at least 2 connections
  19978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19979. sse.stop();
  19980. // Verify behavior
  19981. std::lock_guard<std::mutex> lock(id_mutex);
  19982. EXPECT_GE(received_last_event_ids.size(), 2u);
  19983. // First connection should have no Last-Event-ID
  19984. if (!received_last_event_ids.empty()) {
  19985. EXPECT_EQ(received_last_event_ids[0], "");
  19986. }
  19987. // Second connection should have Last-Event-ID from first connection
  19988. if (received_last_event_ids.size() >= 2) {
  19989. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19990. }
  19991. }
  19992. // Test: set_headers updates headers used on reconnect
  19993. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19994. std::vector<std::string> received_tokens;
  19995. std::mutex token_mutex;
  19996. // Endpoint that captures Authorization header
  19997. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19998. {
  19999. std::lock_guard<std::mutex> lock(token_mutex);
  20000. received_tokens.push_back(req.get_header_value("Authorization"));
  20001. }
  20002. res.set_chunked_content_provider(
  20003. "text/event-stream", [](size_t offset, DataSink &sink) {
  20004. if (offset == 0) {
  20005. std::string event = "data: hello\n\n";
  20006. sink.write(event.data(), event.size());
  20007. }
  20008. return false; // Close connection to trigger reconnect
  20009. });
  20010. });
  20011. Client client("localhost", get_port());
  20012. Headers headers = {{"Authorization", "Bearer old-token"}};
  20013. sse::SSEClient sse(client, "/auth-check", headers);
  20014. // Update headers on each successful connection
  20015. sse.on_open(
  20016. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20017. sse.set_reconnect_interval(100);
  20018. sse.set_max_reconnect_attempts(3);
  20019. sse.start_async();
  20020. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20021. sse.stop();
  20022. std::lock_guard<std::mutex> lock(token_mutex);
  20023. ASSERT_GE(received_tokens.size(), 2u);
  20024. // First connection uses original header
  20025. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20026. // Second connection uses updated header from set_headers
  20027. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20028. }
  20029. // Test: 401 allows reconnection (so on_error can refresh headers)
  20030. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20031. std::atomic<int> connection_count{0};
  20032. // Endpoint: returns 401 on first attempt, 200 on second
  20033. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20034. int conn = connection_count.fetch_add(1);
  20035. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20036. res.status = StatusCode::Unauthorized_401;
  20037. res.set_content("Unauthorized", "text/plain");
  20038. return;
  20039. }
  20040. res.set_chunked_content_provider(
  20041. "text/event-stream", [](size_t offset, DataSink &sink) {
  20042. if (offset == 0) {
  20043. std::string event = "data: authenticated\n\n";
  20044. sink.write(event.data(), event.size());
  20045. }
  20046. return false;
  20047. });
  20048. });
  20049. Client client("localhost", get_port());
  20050. Headers headers = {{"Authorization", "Bearer expired"}};
  20051. sse::SSEClient sse(client, "/auth-retry", headers);
  20052. std::atomic<bool> message_received{false};
  20053. // Refresh token on error
  20054. sse.on_error(
  20055. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20056. sse.on_message([&](const sse::SSEMessage &msg) {
  20057. if (msg.data == "authenticated") { message_received.store(true); }
  20058. });
  20059. sse.set_reconnect_interval(100);
  20060. sse.set_max_reconnect_attempts(3);
  20061. sse.start_async();
  20062. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20063. sse.stop();
  20064. // Should have reconnected after 401 and succeeded with new token
  20065. EXPECT_GE(connection_count.load(), 2);
  20066. EXPECT_TRUE(message_received.load());
  20067. }
  20068. TEST(Issue2318Test, EmptyHostString) {
  20069. {
  20070. httplib::Client cli_empty("", PORT);
  20071. auto res = cli_empty.Get("/");
  20072. ASSERT_FALSE(res);
  20073. EXPECT_EQ(httplib::Error::Connection, res.error());
  20074. }
  20075. {
  20076. httplib::Client cli(" ", PORT);
  20077. auto res = cli.Get("/");
  20078. ASSERT_FALSE(res);
  20079. EXPECT_EQ(httplib::Error::Connection, res.error());
  20080. }
  20081. }
  20082. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20083. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20084. Server svr;
  20085. // Set a small payload limit (1KB)
  20086. svr.set_payload_max_length(1024);
  20087. svr.Post("/test", [&](const Request &req, Response &res) {
  20088. res.set_content("Body size: " + std::to_string(req.body.size()),
  20089. "text/plain");
  20090. });
  20091. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20092. auto se = detail::scope_exit([&] {
  20093. svr.stop();
  20094. listen_thread.join();
  20095. });
  20096. svr.wait_until_ready();
  20097. // Create data that compresses well but exceeds limit when decompressed
  20098. // 8KB of repeated null bytes compresses to a very small size
  20099. std::string original_data(8 * 1024, '\0');
  20100. // Compress the data using gzip
  20101. std::string compressed_data;
  20102. detail::gzip_compressor compressor;
  20103. compressor.compress(original_data.data(), original_data.size(), true,
  20104. [&](const char *data, size_t size) {
  20105. compressed_data.append(data, size);
  20106. return true;
  20107. });
  20108. // Verify compression worked (compressed should be much smaller)
  20109. ASSERT_LT(compressed_data.size(), original_data.size());
  20110. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20111. // Send compressed data with Content-Encoding: gzip
  20112. Client cli(HOST, PORT);
  20113. Headers headers = {{"Content-Encoding", "gzip"}};
  20114. auto res =
  20115. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20116. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20118. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20119. }
  20120. #endif
  20121. // ============================================================================
  20122. // OpenSSL-Specific Tests
  20123. // ============================================================================
  20124. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20125. X509 *readCertificate(const std::string &strFileName) {
  20126. std::ifstream inStream(strFileName);
  20127. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20128. std::istreambuf_iterator<char>());
  20129. if (strCertPEM.empty()) return (nullptr);
  20130. BIO *pbCert = BIO_new(BIO_s_mem());
  20131. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20132. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20133. BIO_free(pbCert);
  20134. return (pCert);
  20135. }
  20136. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20137. std::ifstream inStream(strFileName);
  20138. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20139. std::istreambuf_iterator<char>());
  20140. if (strPrivateKeyPEM.empty()) return (nullptr);
  20141. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20142. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20143. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20144. BIO_free(pbPrivKey);
  20145. return (pPrivateKey);
  20146. }
  20147. TEST(BindServerTest, UpdateCerts) {
  20148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20149. int port = svr.bind_to_any_port("0.0.0.0");
  20150. ASSERT_TRUE(svr.is_valid());
  20151. ASSERT_TRUE(port > 0);
  20152. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20153. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20154. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20155. ASSERT_TRUE(cert != nullptr);
  20156. ASSERT_TRUE(ca_cert != nullptr);
  20157. ASSERT_TRUE(key != nullptr);
  20158. X509_STORE *cert_store = X509_STORE_new();
  20159. X509_STORE_add_cert(cert_store, ca_cert);
  20160. // svr.update_certs(cert, key, cert_store); // deprecated
  20161. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20162. CLIENT_CA_CERT_FILE);
  20163. ASSERT_TRUE(svr.is_valid());
  20164. svr.stop();
  20165. X509_STORE_free(cert_store);
  20166. X509_free(cert);
  20167. X509_free(ca_cert);
  20168. EVP_PKEY_free(key);
  20169. }
  20170. // Test that update_certs() updates client CA list correctly
  20171. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20172. // Start with file-based constructor
  20173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20174. ASSERT_TRUE(svr.is_valid());
  20175. // Initially no client CA list should be set
  20176. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20177. ASSERT_TRUE(ssl_ctx != nullptr);
  20178. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20179. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20180. EXPECT_EQ(0, count_before);
  20181. // Now update with client CA (PEM string)
  20182. std::string cert_pem, key_pem, ca_pem;
  20183. read_file(SERVER_CERT_FILE, cert_pem);
  20184. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20185. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20186. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20187. ASSERT_TRUE(svr.is_valid());
  20188. // Now client CA list should be set
  20189. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20190. ASSERT_TRUE(ca_list_after != nullptr);
  20191. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20192. }
  20193. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20194. // Test that the file-path SSLServer constructor properly sets the client CA
  20195. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20197. ASSERT_TRUE(svr.is_valid());
  20198. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20199. ASSERT_TRUE(ssl_ctx != nullptr);
  20200. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20201. ASSERT_TRUE(ca_list != nullptr);
  20202. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20203. }
  20204. #endif
  20205. // ============================================================================
  20206. // MbedTLS-Specific Tests
  20207. // ============================================================================
  20208. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20209. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20210. using namespace httplib::tls;
  20211. // Track if callback was invoked
  20212. bool callback_invoked = false;
  20213. // The callback receives void* ctx which is actually MbedTlsContext*
  20214. // We can access the mbedtls_ssl_config via the context
  20215. auto setup_callback = [&callback_invoked](void *ctx) {
  20216. callback_invoked = true;
  20217. // Cast to MbedTlsContext* to access the ssl config
  20218. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20219. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20220. // Use static variables to hold certificate data (simplified for test)
  20221. static mbedtls_x509_crt own_cert;
  20222. static mbedtls_pk_context own_key;
  20223. static mbedtls_x509_crt ca_chain;
  20224. static bool initialized = false;
  20225. if (!initialized) {
  20226. mbedtls_x509_crt_init(&own_cert);
  20227. mbedtls_pk_init(&own_key);
  20228. mbedtls_x509_crt_init(&ca_chain);
  20229. // Load server certificate
  20230. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20231. return false;
  20232. }
  20233. // Load server private key.
  20234. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20235. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20236. #if MBEDTLS_VERSION_MAJOR == 3
  20237. ,
  20238. mbedtls_ctr_drbg_random, nullptr
  20239. #endif
  20240. ) != 0) {
  20241. return false;
  20242. }
  20243. // Load CA chain for client verification
  20244. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20245. return false;
  20246. }
  20247. initialized = true;
  20248. }
  20249. // Configure the SSL config
  20250. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20251. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20252. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20253. // Set minimum TLS version using mbedTLS native API
  20254. #if MBEDTLS_VERSION_MAJOR >= 3
  20255. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20256. #else
  20257. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20258. MBEDTLS_SSL_MINOR_VERSION_3);
  20259. #endif
  20260. return true;
  20261. };
  20262. SSLServer svr(setup_callback);
  20263. ASSERT_TRUE(svr.is_valid());
  20264. ASSERT_TRUE(callback_invoked);
  20265. svr.Get("/test", [&](const Request &req, Response &res) {
  20266. res.set_content("test", "text/plain");
  20267. auto cert = req.peer_cert();
  20268. ASSERT_TRUE(static_cast<bool>(cert));
  20269. auto common_name = cert.subject_cn();
  20270. EXPECT_EQ("Common Name", common_name);
  20271. });
  20272. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20273. auto se = detail::scope_exit([&] {
  20274. svr.stop();
  20275. t.join();
  20276. ASSERT_FALSE(svr.is_running());
  20277. });
  20278. svr.wait_until_ready();
  20279. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20280. cli.enable_server_certificate_verification(false);
  20281. cli.set_connection_timeout(30);
  20282. auto res = cli.Get("/test");
  20283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20284. ASSERT_EQ(StatusCode::OK_200, res->status);
  20285. }
  20286. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20287. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20288. // keep-alive SSL session, which reads through that config in
  20289. // mbedtls_ssl_close_notify.
  20290. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20292. ASSERT_TRUE(svr.is_valid());
  20293. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20294. res.set_content("test", "text/plain");
  20295. });
  20296. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20297. auto se = detail::scope_exit([&] {
  20298. svr.stop();
  20299. t.join();
  20300. ASSERT_FALSE(svr.is_running());
  20301. });
  20302. svr.wait_until_ready();
  20303. {
  20304. SSLClient cli(HOST, PORT);
  20305. cli.enable_server_certificate_verification(false);
  20306. cli.set_keep_alive(true);
  20307. auto res = cli.Get("/test");
  20308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20309. ASSERT_EQ(StatusCode::OK_200, res->status);
  20310. // cli is destructed here with the keep-alive SSL session still open.
  20311. }
  20312. }
  20313. #endif
  20314. // WebSocket Tests
  20315. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20316. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20317. // defining the meaning of these bits has been negotiated.
  20318. auto make_frame = [](uint8_t first_byte) {
  20319. std::string frame;
  20320. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20321. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20322. frame += "Hello";
  20323. return frame;
  20324. };
  20325. // RSV1 set (0x40)
  20326. {
  20327. detail::BufferStream strm;
  20328. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20329. ws::Opcode opcode;
  20330. std::string payload;
  20331. bool fin;
  20332. EXPECT_EQ(
  20333. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20334. ws::impl::FrameRead::Fail);
  20335. }
  20336. // RSV2 set (0x20)
  20337. {
  20338. detail::BufferStream strm;
  20339. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20340. ws::Opcode opcode;
  20341. std::string payload;
  20342. bool fin;
  20343. EXPECT_EQ(
  20344. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20345. ws::impl::FrameRead::Fail);
  20346. }
  20347. // RSV3 set (0x10)
  20348. {
  20349. detail::BufferStream strm;
  20350. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20351. ws::Opcode opcode;
  20352. std::string payload;
  20353. bool fin;
  20354. EXPECT_EQ(
  20355. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20356. ws::impl::FrameRead::Fail);
  20357. }
  20358. // No RSV bits set - should succeed
  20359. {
  20360. detail::BufferStream strm;
  20361. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20362. ws::Opcode opcode;
  20363. std::string payload;
  20364. bool fin;
  20365. EXPECT_EQ(
  20366. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20367. ws::impl::FrameRead::Ok);
  20368. EXPECT_EQ(ws::Opcode::Text, opcode);
  20369. EXPECT_EQ("Hello", payload);
  20370. EXPECT_TRUE(fin);
  20371. }
  20372. }
  20373. TEST(WebSocketTest, ControlFrameValidation) {
  20374. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20375. // payload length <= 125.
  20376. // Ping with FIN=0 - must be rejected
  20377. {
  20378. detail::BufferStream strm;
  20379. std::string frame;
  20380. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20381. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20382. strm.write(frame.data(), frame.size());
  20383. ws::Opcode opcode;
  20384. std::string payload;
  20385. bool fin;
  20386. EXPECT_EQ(
  20387. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20388. ws::impl::FrameRead::Fail);
  20389. }
  20390. // Close with FIN=0 - must be rejected
  20391. {
  20392. detail::BufferStream strm;
  20393. std::string frame;
  20394. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20395. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20396. strm.write(frame.data(), frame.size());
  20397. ws::Opcode opcode;
  20398. std::string payload;
  20399. bool fin;
  20400. EXPECT_EQ(
  20401. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20402. ws::impl::FrameRead::Fail);
  20403. }
  20404. // Ping with payload_len=126 (extended length) - must be rejected
  20405. {
  20406. detail::BufferStream strm;
  20407. std::string frame;
  20408. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20409. frame += static_cast<char>(126); // payload_len=126 (>125)
  20410. frame += static_cast<char>(0x00); // extended length high byte
  20411. frame += static_cast<char>(126); // extended length low byte
  20412. frame += std::string(126, 'x');
  20413. strm.write(frame.data(), frame.size());
  20414. ws::Opcode opcode;
  20415. std::string payload;
  20416. bool fin;
  20417. EXPECT_EQ(
  20418. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20419. ws::impl::FrameRead::Fail);
  20420. }
  20421. // Ping with FIN=1 and payload_len=125 - should succeed
  20422. {
  20423. detail::BufferStream strm;
  20424. std::string frame;
  20425. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20426. frame += static_cast<char>(125); // payload_len=125
  20427. frame += std::string(125, 'x');
  20428. strm.write(frame.data(), frame.size());
  20429. ws::Opcode opcode;
  20430. std::string payload;
  20431. bool fin;
  20432. EXPECT_EQ(
  20433. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20434. ws::impl::FrameRead::Ok);
  20435. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20436. EXPECT_EQ(125u, payload.size());
  20437. EXPECT_TRUE(fin);
  20438. }
  20439. }
  20440. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20441. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20442. // length MUST be 0.
  20443. // MSB set - must be rejected
  20444. {
  20445. detail::BufferStream strm;
  20446. std::string frame;
  20447. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20448. frame += static_cast<char>(127); // 64-bit extended length
  20449. frame += static_cast<char>(0x80); // MSB set (invalid)
  20450. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20451. strm.write(frame.data(), frame.size());
  20452. ws::Opcode opcode;
  20453. std::string payload;
  20454. bool fin;
  20455. EXPECT_EQ(
  20456. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20457. ws::impl::FrameRead::Fail);
  20458. }
  20459. // MSB clear - should pass length parsing (will be rejected by max_len,
  20460. // but that's a different check; use a small length to verify)
  20461. {
  20462. detail::BufferStream strm;
  20463. std::string frame;
  20464. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20465. frame += static_cast<char>(127); // 64-bit extended length
  20466. frame += std::string(7, '\0'); // high bytes = 0
  20467. frame += static_cast<char>(0x03); // length = 3
  20468. frame += "abc";
  20469. strm.write(frame.data(), frame.size());
  20470. ws::Opcode opcode;
  20471. std::string payload;
  20472. bool fin;
  20473. EXPECT_EQ(
  20474. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20475. ws::impl::FrameRead::Ok);
  20476. EXPECT_EQ(ws::Opcode::Text, opcode);
  20477. EXPECT_EQ("abc", payload);
  20478. }
  20479. }
  20480. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20481. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20482. // Valid UTF-8
  20483. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20484. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20485. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20486. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20487. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20488. // Invalid UTF-8
  20489. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20490. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20491. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20492. EXPECT_FALSE(
  20493. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20494. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20495. }
  20496. TEST(WebSocketTest, ConnectAndDisconnect) {
  20497. Server svr;
  20498. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20499. std::string msg;
  20500. while (ws.read(msg)) {}
  20501. });
  20502. auto port = svr.bind_to_any_port(HOST);
  20503. std::thread t([&]() { svr.listen_after_bind(); });
  20504. svr.wait_until_ready();
  20505. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20506. auto res = client.connect();
  20507. ASSERT_TRUE(res);
  20508. EXPECT_EQ(Error::Success, res.error());
  20509. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20510. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20511. EXPECT_TRUE(client.is_open());
  20512. client.close();
  20513. EXPECT_FALSE(client.is_open());
  20514. svr.stop();
  20515. t.join();
  20516. }
  20517. TEST(WebSocketTest, ValidURL) {
  20518. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20519. EXPECT_TRUE(ws1.is_valid());
  20520. ws::WebSocketClient ws2("ws://example.com/path");
  20521. EXPECT_TRUE(ws2.is_valid());
  20522. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20523. EXPECT_TRUE(ws3.is_valid());
  20524. #ifdef CPPHTTPLIB_SSL_ENABLED
  20525. ws::WebSocketClient wss1("wss://example.com/path");
  20526. EXPECT_TRUE(wss1.is_valid());
  20527. ws::WebSocketClient wss2("wss://example.com:443/path");
  20528. EXPECT_TRUE(wss2.is_valid());
  20529. #endif
  20530. }
  20531. TEST(WebSocketTest, InvalidURL) {
  20532. // No scheme
  20533. ws::WebSocketClient ws1("localhost:8080/path");
  20534. EXPECT_FALSE(ws1.is_valid());
  20535. // No path
  20536. ws::WebSocketClient ws2("ws://localhost:8080");
  20537. EXPECT_FALSE(ws2.is_valid());
  20538. // Empty string
  20539. ws::WebSocketClient ws3("");
  20540. EXPECT_FALSE(ws3.is_valid());
  20541. // Missing host
  20542. ws::WebSocketClient ws4("ws://:8080/path");
  20543. EXPECT_FALSE(ws4.is_valid());
  20544. // Port number overflow — should not crash
  20545. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20546. EXPECT_FALSE(ws5.is_valid());
  20547. // Port out of range
  20548. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20549. EXPECT_FALSE(ws6.is_valid());
  20550. }
  20551. TEST(WebSocketTest, UnsupportedScheme) {
  20552. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20553. ws::WebSocketClient ws1("http://localhost:8080/path");
  20554. EXPECT_FALSE(ws1.is_valid());
  20555. ws::WebSocketClient ws2("https://localhost:8080/path");
  20556. EXPECT_FALSE(ws2.is_valid());
  20557. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20558. EXPECT_FALSE(ws3.is_valid());
  20559. #else
  20560. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20561. std::invalid_argument);
  20562. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20563. std::invalid_argument);
  20564. #endif
  20565. }
  20566. TEST(WebSocketTest, ConnectWhenInvalid) {
  20567. ws::WebSocketClient ws("not a valid url");
  20568. EXPECT_FALSE(ws.is_valid());
  20569. auto res = ws.connect();
  20570. EXPECT_FALSE(res);
  20571. EXPECT_EQ(Error::Connection, res.error());
  20572. EXPECT_EQ(-1, res.status());
  20573. }
  20574. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20575. // Grab a port that is free, then close it again so nothing listens there
  20576. Server svr;
  20577. auto port = svr.bind_to_any_port(HOST);
  20578. svr.stop();
  20579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20580. auto res = client.connect();
  20581. ASSERT_FALSE(res);
  20582. EXPECT_EQ(Error::Connection, res.error());
  20583. EXPECT_EQ(-1, res.status());
  20584. }
  20585. TEST(WebSocketTest, DefaultPort) {
  20586. ws::WebSocketClient ws1("ws://example.com/path");
  20587. EXPECT_TRUE(ws1.is_valid());
  20588. // ws:// defaults to port 80 (verified by successful parse)
  20589. #ifdef CPPHTTPLIB_SSL_ENABLED
  20590. ws::WebSocketClient ws2("wss://example.com/path");
  20591. EXPECT_TRUE(ws2.is_valid());
  20592. // wss:// defaults to port 443 (verified by successful parse)
  20593. #endif
  20594. }
  20595. TEST(WebSocketTest, IPv6LiteralAddress) {
  20596. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20597. EXPECT_TRUE(ws1.is_valid());
  20598. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20599. EXPECT_TRUE(ws2.is_valid());
  20600. }
  20601. TEST(WebSocketTest, ComplexPath) {
  20602. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20603. EXPECT_TRUE(ws1.is_valid());
  20604. ws::WebSocketClient ws2("ws://localhost:8080/");
  20605. EXPECT_TRUE(ws2.is_valid());
  20606. }
  20607. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20608. Server svr;
  20609. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20610. std::string msg;
  20611. while (ws.read(msg)) {}
  20612. });
  20613. auto port = svr.bind_to_any_port(HOST);
  20614. std::thread t([&]() { svr.listen_after_bind(); });
  20615. svr.wait_until_ready();
  20616. auto another_host = "example.com";
  20617. auto wrong_ip = "192.0.2.1";
  20618. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20619. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20620. ASSERT_TRUE(client.connect());
  20621. EXPECT_TRUE(client.is_open());
  20622. client.close();
  20623. svr.stop();
  20624. t.join();
  20625. }
  20626. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20627. Server svr;
  20628. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20629. std::string msg;
  20630. while (ws.read(msg)) {}
  20631. });
  20632. auto port = svr.bind_to_any_port(HOST);
  20633. std::thread t([&]() { svr.listen_after_bind(); });
  20634. svr.wait_until_ready();
  20635. auto wrong_ip = "192.0.2.1";
  20636. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20637. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20638. client.set_connection_timeout(1);
  20639. client.set_read_timeout(1);
  20640. client.set_write_timeout(1);
  20641. EXPECT_FALSE(client.connect());
  20642. EXPECT_FALSE(client.is_open());
  20643. svr.stop();
  20644. t.join();
  20645. }
  20646. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20647. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20648. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20649. // (RFC 6761) is only a map key and the Host header value.
  20650. auto host = "target.invalid";
  20651. Server svr;
  20652. std::string received_host;
  20653. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20654. received_host = req.get_header_value("Host");
  20655. std::string msg;
  20656. while (ws.read(msg)) {}
  20657. });
  20658. auto port = svr.bind_to_any_port(HOST);
  20659. std::thread t([&]() { svr.listen_after_bind(); });
  20660. // ASSERT_* below returns from the test body, which would leave t joinable
  20661. // and make ~thread call std::terminate.
  20662. auto se = detail::scope_exit([&] {
  20663. svr.stop();
  20664. if (t.joinable()) { t.join(); }
  20665. });
  20666. svr.wait_until_ready();
  20667. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20668. std::to_string(port) + "/ws");
  20669. client.set_hostname_addr_map({{host, HOST}});
  20670. ASSERT_TRUE(client.connect());
  20671. EXPECT_TRUE(client.is_open());
  20672. client.close();
  20673. svr.stop();
  20674. t.join();
  20675. // The mapping only redirects the connection; the identity stays host_.
  20676. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20677. }
  20678. class WebSocketIntegrationTest : public ::testing::Test {
  20679. protected:
  20680. void SetUp() override {
  20681. server_ = httplib::detail::make_unique<Server>();
  20682. setup_server();
  20683. start_server();
  20684. }
  20685. void TearDown() override {
  20686. server_->stop();
  20687. if (server_thread_.joinable()) { server_thread_.join(); }
  20688. }
  20689. void setup_server() {
  20690. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20691. std::string msg;
  20692. ws::ReadResult ret;
  20693. while ((ret = ws.read(msg))) {
  20694. if (ret == ws::Binary) {
  20695. ws.send(msg.data(), msg.size());
  20696. } else {
  20697. ws.send(msg);
  20698. }
  20699. }
  20700. });
  20701. server_->WebSocket("/ws-echo-string",
  20702. [](const Request &, ws::WebSocket &ws) {
  20703. std::string msg;
  20704. while (ws.read(msg)) {
  20705. ws.send("echo: " + msg);
  20706. }
  20707. });
  20708. server_->WebSocket(
  20709. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20710. // Echo back request metadata
  20711. ws.send("path:" + req.path);
  20712. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20713. std::string msg;
  20714. while (ws.read(msg)) {}
  20715. });
  20716. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20717. std::string msg;
  20718. ws.read(msg); // wait for a message
  20719. ws.close();
  20720. });
  20721. server_->WebSocket("/ws-close-status",
  20722. [](const Request &, ws::WebSocket &ws) {
  20723. std::string msg;
  20724. ws.read(msg); // wait for a message
  20725. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20726. });
  20727. server_->WebSocket(
  20728. "/ws-subprotocol",
  20729. [](const Request &, ws::WebSocket &ws) {
  20730. std::string msg;
  20731. while (ws.read(msg)) {
  20732. ws.send(msg);
  20733. }
  20734. },
  20735. [](const std::vector<std::string> &protocols) -> std::string {
  20736. for (const auto &p : protocols) {
  20737. if (p == "graphql-ws") { return p; }
  20738. }
  20739. return "";
  20740. });
  20741. server_->WebSocket(
  20742. "/ws-subprotocol-unoffered",
  20743. [](const Request &, ws::WebSocket &ws) {
  20744. std::string msg;
  20745. while (ws.read(msg)) {
  20746. ws.send(msg);
  20747. }
  20748. },
  20749. [](const std::vector<std::string> &) -> std::string {
  20750. return "admin";
  20751. });
  20752. }
  20753. void start_server() {
  20754. port_ = server_->bind_to_any_port(HOST);
  20755. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20756. server_->wait_until_ready();
  20757. }
  20758. std::unique_ptr<Server> server_;
  20759. std::thread server_thread_;
  20760. int port_ = 0;
  20761. };
  20762. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20764. "/ws-echo");
  20765. ASSERT_TRUE(client.connect());
  20766. ASSERT_TRUE(client.is_open());
  20767. ASSERT_TRUE(client.send("Hello WebSocket"));
  20768. std::string msg;
  20769. EXPECT_EQ(ws::Text, client.read(msg));
  20770. EXPECT_EQ("Hello WebSocket", msg);
  20771. client.close();
  20772. }
  20773. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20774. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20775. "/ws-echo");
  20776. ASSERT_TRUE(client.connect());
  20777. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20778. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20779. std::string msg;
  20780. EXPECT_EQ(ws::Binary, client.read(msg));
  20781. EXPECT_EQ(binary_data, msg);
  20782. client.close();
  20783. }
  20784. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20785. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20786. "/ws-echo");
  20787. ASSERT_TRUE(client.connect());
  20788. for (int i = 0; i < 10; i++) {
  20789. auto text = "message " + std::to_string(i);
  20790. ASSERT_TRUE(client.send(text));
  20791. std::string msg;
  20792. ASSERT_TRUE(client.read(msg));
  20793. EXPECT_EQ(text, msg);
  20794. }
  20795. client.close();
  20796. }
  20797. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20799. "/ws-close");
  20800. ASSERT_TRUE(client.connect());
  20801. // Send a message to trigger the server to close
  20802. ASSERT_TRUE(client.send("trigger close"));
  20803. // The server will close, so read should return false
  20804. std::string msg;
  20805. EXPECT_FALSE(client.read(msg));
  20806. EXPECT_FALSE(client.is_open());
  20807. }
  20808. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20809. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20810. "/ws-echo");
  20811. ASSERT_TRUE(client.connect());
  20812. // 128KB message
  20813. std::string large_data(128 * 1024, 'X');
  20814. ASSERT_TRUE(client.send(large_data));
  20815. std::string msg;
  20816. ASSERT_TRUE(client.read(msg));
  20817. EXPECT_EQ(large_data, msg);
  20818. client.close();
  20819. }
  20820. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20821. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20822. "/ws-echo");
  20823. ASSERT_TRUE(client.connect());
  20824. const int num_threads = 4;
  20825. std::vector<std::thread> threads;
  20826. std::atomic<int> send_count{0};
  20827. for (int t = 0; t < num_threads; t++) {
  20828. threads.emplace_back([&client, &send_count, t]() {
  20829. for (int i = 0; i < 5; i++) {
  20830. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20831. if (client.send(text)) { send_count++; }
  20832. }
  20833. });
  20834. }
  20835. for (auto &th : threads) {
  20836. th.join();
  20837. }
  20838. int received = 0;
  20839. std::string msg;
  20840. while (received < send_count.load()) {
  20841. if (!client.read(msg)) { break; }
  20842. received++;
  20843. }
  20844. EXPECT_EQ(send_count.load(), received);
  20845. client.close();
  20846. }
  20847. TEST_F(WebSocketIntegrationTest, ReadString) {
  20848. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20849. "/ws-echo-string");
  20850. ASSERT_TRUE(client.connect());
  20851. ASSERT_TRUE(client.send("hello"));
  20852. std::string msg;
  20853. ASSERT_TRUE(client.read(msg));
  20854. EXPECT_EQ("echo: hello", msg);
  20855. ASSERT_TRUE(client.send("world"));
  20856. ASSERT_TRUE(client.read(msg));
  20857. EXPECT_EQ("echo: world", msg);
  20858. client.close();
  20859. }
  20860. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20861. Headers headers = {{"X-Test-Header", "test-value"}};
  20862. ws::WebSocketClient client(
  20863. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20864. ASSERT_TRUE(client.connect());
  20865. std::string msg;
  20866. ASSERT_TRUE(client.read(msg));
  20867. EXPECT_EQ("path:/ws-request-info", msg);
  20868. ASSERT_TRUE(client.read(msg));
  20869. EXPECT_EQ("header:test-value", msg);
  20870. client.close();
  20871. }
  20872. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20874. "/ws-echo");
  20875. client.set_read_timeout(1, 0); // 1 second
  20876. ASSERT_TRUE(client.connect());
  20877. // Don't send anything — server echo handler waits for a message, so read()
  20878. // should time out. The connection survives it: nothing was consumed.
  20879. std::string msg;
  20880. EXPECT_EQ(client.read(msg), ws::Timeout);
  20881. EXPECT_TRUE(client.is_open());
  20882. // And it is still usable afterwards.
  20883. EXPECT_TRUE(client.send("after timeout"));
  20884. EXPECT_EQ(client.read(msg), ws::Text);
  20885. EXPECT_EQ(msg, "after timeout");
  20886. }
  20887. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20889. "/ws-echo");
  20890. client.set_read_timeout(1, 0);
  20891. ASSERT_TRUE(client.connect());
  20892. ASSERT_TRUE(client.send("first"));
  20893. std::string msg;
  20894. ASSERT_EQ(client.read(msg), ws::Text);
  20895. ASSERT_EQ(msg, "first");
  20896. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20897. // not be used with a read timeout: it would reprocess the previous message.
  20898. EXPECT_EQ(client.read(msg), ws::Timeout);
  20899. EXPECT_EQ(msg, "first");
  20900. }
  20901. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20902. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20903. "/ws-echo");
  20904. ASSERT_TRUE(client.connect());
  20905. // Setting it once the connection is open reaches the live stream, not just
  20906. // the seed for the next connect().
  20907. client.set_read_timeout(1, 0);
  20908. std::string msg;
  20909. EXPECT_EQ(client.read(msg), ws::Timeout);
  20910. EXPECT_TRUE(client.is_open());
  20911. }
  20912. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20913. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20914. "/ws-echo");
  20915. client.set_read_timeout(5, 0);
  20916. ASSERT_TRUE(client.connect());
  20917. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20918. // The server should reject it and close the connection.
  20919. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20920. client.send(oversized);
  20921. // The server's read() should have failed due to payload limit,
  20922. // so our read() should return false (connection closed).
  20923. std::string msg;
  20924. EXPECT_FALSE(client.read(msg));
  20925. }
  20926. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20927. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20928. "/ws-echo");
  20929. client.set_read_timeout(10, 0);
  20930. ASSERT_TRUE(client.connect());
  20931. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20932. // This should succeed.
  20933. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20934. ASSERT_TRUE(client.send(at_limit));
  20935. std::string msg;
  20936. ASSERT_TRUE(client.read(msg));
  20937. EXPECT_EQ(at_limit.size(), msg.size());
  20938. client.close();
  20939. }
  20940. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20942. "/nonexistent");
  20943. auto res = client.connect();
  20944. EXPECT_FALSE(res);
  20945. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20946. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20947. EXPECT_FALSE(client.is_open());
  20948. }
  20949. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20950. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20951. "/ws-echo");
  20952. ASSERT_TRUE(client.connect());
  20953. ASSERT_TRUE(client.send(""));
  20954. std::string msg;
  20955. EXPECT_EQ(ws::Text, client.read(msg));
  20956. EXPECT_EQ("", msg);
  20957. client.close();
  20958. }
  20959. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20961. "/ws-echo");
  20962. // First connection
  20963. ASSERT_TRUE(client.connect());
  20964. ASSERT_TRUE(client.send("first"));
  20965. std::string msg;
  20966. ASSERT_TRUE(client.read(msg));
  20967. EXPECT_EQ("first", msg);
  20968. client.close();
  20969. EXPECT_FALSE(client.is_open());
  20970. // Reconnect using the same client object
  20971. ASSERT_TRUE(client.connect());
  20972. ASSERT_TRUE(client.is_open());
  20973. ASSERT_TRUE(client.send("second"));
  20974. ASSERT_TRUE(client.read(msg));
  20975. EXPECT_EQ("second", msg);
  20976. client.close();
  20977. }
  20978. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20979. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20980. "/ws-close-status");
  20981. ASSERT_TRUE(client.connect());
  20982. // Trigger the server to close with GoingAway status
  20983. ASSERT_TRUE(client.send("trigger"));
  20984. // read() should return false after receiving the close frame
  20985. std::string msg;
  20986. EXPECT_FALSE(client.read(msg));
  20987. EXPECT_FALSE(client.is_open());
  20988. }
  20989. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20991. "/ws-echo");
  20992. ASSERT_TRUE(client.connect());
  20993. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20994. EXPECT_FALSE(client.is_open());
  20995. }
  20996. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20997. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20998. ws::WebSocketClient client(
  20999. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21000. ASSERT_TRUE(client.connect());
  21001. // Server should have selected graphql-ws
  21002. EXPECT_EQ("graphql-ws", client.subprotocol());
  21003. client.close();
  21004. }
  21005. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21006. Headers headers;
  21007. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21008. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21009. ws::WebSocketClient client(
  21010. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21011. ASSERT_TRUE(client.connect());
  21012. // The offer on the second field line counts too, so graphql-ws is selected
  21013. EXPECT_EQ("graphql-ws", client.subprotocol());
  21014. client.close();
  21015. }
  21016. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21017. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21018. ws::WebSocketClient client(
  21019. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21020. ASSERT_TRUE(client.connect());
  21021. // Server should not have selected any subprotocol
  21022. EXPECT_TRUE(client.subprotocol().empty());
  21023. client.close();
  21024. }
  21025. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21026. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21027. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21028. "/ws-subprotocol-unoffered",
  21029. headers);
  21030. ASSERT_TRUE(client.connect());
  21031. EXPECT_TRUE(client.subprotocol().empty());
  21032. client.close();
  21033. }
  21034. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21035. // Connect without requesting any subprotocol
  21036. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21037. "/ws-subprotocol");
  21038. ASSERT_TRUE(client.connect());
  21039. EXPECT_TRUE(client.subprotocol().empty());
  21040. client.close();
  21041. }
  21042. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21043. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21044. "/ws-echo");
  21045. client.set_tcp_nodelay(true);
  21046. client.set_connection_timeout(3, 0);
  21047. bool socket_options_called = false;
  21048. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21049. ASSERT_TRUE(client.connect());
  21050. ASSERT_TRUE(client.is_open());
  21051. EXPECT_TRUE(socket_options_called);
  21052. ASSERT_TRUE(client.send("hello"));
  21053. std::string msg;
  21054. auto result = client.read(msg);
  21055. EXPECT_EQ(result, ws::ReadResult::Text);
  21056. EXPECT_EQ(msg, "hello");
  21057. client.close();
  21058. }
  21059. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21060. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21061. "/ws-echo");
  21062. client.set_connection_timeout(std::chrono::seconds(3));
  21063. client.set_write_timeout(std::chrono::seconds(3));
  21064. // A sub-second remainder exercises the seconds/microseconds split.
  21065. client.set_read_timeout(std::chrono::milliseconds(1500));
  21066. ASSERT_TRUE(client.connect());
  21067. auto start = std::chrono::steady_clock::now();
  21068. std::string msg;
  21069. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21070. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21071. std::chrono::steady_clock::now() - start)
  21072. .count();
  21073. // Above 1s so that dropping the microseconds half of the split fails here.
  21074. // Ignoring the setter altogether would not reach this line at all: a client
  21075. // waits forever by default.
  21076. EXPECT_GE(elapsed, 1400);
  21077. EXPECT_LT(elapsed, 30000);
  21078. }
  21079. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21080. Server svr;
  21081. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21082. if (!req.has_header("Authorization")) {
  21083. res.status = StatusCode::Unauthorized_401;
  21084. res.set_content("Unauthorized", "text/plain");
  21085. return Server::HandlerResponse::Handled;
  21086. }
  21087. return Server::HandlerResponse::Unhandled;
  21088. });
  21089. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21090. std::string msg;
  21091. while (ws.read(msg)) {
  21092. ws.send(msg);
  21093. }
  21094. });
  21095. auto port = svr.bind_to_any_port("localhost");
  21096. std::thread t([&]() { svr.listen_after_bind(); });
  21097. svr.wait_until_ready();
  21098. // Without Authorization header - should be rejected before upgrade
  21099. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21100. EXPECT_FALSE(client1.connect());
  21101. // The rejection is framed like any other HTTP response
  21102. {
  21103. Client cli("localhost", port);
  21104. Headers headers = {{"Upgrade", "websocket"},
  21105. {"Connection", "Upgrade"},
  21106. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21107. {"Sec-WebSocket-Version", "13"}};
  21108. auto res = cli.Get("/ws", headers);
  21109. ASSERT_TRUE(res);
  21110. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21111. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21112. EXPECT_EQ("Unauthorized", res->body);
  21113. }
  21114. // With Authorization header - should succeed
  21115. Headers headers = {{"Authorization", "Bearer token123"}};
  21116. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21117. headers);
  21118. ASSERT_TRUE(client2.connect());
  21119. ASSERT_TRUE(client2.send("hello"));
  21120. std::string msg;
  21121. ASSERT_TRUE(client2.read(msg));
  21122. EXPECT_EQ("hello", msg);
  21123. client2.close();
  21124. svr.stop();
  21125. t.join();
  21126. }
  21127. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21128. Server svr;
  21129. std::atomic<int> pre_request_calls{0};
  21130. std::atomic<bool> route_matched{false};
  21131. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21132. pre_request_calls++;
  21133. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21134. if (req.get_header_value("Authorization") != "Bearer token123") {
  21135. res.status = StatusCode::Unauthorized_401;
  21136. res.set_content("Unauthorized", "text/plain");
  21137. return Server::HandlerResponse::Handled;
  21138. }
  21139. return Server::HandlerResponse::Unhandled;
  21140. });
  21141. std::atomic<bool> handler_called{false};
  21142. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21143. handler_called = true;
  21144. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21145. });
  21146. auto port = svr.bind_to_any_port("localhost");
  21147. std::thread t([&]() { svr.listen_after_bind(); });
  21148. svr.wait_until_ready();
  21149. // Without Authorization header - should be rejected before upgrade
  21150. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21151. "/ws/1");
  21152. EXPECT_FALSE(client1.connect());
  21153. EXPECT_FALSE(handler_called);
  21154. EXPECT_EQ(1, pre_request_calls);
  21155. EXPECT_TRUE(route_matched);
  21156. // The rejection is an ordinary HTTP response, not a protocol switch
  21157. {
  21158. Client cli("localhost", port);
  21159. Headers headers = {{"Upgrade", "websocket"},
  21160. {"Connection", "Upgrade"},
  21161. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21162. {"Sec-WebSocket-Version", "13"}};
  21163. auto res = cli.Get("/ws/1", headers);
  21164. ASSERT_TRUE(res);
  21165. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21166. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21167. EXPECT_EQ("Unauthorized", res->body);
  21168. }
  21169. EXPECT_FALSE(handler_called);
  21170. // With Authorization header - should succeed
  21171. Headers headers = {{"Authorization", "Bearer token123"}};
  21172. ws::WebSocketClient client2(
  21173. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21174. ASSERT_TRUE(client2.connect());
  21175. std::string msg;
  21176. ASSERT_TRUE(client2.read(msg));
  21177. EXPECT_EQ("/ws/:id 2", msg);
  21178. EXPECT_TRUE(handler_called);
  21179. client2.close();
  21180. svr.stop();
  21181. t.join();
  21182. }
  21183. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21184. Server svr;
  21185. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21186. // A read timeout is how a handler gets control back. Without it, a handler
  21187. // parked in read() can never write on the connection it is reading.
  21188. ws.set_read_timeout(std::chrono::milliseconds(100));
  21189. std::string msg;
  21190. while (ws.is_open()) {
  21191. auto r = ws.read(msg);
  21192. if (r == httplib::ws::Timeout) {
  21193. ws.send("tick");
  21194. continue;
  21195. }
  21196. if (r == httplib::ws::Fail) { break; }
  21197. ws.send(msg);
  21198. }
  21199. });
  21200. auto port = svr.bind_to_any_port("localhost");
  21201. std::thread t([&]() { svr.listen_after_bind(); });
  21202. svr.wait_until_ready();
  21203. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21204. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21205. ASSERT_TRUE(client.connect());
  21206. // The client sends nothing, so anything it receives came out of the
  21207. // handler's timeout path.
  21208. std::string msg;
  21209. ASSERT_EQ(client.read(msg), ws::Text);
  21210. EXPECT_EQ("tick", msg);
  21211. client.close();
  21212. svr.stop();
  21213. t.join();
  21214. }
  21215. // Stream::read may return fewer bytes than asked for. This is that contract at
  21216. // its worst -- one byte per call -- which is what a frame header straddling a
  21217. // read buffer's boundary looks like to the frame parser.
  21218. class WsByteAtATimeStream : public Stream {
  21219. public:
  21220. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21221. bool is_readable() const override { return true; }
  21222. bool wait_readable() const override { return true; }
  21223. bool wait_writable() const override { return true; }
  21224. ssize_t read(char *ptr, size_t size) override {
  21225. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21226. *ptr = data_[pos_++];
  21227. return 1;
  21228. }
  21229. ssize_t write(const char *, size_t size) override {
  21230. return static_cast<ssize_t>(size);
  21231. }
  21232. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21233. ip = "127.0.0.1";
  21234. port = 0;
  21235. }
  21236. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21237. ip = "127.0.0.1";
  21238. port = 0;
  21239. }
  21240. socket_t socket() const override { return INVALID_SOCKET; }
  21241. time_t duration() const override { return 0; }
  21242. private:
  21243. std::string data_;
  21244. size_t pos_ = 0;
  21245. };
  21246. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21247. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21248. // length and the mask key are all multi-byte fields here. Each used to be
  21249. // read with a single read() call, which fails as soon as one is split.
  21250. std::string body(200, 'x');
  21251. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21252. std::string frame;
  21253. frame += static_cast<char>(0x81); // FIN + Text
  21254. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21255. frame += static_cast<char>(body.size() >> 8);
  21256. frame += static_cast<char>(body.size() & 0xff);
  21257. for (size_t i = 0; i < 4; i++) {
  21258. frame += static_cast<char>(mask[i]);
  21259. }
  21260. for (size_t i = 0; i < body.size(); i++) {
  21261. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21262. }
  21263. WsByteAtATimeStream strm(frame);
  21264. ws::Opcode opcode;
  21265. std::string payload;
  21266. bool fin = false;
  21267. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21268. /*expect_masked=*/true, 1024),
  21269. ws::impl::FrameRead::Ok);
  21270. EXPECT_TRUE(fin);
  21271. EXPECT_EQ(opcode, ws::Opcode::Text);
  21272. EXPECT_EQ(payload, body);
  21273. }
  21274. TEST(WebSocketTest, QueryStringInHandshake) {
  21275. Server svr;
  21276. std::mutex mtx;
  21277. std::string received_target;
  21278. std::string received_token;
  21279. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21280. {
  21281. std::lock_guard<std::mutex> lock(mtx);
  21282. received_target = req.target;
  21283. if (req.has_param("token")) {
  21284. received_token = req.get_param_value("token");
  21285. }
  21286. }
  21287. std::string msg;
  21288. while (ws.read(msg)) {
  21289. ws.send(msg);
  21290. }
  21291. });
  21292. auto port = svr.bind_to_any_port("localhost");
  21293. std::thread t([&]() { svr.listen_after_bind(); });
  21294. svr.wait_until_ready();
  21295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21296. "/ws?token=ABC&session=123");
  21297. ASSERT_TRUE(client.connect());
  21298. // Round-trip ensures the handler has run and captured the request.
  21299. ASSERT_TRUE(client.send("hello"));
  21300. std::string msg;
  21301. ASSERT_TRUE(client.read(msg));
  21302. EXPECT_EQ("hello", msg);
  21303. client.close();
  21304. {
  21305. std::lock_guard<std::mutex> lock(mtx);
  21306. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21307. EXPECT_EQ("ABC", received_token);
  21308. }
  21309. svr.stop();
  21310. t.join();
  21311. }
  21312. // Run a handshake against a throwaway server and hand the request the server
  21313. // received back to the caller, so tests can assert on the headers the client
  21314. // actually put on the wire.
  21315. static void capture_websocket_handshake_request(
  21316. const Headers &client_headers,
  21317. std::function<void(const Request &, int port)> verify) {
  21318. Server svr;
  21319. std::mutex mtx;
  21320. Request received;
  21321. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21322. {
  21323. std::lock_guard<std::mutex> lock(mtx);
  21324. received = req;
  21325. }
  21326. std::string msg;
  21327. while (ws.read(msg)) {
  21328. ws.send(msg);
  21329. }
  21330. });
  21331. auto port = svr.bind_to_any_port("localhost");
  21332. std::thread t([&]() { svr.listen_after_bind(); });
  21333. auto se = detail::scope_exit([&] {
  21334. svr.stop();
  21335. t.join();
  21336. });
  21337. svr.wait_until_ready();
  21338. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21339. client_headers);
  21340. ASSERT_TRUE(client.connect());
  21341. ASSERT_TRUE(client.send("hello"));
  21342. std::string msg;
  21343. ASSERT_TRUE(client.read(msg));
  21344. client.close();
  21345. {
  21346. std::lock_guard<std::mutex> lock(mtx);
  21347. verify(received, port);
  21348. }
  21349. }
  21350. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21351. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21352. // Non-default port must be present in the Host header. Default ports
  21353. // (80/443) are omitted; that logic is covered by
  21354. // MakeHostAndPortStringTest.
  21355. EXPECT_EQ("localhost:" + std::to_string(port),
  21356. req.get_header_value("Host"));
  21357. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21358. req.get_header_value("User-Agent"));
  21359. EXPECT_FALSE(req.has_header("Accept"));
  21360. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21361. EXPECT_FALSE(req.has_header("Content-Length"));
  21362. });
  21363. }
  21364. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21365. capture_websocket_handshake_request(
  21366. {{"Host", "example.com"},
  21367. {"User-Agent", "custom-agent"},
  21368. {"X-Custom", "value"}},
  21369. [](const Request &req, int) {
  21370. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21371. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21372. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21373. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21374. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21375. });
  21376. }
  21377. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21378. capture_websocket_handshake_request(
  21379. {{"Upgrade", "bogus"},
  21380. {"Connection", "close"},
  21381. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21382. {"Sec-WebSocket-Version", "8"}},
  21383. [](const Request &req, int) {
  21384. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21385. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21386. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21387. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21388. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21389. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21390. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21391. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21392. req.get_header_value("Sec-WebSocket-Key"));
  21393. });
  21394. }
  21395. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21396. // A header the client refuses to send must abort the handshake before any
  21397. // part of it reaches the wire; a lone request line would otherwise sit in
  21398. // the peer's buffer as a truncated request.
  21399. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21400. ASSERT_NE(INVALID_SOCKET, srv);
  21401. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21402. sockaddr_in addr{};
  21403. addr.sin_family = AF_INET;
  21404. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21405. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21406. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21407. ASSERT_EQ(0, ::listen(srv, 1));
  21408. sockaddr_in bound{};
  21409. socklen_t bound_len = sizeof(bound);
  21410. ASSERT_EQ(
  21411. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21412. auto port = ntohs(bound.sin_port);
  21413. ssize_t received = -1;
  21414. std::thread t([&] {
  21415. // Bound every blocking call so a regression fails the test with a bad
  21416. // value instead of hanging the suite.
  21417. fd_set rfds;
  21418. FD_ZERO(&rfds);
  21419. FD_SET(srv, &rfds);
  21420. timeval tv{5, 0};
  21421. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21422. 0) {
  21423. return;
  21424. }
  21425. sockaddr_in cli_addr{};
  21426. socklen_t cli_len = sizeof(cli_addr);
  21427. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21428. if (cli == INVALID_SOCKET) { return; }
  21429. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21430. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21431. char buf[4096];
  21432. received = ::recv(cli, buf, sizeof(buf), 0);
  21433. });
  21434. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21435. // connect() has already shut the socket down by the time it returns false,
  21436. // so the peer sees EOF without waiting for the client to be destroyed.
  21437. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21438. {{"X-Bad", "a\r\nInjected: 1"}});
  21439. EXPECT_FALSE(client.connect());
  21440. t.join();
  21441. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21442. EXPECT_EQ(0, received);
  21443. }
  21444. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21445. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21446. // contains "upgrade" as a substring is a different token and must not
  21447. // start a WebSocket handshake.
  21448. auto make_request = [](const std::vector<std::string> &connection_values) {
  21449. Request req;
  21450. req.method = "GET";
  21451. req.headers.emplace("Upgrade", "websocket");
  21452. for (const auto &value : connection_values) {
  21453. req.headers.emplace("Connection", value);
  21454. }
  21455. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21456. req.headers.emplace("Sec-WebSocket-Version", "13");
  21457. return req;
  21458. };
  21459. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21460. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21461. EXPECT_TRUE(
  21462. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21463. EXPECT_TRUE(
  21464. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21465. EXPECT_TRUE(
  21466. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21467. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21468. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21469. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21470. EXPECT_FALSE(
  21471. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21472. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21473. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21474. }
  21475. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21476. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21477. // asks recipients to match each protocol-name case-insensitively, and RFC
  21478. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21479. // client naming websocket alongside another protocol, or on a second field
  21480. // line, is offering websocket; a value that merely contains "websocket" as a
  21481. // substring is a different protocol name and is not.
  21482. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21483. Request req;
  21484. req.method = "GET";
  21485. for (const auto &value : upgrade_values) {
  21486. req.headers.emplace("Upgrade", value);
  21487. }
  21488. req.headers.emplace("Connection", "Upgrade");
  21489. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21490. req.headers.emplace("Sec-WebSocket-Version", "13");
  21491. return req;
  21492. };
  21493. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21494. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21495. EXPECT_TRUE(
  21496. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21497. EXPECT_TRUE(
  21498. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21499. EXPECT_TRUE(
  21500. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21501. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21502. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21503. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21504. EXPECT_FALSE(
  21505. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21506. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21507. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21508. }
  21509. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21510. Server svr;
  21511. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21512. auto port = svr.bind_to_any_port("localhost");
  21513. std::thread t([&]() { svr.listen_after_bind(); });
  21514. auto se = detail::scope_exit([&] {
  21515. svr.stop();
  21516. t.join();
  21517. });
  21518. svr.wait_until_ready();
  21519. Headers headers = {{"Upgrade", "websocket"},
  21520. {"Connection", "notupgrade"},
  21521. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21522. {"Sec-WebSocket-Version", "13"}};
  21523. Client cli("localhost", port);
  21524. auto res = cli.Get("/ws", headers);
  21525. // The route exists only as a WebSocket route, so a request that fails the
  21526. // handshake check falls through to ordinary routing.
  21527. ASSERT_TRUE(res);
  21528. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21529. }
  21530. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21531. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21532. // Connection value is the only thing left for the client to reject.
  21533. Server svr;
  21534. svr.Get("/ws", [](const Request &req, Response &res) {
  21535. res.status = StatusCode::SwitchingProtocol_101;
  21536. res.set_header("Upgrade", "websocket");
  21537. res.set_header("Connection", "notupgrade");
  21538. res.set_header("Sec-WebSocket-Accept",
  21539. detail::websocket_accept_key(
  21540. req.get_header_value("Sec-WebSocket-Key")));
  21541. });
  21542. auto port = svr.bind_to_any_port("localhost");
  21543. std::thread t([&]() { svr.listen_after_bind(); });
  21544. auto se = detail::scope_exit([&] {
  21545. svr.stop();
  21546. t.join();
  21547. });
  21548. svr.wait_until_ready();
  21549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21550. auto res = client.connect();
  21551. EXPECT_FALSE(res);
  21552. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21553. EXPECT_FALSE(client.is_open());
  21554. }
  21555. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21556. Server svr;
  21557. svr.Get("/ws", [](const Request &req, Response &res) {
  21558. res.status = StatusCode::SwitchingProtocol_101;
  21559. res.set_header("Upgrade", "websocket");
  21560. res.set_header("Connection", "Upgrade");
  21561. res.set_header("Sec-WebSocket-Accept",
  21562. detail::websocket_accept_key(
  21563. req.get_header_value("Sec-WebSocket-Key")));
  21564. res.set_header("Sec-WebSocket-Protocol", "admin");
  21565. });
  21566. auto port = svr.bind_to_any_port("localhost");
  21567. std::thread t([&]() { svr.listen_after_bind(); });
  21568. auto se = detail::scope_exit([&] {
  21569. svr.stop();
  21570. t.join();
  21571. });
  21572. svr.wait_until_ready();
  21573. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21574. // Server selects a subprotocol the client never offered
  21575. {
  21576. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21577. ws::WebSocketClient client(url, headers);
  21578. auto res = client.connect();
  21579. EXPECT_FALSE(res);
  21580. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21581. EXPECT_FALSE(client.is_open());
  21582. EXPECT_TRUE(client.subprotocol().empty());
  21583. }
  21584. // Client offered none but the server named one anyway
  21585. {
  21586. ws::WebSocketClient client(url);
  21587. auto res = client.connect();
  21588. EXPECT_FALSE(res);
  21589. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21590. EXPECT_FALSE(client.is_open());
  21591. EXPECT_TRUE(client.subprotocol().empty());
  21592. }
  21593. }
  21594. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21595. // The socket path doubles as the URL host, so it must not contain '/'.
  21596. const char *shard = getenv("GTEST_SHARD_INDEX");
  21597. const std::string sock_path =
  21598. shard ? std::string("httplib-ws-") + shard + ".sock"
  21599. : std::string("httplib-ws.sock");
  21600. std::remove(sock_path.c_str());
  21601. Server svr;
  21602. std::mutex mtx;
  21603. std::string received_host;
  21604. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21605. {
  21606. std::lock_guard<std::mutex> lock(mtx);
  21607. received_host = req.get_header_value("Host");
  21608. }
  21609. std::string msg;
  21610. while (ws.read(msg)) {
  21611. ws.send(msg);
  21612. }
  21613. });
  21614. svr.set_address_family(AF_UNIX);
  21615. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21616. auto se = detail::scope_exit([&] {
  21617. svr.stop();
  21618. t.join();
  21619. std::remove(sock_path.c_str());
  21620. });
  21621. svr.wait_until_ready();
  21622. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21623. client.set_address_family(AF_UNIX);
  21624. ASSERT_TRUE(client.connect());
  21625. ASSERT_TRUE(client.send("hello"));
  21626. std::string msg;
  21627. ASSERT_TRUE(client.read(msg));
  21628. client.close();
  21629. {
  21630. std::lock_guard<std::mutex> lock(mtx);
  21631. // There is no host:port for a Unix socket, so the same "localhost"
  21632. // placeholder the HTTP client uses is expected.
  21633. EXPECT_EQ("localhost", received_host);
  21634. }
  21635. }
  21636. // Two threads must never parse WebSocket frames from the same stream.
  21637. // close() used to read the peer's Close reply with its own frame read, so it
  21638. // raced a reader thread that was in the middle of a payload: the payload loop
  21639. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21640. // so bytes taken by close() were replaced with bytes from further along the
  21641. // stream. The message kept its length and silently changed content.
  21642. //
  21643. // The raw peer below sends a frame header plus part of the payload, waits for
  21644. // the handler to call close(), and only then sends the rest. Whichever thread
  21645. // would win the race for those bytes, the message must arrive intact, because
  21646. // close() must not touch the stream while read() owns it.
  21647. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21648. #ifndef _WIN32
  21649. signal(SIGPIPE, SIG_IGN);
  21650. #endif
  21651. const size_t payload_len = 120; // fits the 7-bit length field
  21652. const size_t prefix_len = 8;
  21653. const int attempts = 8;
  21654. std::string expected(payload_len, '\0');
  21655. for (size_t i = 0; i < payload_len; i++) {
  21656. expected[i] = static_cast<char>('a' + i % 26);
  21657. }
  21658. std::atomic<bool> peer_stalled{false};
  21659. std::atomic<bool> handler_done{false};
  21660. std::mutex received_mutex;
  21661. std::vector<std::string> received;
  21662. // Bound every wait, so a regression fails the test instead of hanging the
  21663. // suite.
  21664. auto wait_for = [](const std::atomic<bool> &flag) {
  21665. for (int i = 0; i < 500 && !flag; i++) {
  21666. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21667. }
  21668. };
  21669. Server svr;
  21670. svr.set_websocket_ping_interval(0);
  21671. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21672. std::thread reader([&]() {
  21673. std::string msg;
  21674. while (ws.read(msg)) {
  21675. std::lock_guard<std::mutex> guard(received_mutex);
  21676. received.push_back(msg);
  21677. }
  21678. });
  21679. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21680. // inside read_websocket_frame() when close() runs.
  21681. wait_for(peer_stalled);
  21682. ws.close();
  21683. reader.join();
  21684. handler_done = true;
  21685. });
  21686. auto port = svr.bind_to_any_port("127.0.0.1");
  21687. std::thread t([&]() { svr.listen_after_bind(); });
  21688. auto se = detail::scope_exit([&] {
  21689. svr.stop();
  21690. t.join();
  21691. });
  21692. svr.wait_until_ready();
  21693. auto send_bytes = [](socket_t s, const std::string &data) {
  21694. #ifdef _WIN32
  21695. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21696. #else
  21697. auto n = ::send(s, data.data(), data.size(), 0);
  21698. #endif
  21699. return n == static_cast<decltype(n)>(data.size());
  21700. };
  21701. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21702. // Every length used here fits the 7-bit length field.
  21703. auto masked_header = [](uint8_t first_byte, size_t len) {
  21704. std::string h;
  21705. h += static_cast<char>(first_byte);
  21706. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21707. h.append(4, '\0'); // mask key
  21708. return h;
  21709. };
  21710. for (int attempt = 0; attempt < attempts; attempt++) {
  21711. peer_stalled = false;
  21712. handler_done = false;
  21713. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21714. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21715. auto se_sock = detail::scope_exit([&] {
  21716. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21717. });
  21718. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21719. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21720. sockaddr_in addr{};
  21721. addr.sin_family = AF_INET;
  21722. addr.sin_port = htons(static_cast<uint16_t>(port));
  21723. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21724. ASSERT_EQ(
  21725. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21726. << "attempt " << attempt;
  21727. ASSERT_TRUE(send_bytes(sock,
  21728. "GET /ws HTTP/1.1\r\n"
  21729. "Host: 127.0.0.1\r\n"
  21730. "Upgrade: websocket\r\n"
  21731. "Connection: Upgrade\r\n"
  21732. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21733. "Sec-WebSocket-Version: 13\r\n"
  21734. "\r\n"))
  21735. << "attempt " << attempt;
  21736. std::string response;
  21737. while (response.find("\r\n\r\n") == std::string::npos) {
  21738. char buf[512];
  21739. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21740. if (n <= 0) { break; }
  21741. response.append(buf, static_cast<size_t>(n));
  21742. }
  21743. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21744. << "attempt " << attempt;
  21745. // Send the header of a Binary message but only the first prefix_len bytes
  21746. // of its payload, leaving the reader thread stalled inside the payload.
  21747. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21748. expected.substr(0, prefix_len)))
  21749. << "attempt " << attempt;
  21750. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21751. peer_stalled = true;
  21752. // Let close() send its Close frame and park in its own read before the
  21753. // rest of the payload arrives, so both threads are waiting for it.
  21754. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21755. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21756. close_frame += static_cast<char>(0x03); // status 1000
  21757. close_frame += static_cast<char>(0xE8);
  21758. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21759. << "attempt " << attempt;
  21760. // Closing the peer releases the reader thread even on the buggy path,
  21761. // where it waits for bytes another thread already consumed.
  21762. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21763. detail::close_socket(sock);
  21764. sock = INVALID_SOCKET;
  21765. wait_for(handler_done);
  21766. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21767. }
  21768. std::lock_guard<std::mutex> guard(received_mutex);
  21769. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21770. << "a message in flight when close() ran was dropped";
  21771. for (size_t i = 0; i < received.size(); i++) {
  21772. EXPECT_EQ(expected, received[i]) << "message " << i;
  21773. }
  21774. }
  21775. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21776. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21777. protected:
  21778. void SetUp() override {
  21779. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21780. SERVER_PRIVATE_KEY_FILE);
  21781. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21782. std::string msg;
  21783. ws::ReadResult ret;
  21784. while ((ret = ws.read(msg))) {
  21785. if (ret == ws::Binary) {
  21786. ws.send(msg.data(), msg.size());
  21787. } else {
  21788. ws.send(msg);
  21789. }
  21790. }
  21791. });
  21792. port_ = server_->bind_to_any_port(HOST);
  21793. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21794. server_->wait_until_ready();
  21795. }
  21796. void TearDown() override {
  21797. server_->stop();
  21798. if (server_thread_.joinable()) { server_thread_.join(); }
  21799. }
  21800. std::unique_ptr<SSLServer> server_;
  21801. std::thread server_thread_;
  21802. int port_ = 0;
  21803. };
  21804. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21805. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21806. "/ws-echo");
  21807. client.enable_server_certificate_verification(false);
  21808. ASSERT_TRUE(client.connect());
  21809. ASSERT_TRUE(client.is_open());
  21810. ASSERT_TRUE(client.send("Hello WSS"));
  21811. std::string msg;
  21812. EXPECT_EQ(ws::Text, client.read(msg));
  21813. EXPECT_EQ("Hello WSS", msg);
  21814. client.close();
  21815. }
  21816. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21817. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21818. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21819. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21820. // client (without calling close() first) is the only path that runs
  21821. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21822. // bug exactly.
  21823. //
  21824. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21825. // when linked against an instrumented libssl; run under Valgrind to catch it
  21826. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21827. // suite (the freed session otherwise stalls on the close handshake) — this test
  21828. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21829. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21830. {
  21831. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21832. "/ws-echo");
  21833. client.enable_server_certificate_verification(false);
  21834. client.set_read_timeout(2, 0);
  21835. client.set_write_timeout(2, 0);
  21836. ASSERT_TRUE(client.connect());
  21837. ASSERT_TRUE(client.is_open());
  21838. ASSERT_TRUE(client.send("still open"));
  21839. // Intentionally do NOT call client.close(): leaving scope runs
  21840. // shutdown_and_close() with the WebSocket still open, which must send the
  21841. // close frame while the TLS session is still alive.
  21842. }
  21843. }
  21844. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21845. // shutdown_and_close() at the start of connect(), reproducing the same
  21846. // use-after-free within the test body rather than at scope exit. The second
  21847. // connect must succeed and echo, proving the close handshake ran over a live
  21848. // session. See the note above about memory-tool requirements.
  21849. TEST_F(WebSocketSSLIntegrationTest,
  21850. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21851. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21852. "/ws-echo");
  21853. client.enable_server_certificate_verification(false);
  21854. client.set_read_timeout(2, 0);
  21855. client.set_write_timeout(2, 0);
  21856. ASSERT_TRUE(client.connect());
  21857. ASSERT_TRUE(client.is_open());
  21858. ASSERT_TRUE(client.send("still open"));
  21859. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21860. // the still-open connection, which must not touch a freed TLS session.
  21861. ASSERT_TRUE(client.connect());
  21862. ASSERT_TRUE(client.is_open());
  21863. ASSERT_TRUE(client.send("after reconnect"));
  21864. std::string msg;
  21865. EXPECT_EQ(ws::Text, client.read(msg));
  21866. EXPECT_EQ("after reconnect", msg);
  21867. client.close();
  21868. }
  21869. #endif
  21870. #ifdef CPPHTTPLIB_SSL_ENABLED
  21871. class WebSocketSSLCATest : public ::testing::Test {
  21872. protected:
  21873. void SetUp() override {
  21874. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21875. SERVER_PRIVATE_KEY_FILE);
  21876. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21877. std::string msg;
  21878. while (ws.read(msg)) {
  21879. ws.send(msg);
  21880. }
  21881. });
  21882. port_ = server_->bind_to_any_port("127.0.0.1");
  21883. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21884. server_->wait_until_ready();
  21885. }
  21886. void TearDown() override {
  21887. server_->stop();
  21888. if (server_thread_.joinable()) { server_thread_.join(); }
  21889. }
  21890. std::string url() const {
  21891. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21892. }
  21893. std::unique_ptr<SSLServer> server_;
  21894. std::thread server_thread_;
  21895. int port_ = 0;
  21896. };
  21897. // A custom CA loaded as PEM verifies the server with full certificate
  21898. // verification enabled
  21899. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21900. ws::WebSocketClient client(url());
  21901. std::string cert;
  21902. read_file(SERVER_CERT2_FILE, cert);
  21903. client.load_ca_cert_store(cert.c_str(), cert.size());
  21904. ASSERT_TRUE(client.connect());
  21905. ASSERT_TRUE(client.send("hello"));
  21906. std::string msg;
  21907. EXPECT_EQ(ws::Text, client.read(msg));
  21908. EXPECT_EQ("hello", msg);
  21909. client.close();
  21910. }
  21911. // A custom CA that does not cover the server must fail verification (the
  21912. // custom CA is exclusive; system certs are not loaded alongside it)
  21913. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21914. ws::WebSocketClient client(url());
  21915. std::string cert;
  21916. read_file(CLIENT_CA_CERT_FILE, cert);
  21917. client.load_ca_cert_store(cert.c_str(), cert.size());
  21918. auto res = client.connect();
  21919. ASSERT_FALSE(res);
  21920. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21921. EXPECT_EQ(-1, res.status());
  21922. EXPECT_NE(0u, res.ssl_backend_error());
  21923. }
  21924. // The same CA as a file path rather than PEM in memory
  21925. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21926. ws::WebSocketClient client(url());
  21927. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21928. ASSERT_TRUE(client.connect());
  21929. ASSERT_TRUE(client.send("hello"));
  21930. std::string msg;
  21931. EXPECT_EQ(ws::Text, client.read(msg));
  21932. EXPECT_EQ("hello", msg);
  21933. client.close();
  21934. }
  21935. // ...and a CA file that does not cover the server still fails, so it is the
  21936. // path above that decides the outcome
  21937. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21938. ws::WebSocketClient client(url());
  21939. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21940. ASSERT_FALSE(client.connect());
  21941. }
  21942. // Regression test: reconnecting with a native custom CA store used to reuse
  21943. // a store handle the previous TLS context had already freed (use-after-free
  21944. // under the OpenSSL backend). The context now lives as long as the client.
  21945. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21946. ws::WebSocketClient client(url());
  21947. std::string cert;
  21948. read_file(SERVER_CERT2_FILE, cert);
  21949. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21950. ASSERT_TRUE(client.connect());
  21951. client.close();
  21952. ASSERT_TRUE(client.connect());
  21953. ASSERT_TRUE(client.send("again"));
  21954. std::string msg;
  21955. EXPECT_EQ(ws::Text, client.read(msg));
  21956. EXPECT_EQ("again", msg);
  21957. client.close();
  21958. }
  21959. // Regression test: a certificate with a trusted chain but no identity match
  21960. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21961. // verification entirely for IP hosts, so this connection succeeded there.
  21962. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21963. // chain verification while the identity check must still fail.
  21964. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21965. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21966. ASSERT_TRUE(svr.is_valid());
  21967. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21968. std::string msg;
  21969. while (ws.read(msg)) {
  21970. ws.send(msg);
  21971. }
  21972. });
  21973. auto port = svr.bind_to_any_port("127.0.0.1");
  21974. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21975. auto se = detail::scope_exit([&] {
  21976. svr.stop();
  21977. t.join();
  21978. });
  21979. svr.wait_until_ready();
  21980. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21981. "/echo");
  21982. std::string cert;
  21983. read_file(SERVER_CERT_FILE, cert);
  21984. client.load_ca_cert_store(cert.c_str(), cert.size());
  21985. ASSERT_FALSE(client.connect());
  21986. }
  21987. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21988. // SNI, so nothing binds the host name to the TLS session. These bind the
  21989. // server to "localhost" instead, the only shape that exercises the SNI and
  21990. // hostname-verification path with certificate verification left enabled.
  21991. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21992. protected:
  21993. void Start(const char *cert_file) {
  21994. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21995. SERVER_PRIVATE_KEY_FILE);
  21996. ASSERT_TRUE(server_->is_valid());
  21997. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21998. std::string msg;
  21999. while (ws.read(msg)) {
  22000. ws.send(msg);
  22001. }
  22002. });
  22003. port_ = server_->bind_to_any_port("localhost");
  22004. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22005. server_->wait_until_ready();
  22006. }
  22007. void TearDown() override {
  22008. if (server_) { server_->stop(); }
  22009. if (server_thread_.joinable()) { server_thread_.join(); }
  22010. }
  22011. std::string url() const {
  22012. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22013. }
  22014. std::unique_ptr<SSLServer> server_;
  22015. std::thread server_thread_;
  22016. int port_ = 0;
  22017. };
  22018. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22019. // out and the connection is usable
  22020. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22021. Start(SERVER_CERT2_FILE);
  22022. ws::WebSocketClient client(url());
  22023. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22024. ASSERT_TRUE(client.connect());
  22025. ASSERT_TRUE(client.send("hello"));
  22026. std::string msg;
  22027. EXPECT_EQ(ws::Text, client.read(msg));
  22028. EXPECT_EQ("hello", msg);
  22029. client.close();
  22030. }
  22031. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22032. // while the identity check must still reject "localhost"
  22033. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22034. Start(SERVER_CERT_FILE);
  22035. ws::WebSocketClient client(url());
  22036. client.set_ca_cert_path(SERVER_CERT_FILE);
  22037. auto res = client.connect();
  22038. ASSERT_FALSE(res);
  22039. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22040. EXPECT_EQ(-1, res.status());
  22041. }
  22042. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22043. // disabled: the chain is still checked, only the identity check is skipped
  22044. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22045. Start(SERVER_CERT_FILE);
  22046. ws::WebSocketClient client(url());
  22047. client.set_ca_cert_path(SERVER_CERT_FILE);
  22048. client.enable_server_hostname_verification(false);
  22049. ASSERT_TRUE(client.connect());
  22050. ASSERT_TRUE(client.send("hello"));
  22051. std::string msg;
  22052. EXPECT_EQ(ws::Text, client.read(msg));
  22053. EXPECT_EQ("hello", msg);
  22054. client.close();
  22055. }
  22056. // A CA that did not sign the server certificate fails the chain, even though
  22057. // the name would match
  22058. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22059. Start(SERVER_CERT2_FILE);
  22060. ws::WebSocketClient client(url());
  22061. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22062. ASSERT_FALSE(client.connect());
  22063. }
  22064. // With verification disabled, neither the chain nor the name is checked
  22065. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22066. Start(SERVER_CERT_FILE);
  22067. ws::WebSocketClient client(url());
  22068. client.enable_server_certificate_verification(false);
  22069. ASSERT_TRUE(client.connect());
  22070. ASSERT_TRUE(client.send("hello"));
  22071. std::string msg;
  22072. EXPECT_EQ(ws::Text, client.read(msg));
  22073. EXPECT_EQ("hello", msg);
  22074. client.close();
  22075. }
  22076. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22077. protected:
  22078. void SetUp() override {
  22079. server_ = httplib::detail::make_unique<SSLServer>(
  22080. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22081. ASSERT_TRUE(server_->is_valid());
  22082. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22083. std::string msg;
  22084. while (ws.read(msg)) {
  22085. ws.send(msg);
  22086. }
  22087. });
  22088. port_ = server_->bind_to_any_port("localhost");
  22089. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22090. server_->wait_until_ready();
  22091. }
  22092. void TearDown() override {
  22093. server_->stop();
  22094. if (server_thread_.joinable()) { server_thread_.join(); }
  22095. }
  22096. std::string url() const {
  22097. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22098. }
  22099. void ConnectWithClientCert(const std::string &client_cert_file,
  22100. const std::string &client_private_key_file,
  22101. const char *private_key_password) {
  22102. std::string cert_pem, key_pem;
  22103. read_file(client_cert_file, cert_pem);
  22104. read_file(client_private_key_file, key_pem);
  22105. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22106. key_pem.c_str(), key_pem.size(),
  22107. private_key_password};
  22108. ws::WebSocketClient client(url(), pem);
  22109. ASSERT_TRUE(client.is_valid());
  22110. client.enable_server_certificate_verification(false);
  22111. ASSERT_TRUE(client.connect());
  22112. ASSERT_TRUE(client.send("hello"));
  22113. std::string msg;
  22114. EXPECT_EQ(ws::Text, client.read(msg));
  22115. EXPECT_EQ("hello", msg);
  22116. client.close();
  22117. }
  22118. std::unique_ptr<SSLServer> server_;
  22119. std::thread server_thread_;
  22120. int port_ = 0;
  22121. };
  22122. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22123. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22124. }
  22125. // Control for the tests above: the fixture's server really does require a
  22126. // client certificate, so it is the PEM the constructor installed that decides
  22127. // the outcome.
  22128. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22129. ws::WebSocketClient client(url());
  22130. ASSERT_TRUE(client.is_valid());
  22131. client.enable_server_certificate_verification(false);
  22132. EXPECT_FALSE(client.connect());
  22133. }
  22134. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22135. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22136. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22137. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22138. }
  22139. #endif
  22140. #if !defined(_WIN32)
  22141. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22142. auto secret_dir = std::string("./symlink_test_secret");
  22143. auto served_dir = std::string("./symlink_test_served");
  22144. auto secret_file = secret_dir + "/secret.txt";
  22145. auto symlink_path = served_dir + "/escape";
  22146. // Setup: create directories and files
  22147. mkdir(secret_dir.c_str(), 0755);
  22148. mkdir(served_dir.c_str(), 0755);
  22149. {
  22150. std::ofstream ofs(secret_file);
  22151. ofs << "SECRET_DATA";
  22152. }
  22153. // Create symlink using absolute path so it resolves correctly
  22154. #ifdef PATH_MAX
  22155. char abs_secret[PATH_MAX];
  22156. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22157. #else
  22158. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22159. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22160. ASSERT_NE(nullptr, abs_secret);
  22161. #endif
  22162. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22163. auto se = detail::scope_exit([&] {
  22164. unlink(symlink_path.c_str());
  22165. unlink(secret_file.c_str());
  22166. rmdir(served_dir.c_str());
  22167. rmdir(secret_dir.c_str());
  22168. });
  22169. Server svr;
  22170. svr.set_mount_point("/", served_dir);
  22171. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22172. auto se2 = detail::scope_exit([&] {
  22173. svr.stop();
  22174. listen_thread.join();
  22175. });
  22176. svr.wait_until_ready();
  22177. Client cli("localhost", PORT);
  22178. // Symlink pointing outside base dir should be blocked
  22179. auto res = cli.Get("/escape/secret.txt");
  22180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22181. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22182. }
  22183. #endif
  22184. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22185. // "GET /smuggled" request), reads the first response, and only then sends the
  22186. // embedded request as the body. Returns how many times /smuggled ran.
  22187. //
  22188. // The body is sent AFTER receiving the first response (as in the original
  22189. // PoC) so that the stream_line_reader cannot buffer it together with the
  22190. // headers of the first request.
  22191. static int count_smuggled_requests(const std::string &outer_head,
  22192. std::string &first_response) {
  22193. Server svr;
  22194. svr.set_mount_point("/", "./www");
  22195. std::atomic<int> smuggled_count(0);
  22196. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22197. smuggled_count++;
  22198. res.set_content("oops", "text/plain");
  22199. });
  22200. svr.Post("/post", [&](const Request &req, Response &res) {
  22201. res.set_content(req.body, "text/plain");
  22202. });
  22203. auto port = svr.bind_to_any_port("localhost");
  22204. thread t = thread([&] { svr.listen_after_bind(); });
  22205. auto se = detail::scope_exit([&] {
  22206. svr.stop();
  22207. t.join();
  22208. });
  22209. svr.wait_until_ready();
  22210. auto error = Error::Success;
  22211. auto sock = detail::create_client_socket(
  22212. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22213. /*connection_timeout_sec=*/2, 0,
  22214. /*read_timeout_sec=*/2, 0,
  22215. /*write_timeout_sec=*/2, 0, std::string(), error);
  22216. EXPECT_NE(INVALID_SOCKET, sock);
  22217. if (sock == INVALID_SOCKET) { return -1; }
  22218. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22219. // The "smuggled" request will be sent as the body of the outer request
  22220. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22221. "Host: localhost\r\n"
  22222. "Connection: close\r\n"
  22223. "\r\n";
  22224. auto head = outer_head;
  22225. auto len = std::to_string(smuggled.size());
  22226. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22227. pos = head.find("{len}", pos + len.size())) {
  22228. head.replace(pos, 5, len);
  22229. }
  22230. // Step 1: Send only the outer request headers (no body yet)
  22231. auto sent = send(sock, head.data(), head.size(), 0);
  22232. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22233. // Step 2: Read the first response
  22234. char buf[4096];
  22235. for (;;) {
  22236. auto n = recv(sock, buf, sizeof(buf), 0);
  22237. if (n <= 0) break;
  22238. first_response.append(buf, static_cast<size_t>(n));
  22239. // Stop once we have a complete response (headers + body)
  22240. auto hdr_end = first_response.find("\r\n\r\n");
  22241. if (hdr_end != std::string::npos) {
  22242. // Check for Content-Length to know when the body is complete
  22243. auto cl_pos = first_response.find("Content-Length:");
  22244. if (cl_pos != std::string::npos) {
  22245. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22246. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22247. auto cl = std::stoul(
  22248. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22249. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22250. } else {
  22251. break; // No Content-Length, assume headers-only response
  22252. }
  22253. }
  22254. }
  22255. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22256. // vulnerable server the keep-alive loop reads this as a second request. The
  22257. // server may already have closed the connection, so the result is ignored.
  22258. send(sock, smuggled.data(), smuggled.size(), 0);
  22259. // Half-close so that a server which drained the body sees EOF and closes,
  22260. // instead of the read below waiting for the read timeout.
  22261. #ifdef _WIN32
  22262. ::shutdown(sock, SD_SEND);
  22263. #else
  22264. ::shutdown(sock, SHUT_WR);
  22265. #endif
  22266. // Step 4: Read until the server closes the connection
  22267. for (;;) {
  22268. auto n = recv(sock, buf, sizeof(buf), 0);
  22269. if (n <= 0) break;
  22270. }
  22271. return smuggled_count.load();
  22272. }
  22273. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22274. // A GET request with Content-Length to a static file handler must have its
  22275. // body drained before the keep-alive connection is reused. Otherwise the
  22276. // unread body bytes are interpreted as the next HTTP request.
  22277. std::string first_response;
  22278. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22279. "Host: localhost\r\n"
  22280. "Content-Length: {len}\r\n"
  22281. "\r\n",
  22282. first_response));
  22283. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22284. }
  22285. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22286. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22287. // be answered with 400 and the connection closed. Treating it as "no body"
  22288. // leaves the body to be parsed as the next request.
  22289. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22290. const char *targets[] = {
  22291. "GET /file", // handler that never reads the body
  22292. "GET /not-found", // no handler matches (404)
  22293. "POST /post", // handler that reads the body
  22294. };
  22295. for (auto target : targets) {
  22296. for (auto value : values) {
  22297. std::string first_response;
  22298. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22299. " HTTP/1.1\r\n"
  22300. "Host: localhost\r\n"
  22301. "Content-Length: " +
  22302. value + "\r\n\r\n",
  22303. first_response))
  22304. << target << " with Content-Length: " << value;
  22305. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22306. << target << " with Content-Length: " << value;
  22307. }
  22308. }
  22309. }
  22310. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22311. // A 400 for an unparseable request line leaves the rest of the message
  22312. // unread, so the connection must be closed rather than reused.
  22313. std::string first_response;
  22314. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22315. "Host: localhost\r\n"
  22316. "Content-Length: {len}\r\n"
  22317. "\r\n",
  22318. first_response));
  22319. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22320. }
  22321. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22322. // Same as above for a header block that fails to parse.
  22323. std::string first_response;
  22324. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22325. "Host: localhost\r\n"
  22326. "Bad Header\r\n"
  22327. "Content-Length: {len}\r\n"
  22328. "\r\n",
  22329. first_response));
  22330. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22331. }
  22332. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22333. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22334. // server must not read another request on that connection, even when the
  22335. // request had no body to drain.
  22336. std::string first_response;
  22337. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22338. "Host: localhost\r\n"
  22339. "\r\n",
  22340. first_response));
  22341. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22342. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22343. }
  22344. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22345. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22346. // must be rejected with 400 Bad Request.
  22347. Server svr;
  22348. svr.Post("/test", [&](const Request &, Response &res) {
  22349. res.set_content("ok", "text/plain");
  22350. });
  22351. thread t = thread([&] { svr.listen(HOST, PORT); });
  22352. auto se = detail::scope_exit([&] {
  22353. svr.stop();
  22354. t.join();
  22355. ASSERT_FALSE(svr.is_running());
  22356. });
  22357. svr.wait_until_ready();
  22358. // Exact "chunked"
  22359. {
  22360. auto req = "POST /test HTTP/1.1\r\n"
  22361. "Host: localhost\r\n"
  22362. "Content-Length: 5\r\n"
  22363. "Transfer-Encoding: chunked\r\n"
  22364. "Connection: close\r\n"
  22365. "\r\n"
  22366. "hello";
  22367. std::string response;
  22368. ASSERT_TRUE(send_request(1, req, &response));
  22369. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22370. response.substr(0, response.find("\r\n")));
  22371. }
  22372. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22373. {
  22374. auto req = "POST /test HTTP/1.1\r\n"
  22375. "Host: localhost\r\n"
  22376. "Content-Length: 5\r\n"
  22377. "Transfer-Encoding: gzip, chunked\r\n"
  22378. "Connection: close\r\n"
  22379. "\r\n"
  22380. "hello";
  22381. std::string response;
  22382. ASSERT_TRUE(send_request(1, req, &response));
  22383. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22384. response.substr(0, response.find("\r\n")));
  22385. }
  22386. }
  22387. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22388. Server svr;
  22389. svr.Post("/test", [&](const Request &, Response &res) {
  22390. res.set_content("ok", "text/plain");
  22391. });
  22392. thread t = thread([&] { svr.listen(HOST, PORT); });
  22393. auto se = detail::scope_exit([&] {
  22394. svr.stop();
  22395. t.join();
  22396. ASSERT_FALSE(svr.is_running());
  22397. });
  22398. svr.wait_until_ready();
  22399. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22400. // length cannot be determined, so the server must answer 400 and close
  22401. // rather than treat the request as bodyless and leave the body in the
  22402. // socket for the next request to pick up.
  22403. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22404. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22405. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22406. std::string response;
  22407. ASSERT_TRUE(send_request(1, req, &response));
  22408. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22409. response.substr(0, response.find("\r\n")))
  22410. << transfer_encoding;
  22411. }
  22412. // RFC 9110 5.3: the codings may also be split across several
  22413. // Transfer-Encoding lines, which combine in the order they were received.
  22414. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22415. // just like the single-line "chunked, gzip" above.
  22416. {
  22417. auto req = "POST /test HTTP/1.1\r\n"
  22418. "Host: localhost\r\n"
  22419. "Transfer-Encoding: chunked\r\n"
  22420. "Transfer-Encoding: gzip\r\n"
  22421. "\r\n"
  22422. "0\r\n\r\n";
  22423. std::string response;
  22424. ASSERT_TRUE(send_request(1, req, &response));
  22425. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22426. response.substr(0, response.find("\r\n")));
  22427. }
  22428. // A sequence ending in chunked stays valid.
  22429. auto req = "POST /test HTTP/1.1\r\n"
  22430. "Host: localhost\r\n"
  22431. "Transfer-Encoding: gzip, chunked\r\n"
  22432. "Connection: close\r\n"
  22433. "\r\n"
  22434. "0\r\n\r\n";
  22435. std::string response;
  22436. ASSERT_TRUE(send_request(1, req, &response));
  22437. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22438. // ...including when it is spread over several lines.
  22439. auto split_req = "POST /test HTTP/1.1\r\n"
  22440. "Host: localhost\r\n"
  22441. "Transfer-Encoding: gzip\r\n"
  22442. "Transfer-Encoding: chunked\r\n"
  22443. "Connection: close\r\n"
  22444. "\r\n"
  22445. "0\r\n\r\n";
  22446. std::string split_response;
  22447. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22448. EXPECT_EQ("HTTP/1.1 200 OK",
  22449. split_response.substr(0, split_response.find("\r\n")));
  22450. }
  22451. // Regression for issue #2450: a DELETE without Content-Length on a
  22452. // keep-alive connection must not let the post-response drain consume the
  22453. // next request's bytes.
  22454. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22455. Server svr;
  22456. std::atomic<int> delete_count(0);
  22457. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22458. delete_count++;
  22459. res.status = StatusCode::NoContent_204;
  22460. });
  22461. auto port = svr.bind_to_any_port(HOST);
  22462. thread t = thread([&] { svr.listen_after_bind(); });
  22463. auto se = detail::scope_exit([&] {
  22464. svr.stop();
  22465. t.join();
  22466. });
  22467. svr.wait_until_ready();
  22468. auto error = Error::Success;
  22469. auto sock = detail::create_client_socket(
  22470. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22471. /*connection_timeout_sec=*/2, 0,
  22472. /*read_timeout_sec=*/2, 0,
  22473. /*write_timeout_sec=*/2, 0, std::string(), error);
  22474. ASSERT_NE(INVALID_SOCKET, sock);
  22475. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22476. auto send_request_and_read_response = [&](const std::string &req,
  22477. std::string &out) -> bool {
  22478. auto sent = send(sock, req.data(), req.size(), 0);
  22479. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22480. char buf[4096];
  22481. for (;;) {
  22482. auto n = recv(sock, buf, sizeof(buf), 0);
  22483. if (n <= 0) { return !out.empty(); }
  22484. out.append(buf, static_cast<size_t>(n));
  22485. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22486. }
  22487. };
  22488. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22489. "Host: localhost\r\n"
  22490. "\r\n";
  22491. std::string resp1;
  22492. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22493. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22494. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22495. "Host: localhost\r\n"
  22496. "Connection: close\r\n"
  22497. "\r\n";
  22498. std::string resp2;
  22499. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22500. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22501. EXPECT_EQ(2, delete_count.load());
  22502. }
  22503. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22504. Server svr;
  22505. svr.Post("/ingest", [&](const Request &, Response &res,
  22506. const ContentReader &content_reader) {
  22507. auto consumed = content_reader([](const char *, size_t) { return false; });
  22508. EXPECT_FALSE(consumed);
  22509. res.status = StatusCode::Conflict_409;
  22510. res.set_header("Connection", "close");
  22511. });
  22512. auto port = svr.bind_to_any_port(HOST);
  22513. thread t = thread([&] { svr.listen_after_bind(); });
  22514. auto se = detail::scope_exit([&] {
  22515. svr.stop();
  22516. t.join();
  22517. });
  22518. svr.wait_until_ready();
  22519. auto error = Error::Success;
  22520. auto sock = detail::create_client_socket(
  22521. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22522. /*connection_timeout_sec=*/2, 0,
  22523. /*read_timeout_sec=*/1, 0,
  22524. /*write_timeout_sec=*/2, 0, std::string(), error);
  22525. ASSERT_NE(INVALID_SOCKET, sock);
  22526. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22527. std::string request = "POST /ingest HTTP/1.1\r\n"
  22528. "Host: localhost\r\n"
  22529. "Transfer-Encoding: chunked\r\n"
  22530. "\r\n"
  22531. "4\r\n"
  22532. "data\r\n";
  22533. auto sent = send(sock, request.data(), request.size(), 0);
  22534. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22535. std::string response;
  22536. ssize_t received = 0;
  22537. do {
  22538. char buf[4096];
  22539. received = recv(sock, buf, sizeof(buf), 0);
  22540. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22541. } while (received > 0);
  22542. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22543. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22544. EXPECT_EQ(0, received);
  22545. }
  22546. namespace no_proxy_test {
  22547. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22548. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22549. // calling listen().
  22550. class ScopedServer {
  22551. public:
  22552. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22553. ~ScopedServer() {
  22554. svr_.stop();
  22555. if (th_.joinable()) { th_.join(); }
  22556. }
  22557. Server &svr() { return svr_; }
  22558. int port() const { return port_; }
  22559. void listen() {
  22560. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22561. svr_.wait_until_ready();
  22562. }
  22563. private:
  22564. Server svr_;
  22565. std::thread th_;
  22566. int port_ = 0;
  22567. };
  22568. class ProxyAndTargetServers {
  22569. public:
  22570. ProxyAndTargetServers() {
  22571. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22572. proxy_hits_++;
  22573. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22574. res.set_content("via-proxy", "text/plain");
  22575. });
  22576. target_.Get(".*", [this](const Request &req, Response &res) {
  22577. target_hits_++;
  22578. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22579. res.set_content("direct", "text/plain");
  22580. });
  22581. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22582. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22583. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22584. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22585. proxy_mock_.wait_until_ready();
  22586. target_.wait_until_ready();
  22587. }
  22588. ~ProxyAndTargetServers() {
  22589. proxy_mock_.stop();
  22590. target_.stop();
  22591. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22592. if (target_thread_.joinable()) { target_thread_.join(); }
  22593. }
  22594. Server &proxy_mock() { return proxy_mock_; }
  22595. Server &target() { return target_; }
  22596. int proxy_port() const { return proxy_port_; }
  22597. int target_port() const { return target_port_; }
  22598. int proxy_hits() const { return proxy_hits_.load(); }
  22599. int target_hits() const { return target_hits_.load(); }
  22600. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22601. void reset_counters() {
  22602. proxy_hits_ = 0;
  22603. target_hits_ = 0;
  22604. last_had_proxy_authz_ = false;
  22605. }
  22606. private:
  22607. Server proxy_mock_;
  22608. Server target_;
  22609. std::thread proxy_thread_;
  22610. std::thread target_thread_;
  22611. int proxy_port_ = 0;
  22612. int target_port_ = 0;
  22613. std::atomic<int> proxy_hits_{0};
  22614. std::atomic<int> target_hits_{0};
  22615. std::atomic<bool> last_had_proxy_authz_{false};
  22616. };
  22617. inline std::unique_ptr<Client> make_client(const std::string &host,
  22618. ProxyAndTargetServers &s) {
  22619. auto cli = detail::make_unique<Client>(host, s.target_port());
  22620. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22621. cli->set_proxy("127.0.0.1", s.proxy_port());
  22622. return cli;
  22623. }
  22624. } // namespace no_proxy_test
  22625. using no_proxy_test::make_client;
  22626. using no_proxy_test::ProxyAndTargetServers;
  22627. TEST(NoProxyTest, ExactHostnameBypasses) {
  22628. ProxyAndTargetServers s;
  22629. auto cli = make_client("example.com", s);
  22630. cli->set_no_proxy({"example.com"});
  22631. auto res = cli->Get("/");
  22632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22633. EXPECT_EQ(0, s.proxy_hits());
  22634. EXPECT_EQ(1, s.target_hits());
  22635. }
  22636. TEST(NoProxyTest, SubdomainBypasses) {
  22637. ProxyAndTargetServers s;
  22638. auto cli = make_client("foo.example.com", s);
  22639. cli->set_no_proxy({"example.com"});
  22640. auto res = cli->Get("/");
  22641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22642. EXPECT_EQ(0, s.proxy_hits());
  22643. EXPECT_EQ(1, s.target_hits());
  22644. }
  22645. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22646. // Regression guard: "evilexample.com" must not be considered a subdomain
  22647. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22648. // check would let traffic bypass the proxy and leak credentials direct
  22649. // to the attacker host.
  22650. ProxyAndTargetServers s;
  22651. auto cli = make_client("evilexample.com", s);
  22652. cli->set_no_proxy({"example.com"});
  22653. auto res = cli->Get("/");
  22654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22655. EXPECT_GE(s.proxy_hits(), 1);
  22656. EXPECT_EQ(0, s.target_hits());
  22657. }
  22658. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22659. ProxyAndTargetServers s;
  22660. auto cli = make_client("example.com.evil.com", s);
  22661. cli->set_no_proxy({"example.com"});
  22662. auto res = cli->Get("/");
  22663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22664. EXPECT_GE(s.proxy_hits(), 1);
  22665. EXPECT_EQ(0, s.target_hits());
  22666. }
  22667. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22668. ProxyAndTargetServers s;
  22669. auto cli = make_client("example.com", s);
  22670. cli->set_no_proxy({".example.com"});
  22671. auto res = cli->Get("/");
  22672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22673. EXPECT_EQ(0, s.proxy_hits());
  22674. EXPECT_EQ(1, s.target_hits());
  22675. }
  22676. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22677. ProxyAndTargetServers s;
  22678. auto cli = make_client("Example.COM", s);
  22679. cli->set_no_proxy({"EXAMPLE.com"});
  22680. auto res = cli->Get("/");
  22681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22682. EXPECT_EQ(0, s.proxy_hits());
  22683. EXPECT_EQ(1, s.target_hits());
  22684. }
  22685. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22686. ProxyAndTargetServers s;
  22687. auto cli = make_client("example.com.", s);
  22688. cli->set_no_proxy({"example.com"});
  22689. auto res = cli->Get("/");
  22690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22691. EXPECT_EQ(0, s.proxy_hits());
  22692. EXPECT_EQ(1, s.target_hits());
  22693. }
  22694. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22695. // Trailing dots must be normalized on BOTH sides — host and entry.
  22696. // An implementation that only strips the host-side trailing dot would
  22697. // fail to match host "example.com" against entry "example.com." because
  22698. // a literal substring search would compare 11 chars against 12.
  22699. ProxyAndTargetServers s;
  22700. auto cli = make_client("example.com", s);
  22701. cli->set_no_proxy({"example.com."});
  22702. auto res = cli->Get("/");
  22703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22704. EXPECT_EQ(0, s.proxy_hits());
  22705. EXPECT_EQ(1, s.target_hits());
  22706. }
  22707. TEST(NoProxyTest, WildcardBypassesEverything) {
  22708. ProxyAndTargetServers s;
  22709. auto cli = make_client("anything.invalid.test", s);
  22710. cli->set_no_proxy({"*"});
  22711. auto res = cli->Get("/");
  22712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22713. EXPECT_EQ(0, s.proxy_hits());
  22714. EXPECT_EQ(1, s.target_hits());
  22715. }
  22716. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22717. ProxyAndTargetServers s;
  22718. Client cli("127.0.0.1", s.target_port());
  22719. cli.set_proxy("127.0.0.1", s.proxy_port());
  22720. cli.set_no_proxy({"127.0.0.1"});
  22721. auto res = cli.Get("/");
  22722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22723. EXPECT_EQ(0, s.proxy_hits());
  22724. EXPECT_EQ(1, s.target_hits());
  22725. }
  22726. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22727. ProxyAndTargetServers s;
  22728. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22729. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22730. cli.set_proxy("127.0.0.1", s.proxy_port());
  22731. cli.set_no_proxy({"::1"});
  22732. auto res = cli.Get("/");
  22733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22734. EXPECT_EQ(0, s.proxy_hits());
  22735. EXPECT_EQ(1, s.target_hits());
  22736. }
  22737. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22738. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22739. // must still be recognized as IPv6 for CIDR matching. Implementations
  22740. // that detect IPv6 only when the host begins with '[' would parse the
  22741. // host as a hostname and miss the match.
  22742. ProxyAndTargetServers s;
  22743. Client cli("fe80::1", s.target_port());
  22744. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22745. cli.set_proxy("127.0.0.1", s.proxy_port());
  22746. cli.set_no_proxy({"fe80::/10"});
  22747. auto res = cli.Get("/");
  22748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22749. EXPECT_EQ(0, s.proxy_hits());
  22750. EXPECT_EQ(1, s.target_hits());
  22751. }
  22752. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22753. ProxyAndTargetServers s;
  22754. Client cli("::1", s.target_port());
  22755. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22756. cli.set_proxy("127.0.0.1", s.proxy_port());
  22757. cli.set_no_proxy({"[::1]"});
  22758. auto res = cli.Get("/");
  22759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22760. EXPECT_EQ(0, s.proxy_hits());
  22761. EXPECT_EQ(1, s.target_hits());
  22762. }
  22763. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22764. ProxyAndTargetServers s;
  22765. Client cli("fe80::1", s.target_port());
  22766. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22767. cli.set_proxy("127.0.0.1", s.proxy_port());
  22768. cli.set_no_proxy({"[fe80::]/10"});
  22769. auto res = cli.Get("/");
  22770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22771. EXPECT_EQ(0, s.proxy_hits());
  22772. EXPECT_EQ(1, s.target_hits());
  22773. }
  22774. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22775. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22776. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22777. // tricks via address-family conversion.
  22778. ProxyAndTargetServers s;
  22779. Client cli("::ffff:127.0.0.1", s.target_port());
  22780. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22781. cli.set_proxy("127.0.0.1", s.proxy_port());
  22782. cli.set_no_proxy({"127.0.0.1"});
  22783. auto res = cli.Get("/");
  22784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22785. EXPECT_GE(s.proxy_hits(), 1);
  22786. EXPECT_EQ(0, s.target_hits());
  22787. }
  22788. TEST(NoProxyTest, IPv4CidrMatch) {
  22789. ProxyAndTargetServers s;
  22790. Client cli("127.0.0.1", s.target_port());
  22791. cli.set_proxy("127.0.0.1", s.proxy_port());
  22792. cli.set_no_proxy({"127.0.0.0/8"});
  22793. auto res = cli.Get("/");
  22794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22795. EXPECT_EQ(0, s.proxy_hits());
  22796. EXPECT_EQ(1, s.target_hits());
  22797. }
  22798. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22799. ProxyAndTargetServers s;
  22800. Client cli("127.0.0.1", s.target_port());
  22801. cli.set_proxy("127.0.0.1", s.proxy_port());
  22802. cli.set_no_proxy({"10.0.0.0/8"});
  22803. auto res = cli.Get("/");
  22804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22805. EXPECT_GE(s.proxy_hits(), 1);
  22806. EXPECT_EQ(0, s.target_hits());
  22807. }
  22808. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22809. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22810. // IPv4 target matches.
  22811. ProxyAndTargetServers s;
  22812. Client cli("127.0.0.1", s.target_port());
  22813. cli.set_proxy("127.0.0.1", s.proxy_port());
  22814. cli.set_no_proxy({"0.0.0.0/0"});
  22815. auto res = cli.Get("/");
  22816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22817. EXPECT_EQ(0, s.proxy_hits());
  22818. EXPECT_EQ(1, s.target_hits());
  22819. }
  22820. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22821. ProxyAndTargetServers s;
  22822. Client cli("127.0.0.1", s.target_port());
  22823. cli.set_proxy("127.0.0.1", s.proxy_port());
  22824. cli.set_no_proxy({"127.0.0.1"});
  22825. auto res = cli.Get("/");
  22826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22827. EXPECT_EQ(0, s.proxy_hits());
  22828. EXPECT_EQ(1, s.target_hits());
  22829. }
  22830. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22831. ProxyAndTargetServers s;
  22832. Client cli("127.0.0.1", s.target_port());
  22833. cli.set_proxy("127.0.0.1", s.proxy_port());
  22834. cli.set_no_proxy({"127.0.0.0/33"});
  22835. auto res = cli.Get("/");
  22836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22837. EXPECT_GE(s.proxy_hits(), 1);
  22838. EXPECT_EQ(0, s.target_hits());
  22839. }
  22840. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22841. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22842. ProxyAndTargetServers s;
  22843. Client cli("127.0.0.1", s.target_port());
  22844. cli.set_proxy("127.0.0.1", s.proxy_port());
  22845. cli.set_no_proxy({"127.0.0.1/"});
  22846. auto res = cli.Get("/");
  22847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22848. EXPECT_GE(s.proxy_hits(), 1);
  22849. EXPECT_EQ(0, s.target_hits());
  22850. }
  22851. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22852. ProxyAndTargetServers s;
  22853. auto cli = make_client("internal.corp", s);
  22854. cli->set_proxy_basic_auth("u", "p");
  22855. cli->set_no_proxy({"internal.corp"});
  22856. auto res = cli->Get("/");
  22857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22858. EXPECT_EQ(1, s.target_hits());
  22859. EXPECT_EQ(0, s.proxy_hits());
  22860. EXPECT_FALSE(s.last_had_proxy_authz())
  22861. << "Proxy-Authorization must not be sent direct to the target";
  22862. }
  22863. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22864. ProxyAndTargetServers s;
  22865. auto cli = make_client("public.example", s);
  22866. cli->set_proxy_basic_auth("u", "p");
  22867. cli->set_no_proxy({"internal.corp"}); // does not match
  22868. auto res = cli->Get("/");
  22869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22870. EXPECT_GE(s.proxy_hits(), 1);
  22871. EXPECT_TRUE(s.last_had_proxy_authz());
  22872. }
  22873. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22874. std::atomic<int> hits{0};
  22875. std::atomic<int> hits_with_authz{0};
  22876. no_proxy_test::ScopedServer proxy_mock;
  22877. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22878. hits++;
  22879. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  22880. if (req.target.find("/redir") != std::string::npos) {
  22881. res.set_redirect("http://other.example/landed");
  22882. } else {
  22883. res.set_content("via-proxy", "text/plain");
  22884. }
  22885. });
  22886. proxy_mock.listen();
  22887. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  22888. hits = 0;
  22889. hits_with_authz = 0;
  22890. Client cli("public.example", 80);
  22891. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22892. cli.set_proxy_basic_auth(c.first, c.second);
  22893. cli.set_follow_location(true);
  22894. // The redirect to another host goes through the proxy as well
  22895. auto res = cli.Get("/redir");
  22896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22897. EXPECT_EQ(2, hits.load());
  22898. EXPECT_EQ(2, hits_with_authz.load());
  22899. }
  22900. }
  22901. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22902. ProxyAndTargetServers s;
  22903. auto cli = make_client("anything.test", s);
  22904. auto res = cli->Get("/");
  22905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22906. EXPECT_GE(s.proxy_hits(), 1);
  22907. EXPECT_EQ(0, s.target_hits());
  22908. }
  22909. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22910. ProxyAndTargetServers s;
  22911. auto cli = make_client("example.com", s);
  22912. cli->set_no_proxy({"example.com:8080"});
  22913. auto res = cli->Get("/");
  22914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22915. EXPECT_GE(s.proxy_hits(), 1);
  22916. EXPECT_EQ(0, s.target_hits());
  22917. }
  22918. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22919. ProxyAndTargetServers s;
  22920. auto cli = make_client("anything.test", s);
  22921. cli->set_no_proxy({"", " ", "\t"});
  22922. auto res = cli->Get("/");
  22923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22924. EXPECT_GE(s.proxy_hits(), 1);
  22925. EXPECT_EQ(0, s.target_hits());
  22926. }
  22927. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22928. // An entry with leading/trailing whitespace must still match — env-style
  22929. // values are commonly pasted with stray spaces and an implementation
  22930. // that feeds the raw token directly to inet_pton would fail to match
  22931. // valid CIDRs because of the spaces.
  22932. ProxyAndTargetServers s;
  22933. Client cli("127.0.0.1", s.target_port());
  22934. cli.set_proxy("127.0.0.1", s.proxy_port());
  22935. cli.set_no_proxy({" 127.0.0.0/8 "});
  22936. auto res = cli.Get("/");
  22937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22938. EXPECT_EQ(0, s.proxy_hits());
  22939. EXPECT_EQ(1, s.target_hits());
  22940. }
  22941. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22942. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22943. // go direct and must NOT carry Proxy-Authorization.
  22944. std::atomic<int> proxy_hits{0};
  22945. std::atomic<int> target_hits{0};
  22946. std::atomic<bool> target_saw_authz{false};
  22947. no_proxy_test::ScopedServer proxy_mock, target;
  22948. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22949. proxy_hits++;
  22950. res.status = 302;
  22951. res.set_header("Location", "http://127.0.0.1:" +
  22952. std::to_string(target.port()) + "/landed");
  22953. });
  22954. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22955. target_hits++;
  22956. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22957. res.set_content("direct", "text/plain");
  22958. });
  22959. proxy_mock.listen();
  22960. target.listen();
  22961. Client cli("public.example", target.port());
  22962. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22963. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22964. cli.set_proxy_basic_auth("u", "p");
  22965. cli.set_no_proxy({"127.0.0.1"});
  22966. cli.set_follow_location(true);
  22967. auto res = cli.Get("/redir");
  22968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22969. EXPECT_GE(proxy_hits.load(), 1);
  22970. EXPECT_GE(target_hits.load(), 1);
  22971. EXPECT_FALSE(target_saw_authz.load());
  22972. }
  22973. #ifdef CPPHTTPLIB_SSL_ENABLED
  22974. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22975. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22976. // proxy creds would be sent to the (possibly hostile) origin.
  22977. std::atomic<int> target_hits{0};
  22978. std::atomic<bool> target_saw_proxy_authz{false};
  22979. no_proxy_test::ScopedServer target;
  22980. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22981. target_hits++;
  22982. if (req.has_header("Proxy-Authorization")) {
  22983. target_saw_proxy_authz = true;
  22984. }
  22985. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22986. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22987. "nonce=\"abc\", algorithm=MD5");
  22988. });
  22989. target.listen();
  22990. // The proxy address is set to the target's port: the bypass MUST kick in;
  22991. // if it doesn't, the test still routes "via proxy" to the same server and
  22992. // the Proxy-Authorization assertion below catches the leak.
  22993. Client cli("evil.example", target.port());
  22994. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22995. cli.set_proxy("127.0.0.1", target.port());
  22996. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22997. cli.set_no_proxy({"evil.example"});
  22998. auto res = cli.Get("/x");
  22999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23000. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23001. EXPECT_EQ(1, target_hits.load());
  23002. EXPECT_FALSE(target_saw_proxy_authz.load());
  23003. }
  23004. #endif
  23005. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23006. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23007. std::atomic<int> proxy_hits{0};
  23008. std::atomic<int> bypass_hits{0};
  23009. std::atomic<bool> proxy_saw_c_url{false};
  23010. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23011. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23012. proxy_hits++;
  23013. if (req.path.find("/start") != std::string::npos) {
  23014. res.status = 302;
  23015. res.set_header("Location", "http://127.0.0.1:" +
  23016. std::to_string(bypass_server.port()) +
  23017. "/middle");
  23018. return;
  23019. }
  23020. if (req.path.find("/end") != std::string::npos) {
  23021. proxy_saw_c_url = true;
  23022. res.set_content("c-via-proxy", "text/plain");
  23023. return;
  23024. }
  23025. res.set_content("unexpected", "text/plain");
  23026. });
  23027. // public.example's "advertised" port is arbitrary (the request never lands
  23028. // there — it goes through the proxy), but use a dynamic value to stay
  23029. // friendly with sharded parallel runs.
  23030. int public_port = bypass_server.port();
  23031. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23032. bypass_hits++;
  23033. res.status = 302;
  23034. res.set_header("Location", "http://public.example:" +
  23035. std::to_string(public_port) + "/end");
  23036. });
  23037. proxy_mock.listen();
  23038. bypass_server.listen();
  23039. Client cli("public.example", public_port);
  23040. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23041. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23042. cli.set_no_proxy({"127.0.0.1"});
  23043. cli.set_follow_location(true);
  23044. auto res = cli.Get("/start");
  23045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23046. EXPECT_EQ(StatusCode::OK_200, res->status);
  23047. EXPECT_EQ("c-via-proxy", res->body);
  23048. EXPECT_GE(proxy_hits.load(), 2);
  23049. EXPECT_GE(bypass_hits.load(), 1);
  23050. EXPECT_TRUE(proxy_saw_c_url.load());
  23051. }
  23052. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23053. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23054. // request reconnects to the correct endpoint.
  23055. std::atomic<int> proxy_hits{0};
  23056. std::atomic<int> target_hits{0};
  23057. no_proxy_test::ScopedServer proxy_mock, target;
  23058. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23059. proxy_hits++;
  23060. res.set_content("via-proxy", "text/plain");
  23061. });
  23062. target.svr().Get(".*", [&](const Request &, Response &res) {
  23063. target_hits++;
  23064. res.set_content("direct", "text/plain");
  23065. });
  23066. proxy_mock.listen();
  23067. target.listen();
  23068. Client cli("public.example", target.port());
  23069. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23070. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23071. cli.set_keep_alive(true);
  23072. auto res1 = cli.Get("/a");
  23073. ASSERT_TRUE(res1);
  23074. EXPECT_EQ("via-proxy", res1->body);
  23075. EXPECT_EQ(1, proxy_hits.load());
  23076. EXPECT_EQ(0, target_hits.load());
  23077. cli.set_no_proxy({"public.example"});
  23078. auto res2 = cli.Get("/b");
  23079. ASSERT_TRUE(res2);
  23080. EXPECT_EQ("direct", res2->body);
  23081. EXPECT_EQ(1, proxy_hits.load());
  23082. EXPECT_EQ(1, target_hits.load());
  23083. }
  23084. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23085. namespace proxy_tunnel_test {
  23086. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23087. class ScopedSSLServer {
  23088. public:
  23089. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23090. port_ = svr_.bind_to_any_port("127.0.0.1");
  23091. }
  23092. ~ScopedSSLServer() {
  23093. svr_.stop();
  23094. if (th_.joinable()) { th_.join(); }
  23095. }
  23096. SSLServer &svr() { return svr_; }
  23097. int port() const { return port_; }
  23098. void listen() {
  23099. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23100. svr_.wait_until_ready();
  23101. }
  23102. private:
  23103. SSLServer svr_;
  23104. std::thread th_;
  23105. int port_ = 0;
  23106. };
  23107. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23108. class ScopedConnectProxy {
  23109. public:
  23110. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23111. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23112. if (listen_fd_ < 0) { return; }
  23113. int yes = 1;
  23114. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23115. sockaddr_in a{};
  23116. a.sin_family = AF_INET;
  23117. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23118. a.sin_port = 0;
  23119. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23120. return;
  23121. }
  23122. socklen_t alen = sizeof(a);
  23123. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23124. 0) {
  23125. return;
  23126. }
  23127. port_ = ntohs(a.sin_port);
  23128. if (::listen(listen_fd_, 1) != 0) { return; }
  23129. th_ = std::thread([this] { run(); });
  23130. }
  23131. ~ScopedConnectProxy() {
  23132. stop_ = true;
  23133. if (listen_fd_ >= 0) {
  23134. ::shutdown(listen_fd_, SHUT_RDWR);
  23135. ::close(listen_fd_);
  23136. }
  23137. if (th_.joinable()) { th_.join(); }
  23138. }
  23139. int port() const { return port_; }
  23140. int connect_hits() const { return connect_hits_.load(); }
  23141. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23142. std::string connect_request() const {
  23143. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23144. return connect_request_;
  23145. }
  23146. private:
  23147. void run() {
  23148. while (!stop_.load()) {
  23149. fd_set rfds;
  23150. FD_ZERO(&rfds);
  23151. FD_SET(listen_fd_, &rfds);
  23152. timeval tv{0, 100 * 1000};
  23153. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23154. if (sel <= 0) { continue; }
  23155. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23156. if (client_fd < 0) { continue; }
  23157. std::string req;
  23158. char buf[2048];
  23159. while (req.find("\r\n\r\n") == std::string::npos) {
  23160. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23161. if (n <= 0) { break; }
  23162. req.append(buf, static_cast<size_t>(n));
  23163. }
  23164. if (req.compare(0, 7, "CONNECT") != 0) {
  23165. ::close(client_fd);
  23166. continue;
  23167. }
  23168. connect_hits_++;
  23169. {
  23170. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23171. connect_request_ = req;
  23172. }
  23173. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23174. ::send(client_fd, ok, std::strlen(ok), 0);
  23175. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23176. sockaddr_in o{};
  23177. o.sin_family = AF_INET;
  23178. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23179. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23180. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23181. 0) {
  23182. ::close(client_fd);
  23183. ::close(origin_fd);
  23184. continue;
  23185. }
  23186. auto forward = [](int from, int to) {
  23187. char b[8192];
  23188. for (;;) {
  23189. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23190. if (n <= 0) { break; }
  23191. ssize_t off = 0;
  23192. while (off < n) {
  23193. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23194. if (s <= 0) {
  23195. off = n;
  23196. break;
  23197. }
  23198. off += s;
  23199. }
  23200. }
  23201. ::shutdown(to, SHUT_WR);
  23202. };
  23203. std::thread t1([&] { forward(client_fd, origin_fd); });
  23204. std::thread t2([&] { forward(origin_fd, client_fd); });
  23205. t1.join();
  23206. t2.join();
  23207. ::close(client_fd);
  23208. ::close(origin_fd);
  23209. }
  23210. }
  23211. int forward_port_ = -1;
  23212. int listen_fd_ = -1;
  23213. int port_ = 0;
  23214. std::thread th_;
  23215. std::atomic<bool> stop_{false};
  23216. std::atomic<int> connect_hits_{0};
  23217. mutable std::mutex connect_request_mutex_;
  23218. std::string connect_request_;
  23219. };
  23220. // Sends one request through the CONNECT proxy to the TLS origin with a
  23221. // credential configured for each hop, and checks that each credential reaches
  23222. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23223. // origin's (every header in origin_headers) on the tunnelled request.
  23224. void CredentialsStayWithTheirHop(
  23225. const std::function<void(SSLClient &)> &set_credentials,
  23226. const std::string &scheme,
  23227. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23228. std::atomic<int> origin_hits{0};
  23229. std::atomic<bool> origin_saw_proxy_authz{false};
  23230. std::atomic<bool> origin_saw_headers{false};
  23231. ScopedSSLServer origin;
  23232. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23233. origin_hits++;
  23234. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23235. origin_saw_headers =
  23236. std::all_of(origin_headers.begin(), origin_headers.end(),
  23237. [&](const std::string &h) { return req.has_header(h); });
  23238. res.set_content("ok", "text/plain");
  23239. });
  23240. origin.listen();
  23241. ScopedConnectProxy proxy(origin.port());
  23242. ASSERT_NE(0, proxy.port());
  23243. // Pinned to 127.0.0.1 for the same reason as the test below.
  23244. SSLClient cli("127.0.0.1", origin.port());
  23245. cli.enable_server_certificate_verification(false);
  23246. cli.set_proxy("127.0.0.1", proxy.port());
  23247. set_credentials(cli);
  23248. auto res = cli.Get("/x");
  23249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23250. EXPECT_EQ(StatusCode::OK_200, res->status);
  23251. EXPECT_EQ(1, origin_hits.load());
  23252. EXPECT_EQ(1, proxy.connect_hits());
  23253. EXPECT_TRUE(origin_saw_headers.load());
  23254. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23255. << "Proxy-Authorization must not be sent inside the tunnel";
  23256. auto connect_req = proxy.connect_request();
  23257. EXPECT_NE(std::string::npos,
  23258. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23259. for (const auto &h : origin_headers) {
  23260. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23261. << h << " must not be sent to the proxy on CONNECT";
  23262. }
  23263. }
  23264. } // namespace proxy_tunnel_test
  23265. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23266. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23267. [](SSLClient &cli) {
  23268. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23269. cli.set_basic_auth("origin-user", "origin-pass");
  23270. },
  23271. "Basic");
  23272. }
  23273. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23274. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23275. [](SSLClient &cli) {
  23276. cli.set_proxy_bearer_token_auth("proxy-token");
  23277. cli.set_bearer_token_auth("origin-token");
  23278. },
  23279. "Bearer");
  23280. }
  23281. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23282. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23283. [](SSLClient &cli) {
  23284. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23285. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23286. {"Cookie", "sid=origin-session"},
  23287. {"X-Api-Key", "origin-key"}});
  23288. },
  23289. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23290. }
  23291. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23292. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23293. // retry; otherwise proxy creds would be sent to the origin.
  23294. std::atomic<int> origin_hits{0};
  23295. std::atomic<bool> origin_saw_proxy_authz{false};
  23296. proxy_tunnel_test::ScopedSSLServer origin;
  23297. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23298. origin_hits++;
  23299. if (req.has_header("Proxy-Authorization")) {
  23300. origin_saw_proxy_authz = true;
  23301. }
  23302. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23303. res.set_header("Proxy-Authenticate",
  23304. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23305. "algorithm=MD5");
  23306. });
  23307. origin.listen();
  23308. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23309. ASSERT_NE(0, proxy.port());
  23310. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23311. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23312. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23313. // and answer with its own status, making this test flaky.
  23314. SSLClient cli("127.0.0.1", origin.port());
  23315. cli.enable_server_certificate_verification(false);
  23316. cli.set_proxy("127.0.0.1", proxy.port());
  23317. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23318. auto res = cli.Get("/x");
  23319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23320. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23321. EXPECT_EQ(1, origin_hits.load());
  23322. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23323. EXPECT_EQ(1, proxy.connect_hits());
  23324. }
  23325. #endif