test.cc 900 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809
  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 notices on its first write or read
  12283. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  12284. res.error() == Error::Write || res.error() == Error::Read)
  12285. << to_string(res.error());
  12286. if (res.error() == Error::SSLConnection) {
  12287. EXPECT_NE(0UL, res.ssl_backend_error());
  12288. }
  12289. // A rejection noticed on the write keeps the TLS error the write hit
  12290. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  12291. }
  12292. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  12293. // A server that requires client certificates must keep requiring them after a
  12294. // verify callback is set on its context, or set and then cleared again.
  12295. void ClientCertStillRequired(bool clear_callback) {
  12296. auto setup = [clear_callback](SSLServer &svr) {
  12297. ASSERT_TRUE(tls::set_verify_callback(
  12298. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  12299. if (clear_callback) {
  12300. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  12301. }
  12302. };
  12303. ClientCertMissing(setup);
  12304. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  12305. setup);
  12306. }
  12307. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  12308. ClientCertStillRequired(false);
  12309. }
  12310. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  12311. ClientCertStillRequired(true);
  12312. }
  12313. // A TLS error from one request must not show up in a later request's Result
  12314. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  12315. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12316. ASSERT_TRUE(svr.is_valid());
  12317. svr.Get("/test", [](const Request &, Response &res) {
  12318. res.set_content("test", "text/plain");
  12319. });
  12320. auto port = svr.bind_to_any_port(HOST);
  12321. ASSERT_LT(0, port);
  12322. thread t = thread([&]() { svr.listen_after_bind(); });
  12323. auto se = detail::scope_exit([&] {
  12324. svr.stop();
  12325. t.join();
  12326. ASSERT_FALSE(svr.is_running());
  12327. });
  12328. svr.wait_until_ready();
  12329. SSLClient cli(HOST, port);
  12330. cli.set_connection_timeout(30);
  12331. cli.enable_server_hostname_verification(false);
  12332. // cert.pem is not trusted, so the handshake fails
  12333. ASSERT_FALSE(cli.Get("/test"));
  12334. cli.enable_server_certificate_verification(false);
  12335. auto res = cli.Get("/test");
  12336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12337. EXPECT_EQ(0, res.ssl_error());
  12338. EXPECT_EQ(0UL, res.ssl_backend_error());
  12339. }
  12340. // PEM memory-based constructor tests (works with all TLS backends)
  12341. void PemMemoryClientCertPresent(
  12342. const std::string &client_cert_file,
  12343. const std::string &client_private_key_file,
  12344. const std::string &client_encrypted_private_key_pass = std::string()) {
  12345. // Read PEM files into memory
  12346. std::string server_cert_pem, server_key_pem;
  12347. std::string client_ca_pem;
  12348. std::string client_cert_pem, client_key_pem;
  12349. read_file(SERVER_CERT_FILE, server_cert_pem);
  12350. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12351. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12352. read_file(client_cert_file, client_cert_pem);
  12353. read_file(client_private_key_file, client_key_pem);
  12354. // Create server with PEM memory
  12355. SSLServer::PemMemory server_pem = {
  12356. server_cert_pem.c_str(),
  12357. server_cert_pem.size(),
  12358. server_key_pem.c_str(),
  12359. server_key_pem.size(),
  12360. client_ca_pem.c_str(),
  12361. client_ca_pem.size(),
  12362. nullptr // no password for server key
  12363. };
  12364. SSLServer svr(server_pem);
  12365. ASSERT_TRUE(svr.is_valid());
  12366. svr.Get("/test", [&](const Request &, Response &res) {
  12367. res.set_content("test", "text/plain");
  12368. });
  12369. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12370. auto se = detail::scope_exit([&] {
  12371. svr.stop();
  12372. t.join();
  12373. ASSERT_FALSE(svr.is_running());
  12374. });
  12375. svr.wait_until_ready();
  12376. // Create client with PEM memory
  12377. const char *password = client_encrypted_private_key_pass.empty()
  12378. ? nullptr
  12379. : client_encrypted_private_key_pass.c_str();
  12380. SSLClient::PemMemory client_pem = {
  12381. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12382. client_key_pem.size(), password};
  12383. SSLClient cli(HOST, PORT, client_pem);
  12384. cli.enable_server_certificate_verification(false);
  12385. cli.set_connection_timeout(30);
  12386. auto res = cli.Get("/test");
  12387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12388. ASSERT_EQ(StatusCode::OK_200, res->status);
  12389. }
  12390. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12391. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12392. }
  12393. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12394. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12395. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12396. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12397. }
  12398. TEST(SSLClientServerTest, TrustDirOptional) {
  12399. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12400. ASSERT_TRUE(svr.is_valid());
  12401. svr.Get("/test", [&](const Request &, Response &res) {
  12402. res.set_content("test", "text/plain");
  12403. });
  12404. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12405. auto se = detail::scope_exit([&] {
  12406. svr.stop();
  12407. t.join();
  12408. ASSERT_FALSE(svr.is_running());
  12409. });
  12410. svr.wait_until_ready();
  12411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12412. cli.enable_server_certificate_verification(false);
  12413. cli.set_connection_timeout(30);
  12414. auto res = cli.Get("/test");
  12415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12416. ASSERT_EQ(StatusCode::OK_200, res->status);
  12417. }
  12418. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12419. class NoListenSSLServer : public SSLServer {
  12420. public:
  12421. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12422. const char *client_ca_cert_file_path,
  12423. const char *client_ca_cert_dir_path = nullptr)
  12424. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12425. client_ca_cert_dir_path),
  12426. stop_(false) {}
  12427. std::atomic_bool stop_;
  12428. private:
  12429. bool process_and_close_socket(socket_t /*sock*/) override {
  12430. // Don't create SSL context
  12431. while (!stop_.load()) {
  12432. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12433. }
  12434. return true;
  12435. }
  12436. };
  12437. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12438. CLIENT_CA_CERT_FILE);
  12439. ASSERT_TRUE(svr.is_valid());
  12440. svr.Get("/test", [&](const Request &, Response &res) {
  12441. res.set_content("test", "text/plain");
  12442. });
  12443. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12444. auto se = detail::scope_exit([&] {
  12445. svr.stop_ = true;
  12446. svr.stop();
  12447. t.join();
  12448. ASSERT_FALSE(svr.is_running());
  12449. });
  12450. svr.wait_until_ready();
  12451. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12452. cli.enable_server_certificate_verification(false);
  12453. cli.set_connection_timeout(1);
  12454. auto res = cli.Get("/test");
  12455. ASSERT_TRUE(!res);
  12456. EXPECT_EQ(Error::SSLConnection, res.error());
  12457. // Timeout results in WantRead error code (maps to backend-specific value)
  12458. EXPECT_NE(0, res.ssl_error());
  12459. }
  12460. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12461. // Test SSLServer with client certificate verification using the standard
  12462. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12464. CLIENT_CA_CERT_DIR);
  12465. ASSERT_TRUE(svr.is_valid());
  12466. svr.Get("/test", [&](const Request &req, Response &res) {
  12467. res.set_content("test", "text/plain");
  12468. auto cert = req.peer_cert();
  12469. ASSERT_TRUE(static_cast<bool>(cert));
  12470. auto common_name = cert.subject_cn();
  12471. EXPECT_EQ("Common Name", common_name);
  12472. });
  12473. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12474. auto se = detail::scope_exit([&] {
  12475. svr.stop();
  12476. t.join();
  12477. ASSERT_FALSE(svr.is_running());
  12478. });
  12479. svr.wait_until_ready();
  12480. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12481. cli.enable_server_certificate_verification(false);
  12482. cli.set_connection_timeout(30);
  12483. auto res = cli.Get("/test");
  12484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12485. ASSERT_EQ(StatusCode::OK_200, res->status);
  12486. }
  12487. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12488. // Verifies that wildcard matching and exact matching work consistently
  12489. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12490. using namespace httplib::tls;
  12491. // We need a running server to test against
  12492. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12493. ASSERT_TRUE(svr.is_valid());
  12494. svr.Get("/test", [](const Request &, Response &res) {
  12495. res.set_content("ok", "text/plain");
  12496. });
  12497. thread t([&]() { svr.listen(HOST, PORT); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. });
  12502. svr.wait_until_ready();
  12503. bool verify_callback_called = false;
  12504. bool verify_result_wrong = false;
  12505. SSLClient cli(HOST, PORT);
  12506. cli.enable_server_certificate_verification(true);
  12507. cli.set_ca_cert_path(CA_CERT_FILE);
  12508. cli.set_connection_timeout(5);
  12509. // Note: Test certificate has CN="Common Name", not "localhost"
  12510. bool verify_result_cn = false;
  12511. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12512. verify_callback_called = true;
  12513. if (!ctx.cert) return false;
  12514. // Test 1: "Common Name" should match (our test server cert CN)
  12515. verify_result_cn = ctx.check_hostname("Common Name");
  12516. // Test 2: wrong hostname should not match
  12517. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12518. return true; // Accept for the purpose of this test
  12519. });
  12520. auto res = cli.Get("/test");
  12521. // The request may succeed or fail depending on cert configuration
  12522. // but the callback should have been called
  12523. ASSERT_TRUE(verify_callback_called)
  12524. << "Verify callback should have been called";
  12525. // CN="Common Name" should match our test certificate
  12526. //
  12527. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12528. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12529. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12530. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12531. // <openssl/base.h>, which is included transitively when
  12532. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12533. #if defined(OPENSSL_IS_BORINGSSL)
  12534. EXPECT_FALSE(verify_result_cn)
  12535. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12536. #else
  12537. EXPECT_TRUE(verify_result_cn)
  12538. << "verify_hostname should match 'Common Name' (certificate CN)";
  12539. #endif
  12540. // Wrong hostname should not match
  12541. EXPECT_FALSE(verify_result_wrong)
  12542. << "verify_hostname should not match 'wronghost.example.com'";
  12543. }
  12544. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12545. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12546. // X509_check_ip behavior and must hold for every backend.
  12547. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12548. using namespace httplib::tls;
  12549. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12550. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12551. ASSERT_TRUE(svr.is_valid());
  12552. svr.Get("/test", [](const Request &, Response &res) {
  12553. res.set_content("ok", "text/plain");
  12554. });
  12555. thread t([&]() { svr.listen(HOST, PORT); });
  12556. auto se = detail::scope_exit([&] {
  12557. svr.stop();
  12558. t.join();
  12559. });
  12560. svr.wait_until_ready();
  12561. bool verify_callback_called = false;
  12562. bool ip_matched_via_cn = true;
  12563. SSLClient cli(HOST, PORT);
  12564. cli.enable_server_certificate_verification(true);
  12565. cli.set_ca_cert_path(CA_CERT_FILE);
  12566. cli.set_connection_timeout(5);
  12567. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12568. verify_callback_called = true;
  12569. if (!ctx.cert) return false;
  12570. // The IP appears only in the CN, so it must NOT be accepted.
  12571. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12572. return true; // Accept for the purpose of this test
  12573. });
  12574. cli.Get("/test");
  12575. ASSERT_TRUE(verify_callback_called)
  12576. << "Verify callback should have been called";
  12577. EXPECT_FALSE(ip_matched_via_cn)
  12578. << "An IP host must not be authenticated via the certificate CN";
  12579. }
  12580. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12581. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12582. using namespace httplib::tls;
  12583. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12584. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12585. ASSERT_TRUE(svr.is_valid());
  12586. svr.Get("/test", [](const Request &, Response &res) {
  12587. res.set_content("ok", "text/plain");
  12588. });
  12589. thread t([&]() { svr.listen(HOST, PORT); });
  12590. auto se = detail::scope_exit([&] {
  12591. svr.stop();
  12592. t.join();
  12593. });
  12594. svr.wait_until_ready();
  12595. bool verify_callback_called = false;
  12596. bool san_matched = false;
  12597. bool wrong_ipv6_matched = true;
  12598. bool cn_ipv6_matched = true;
  12599. SSLClient cli(HOST, PORT);
  12600. cli.enable_server_certificate_verification(true);
  12601. cli.set_ca_cert_path(CA_CERT_FILE);
  12602. cli.set_connection_timeout(5);
  12603. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12604. verify_callback_called = true;
  12605. if (!ctx.cert) return false;
  12606. // Matches the IPv6 iPAddress SAN.
  12607. san_matched = ctx.check_hostname("2001:db8::1");
  12608. // A different IPv6 address must not match.
  12609. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12610. // "::1" lives only in the CN, so it must not be accepted.
  12611. cn_ipv6_matched = ctx.check_hostname("::1");
  12612. return true; // Accept for the purpose of this test
  12613. });
  12614. cli.Get("/test");
  12615. ASSERT_TRUE(verify_callback_called)
  12616. << "Verify callback should have been called";
  12617. EXPECT_TRUE(san_matched)
  12618. << "verify_hostname should match an IPv6 iPAddress SAN";
  12619. EXPECT_FALSE(wrong_ipv6_matched)
  12620. << "verify_hostname should not match a non-matching IPv6 address";
  12621. EXPECT_FALSE(cn_ipv6_matched)
  12622. << "An IPv6 host must not be authenticated via the certificate CN";
  12623. }
  12624. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12625. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12626. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12627. using namespace httplib::tls;
  12628. // SANs: DNS:a.zz, IP:42.46.122.122
  12629. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12630. ASSERT_TRUE(svr.is_valid());
  12631. svr.Get("/test", [](const Request &, Response &res) {
  12632. res.set_content("ok", "text/plain");
  12633. });
  12634. auto port = svr.bind_to_any_port(HOST);
  12635. thread t([&]() { svr.listen_after_bind(); });
  12636. auto se = detail::scope_exit([&] {
  12637. svr.stop();
  12638. t.join();
  12639. });
  12640. svr.wait_until_ready();
  12641. bool verify_callback_called = false;
  12642. bool dns_san_matched = false;
  12643. bool ip_san_matched = false;
  12644. bool ip_matched_via_dns_san = true;
  12645. bool dns_matched_via_ip_san = true;
  12646. SSLClient cli(HOST, port);
  12647. cli.enable_server_certificate_verification(true);
  12648. cli.set_ca_cert_path(CA_CERT_FILE);
  12649. cli.set_connection_timeout(5);
  12650. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12651. verify_callback_called = true;
  12652. if (!ctx.cert) return false;
  12653. dns_san_matched = ctx.check_hostname("a.zz");
  12654. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12655. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12656. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12657. return true; // Accept for the purpose of this test
  12658. });
  12659. cli.Get("/test");
  12660. ASSERT_TRUE(verify_callback_called)
  12661. << "Verify callback should have been called";
  12662. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12663. EXPECT_TRUE(ip_san_matched)
  12664. << "verify_hostname should match an iPAddress SAN";
  12665. EXPECT_FALSE(ip_matched_via_dns_san)
  12666. << "An IP host must not be authenticated via a dNSName SAN";
  12667. EXPECT_FALSE(dns_matched_via_ip_san)
  12668. << "A DNS host must not be authenticated via an iPAddress SAN";
  12669. }
  12670. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12671. // "www.*.example.test" names one host and not every host under example.test.
  12672. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12673. using namespace httplib::tls;
  12674. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12675. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12676. ASSERT_TRUE(svr.is_valid());
  12677. svr.Get("/test", [](const Request &, Response &res) {
  12678. res.set_content("ok", "text/plain");
  12679. });
  12680. auto port = svr.bind_to_any_port(HOST);
  12681. thread t([&]() { svr.listen_after_bind(); });
  12682. auto se = detail::scope_exit([&] {
  12683. svr.stop();
  12684. t.join();
  12685. });
  12686. svr.wait_until_ready();
  12687. bool verify_callback_called = false;
  12688. bool leftmost_wildcard_matched = false;
  12689. bool wildcard_spanned_labels = true;
  12690. bool inner_wildcard_matched = true;
  12691. SSLClient cli(HOST, port);
  12692. cli.enable_server_certificate_verification(true);
  12693. cli.set_ca_cert_path(CA_CERT_FILE);
  12694. cli.set_connection_timeout(5);
  12695. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12696. verify_callback_called = true;
  12697. if (!ctx.cert) return false;
  12698. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12699. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12700. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12701. return true; // Accept for the purpose of this test
  12702. });
  12703. cli.Get("/test");
  12704. ASSERT_TRUE(verify_callback_called)
  12705. << "Verify callback should have been called";
  12706. EXPECT_TRUE(leftmost_wildcard_matched)
  12707. << "A leftmost wildcard should match a single label";
  12708. EXPECT_FALSE(wildcard_spanned_labels)
  12709. << "A wildcard label must not match more than one label";
  12710. EXPECT_FALSE(inner_wildcard_matched)
  12711. << "A wildcard outside the leftmost label must not be honoured";
  12712. }
  12713. // sans() must report each SAN entry under its own type.
  12714. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12715. using namespace httplib::tls;
  12716. // SANs: DNS:a.zz, IP:42.46.122.122
  12717. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12718. ASSERT_TRUE(svr.is_valid());
  12719. svr.Get("/test", [](const Request &, Response &res) {
  12720. res.set_content("ok", "text/plain");
  12721. });
  12722. auto port = svr.bind_to_any_port(HOST);
  12723. thread t([&]() { svr.listen_after_bind(); });
  12724. auto se = detail::scope_exit([&] {
  12725. svr.stop();
  12726. t.join();
  12727. });
  12728. svr.wait_until_ready();
  12729. bool verify_callback_called = false;
  12730. std::vector<SanEntry> sans;
  12731. SSLClient cli(HOST, port);
  12732. cli.enable_server_certificate_verification(true);
  12733. cli.set_ca_cert_path(CA_CERT_FILE);
  12734. cli.set_connection_timeout(5);
  12735. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12736. verify_callback_called = true;
  12737. if (!ctx.cert) return false;
  12738. sans = ctx.sans();
  12739. return true; // Accept for the purpose of this test
  12740. });
  12741. cli.Get("/test");
  12742. ASSERT_TRUE(verify_callback_called)
  12743. << "Verify callback should have been called";
  12744. auto has_san = [&](SanType type, const std::string &value) {
  12745. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12746. return san.type == type && san.value == value;
  12747. });
  12748. };
  12749. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12750. << "sans() should report the dNSName SAN";
  12751. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12752. << "sans() should report the iPAddress SAN";
  12753. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12754. << "sans() must not report the dNSName SAN as an address";
  12755. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12756. << "sans() must not report the iPAddress SAN as a DNS name";
  12757. }
  12758. #endif
  12759. // mbedTLS-specific callback constructor test
  12760. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12761. #ifdef CPPHTTPLIB_SSL_ENABLED
  12762. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12763. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12764. ASSERT_TRUE(svr.is_valid());
  12765. // Set up a handler to verify client certificate is present
  12766. bool client_cert_verified = false;
  12767. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12768. // Verify that client certificate was provided
  12769. client_cert_verified = true;
  12770. res.set_content("success", "text/plain");
  12771. });
  12772. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12773. auto se = detail::scope_exit([&] {
  12774. svr.stop();
  12775. t.join();
  12776. ASSERT_FALSE(svr.is_running());
  12777. });
  12778. svr.wait_until_ready();
  12779. // Client with certificate
  12780. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12781. cli.enable_server_certificate_verification(false);
  12782. cli.set_connection_timeout(30);
  12783. auto res = cli.Get("/test");
  12784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12785. ASSERT_EQ(StatusCode::OK_200, res->status);
  12786. ASSERT_TRUE(client_cert_verified);
  12787. EXPECT_EQ("success", res->body);
  12788. }
  12789. #endif
  12790. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12791. // backends
  12792. #ifdef CPPHTTPLIB_SSL_ENABLED
  12793. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12794. using namespace httplib::tls;
  12795. // Test that when client CA cert file is provided,
  12796. // the server properly requests and validates client certificates
  12797. // Create a server with client authentication
  12798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12799. ASSERT_TRUE(svr.is_valid());
  12800. bool handler_called = false;
  12801. svr.Get("/test", [&](const Request &req, Response &res) {
  12802. handler_called = true;
  12803. // Verify that a client certificate was provided
  12804. auto cert = req.peer_cert();
  12805. ASSERT_TRUE(static_cast<bool>(cert));
  12806. // Get the issuer name
  12807. std::string issuer_str = cert.issuer_name();
  12808. ASSERT_FALSE(issuer_str.empty());
  12809. // The client certificate should be issued by our test CA
  12810. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12811. res.set_content("authenticated", "text/plain");
  12812. });
  12813. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12814. auto se = detail::scope_exit([&] {
  12815. svr.stop();
  12816. t.join();
  12817. ASSERT_FALSE(svr.is_running());
  12818. });
  12819. svr.wait_until_ready();
  12820. // Connect with a client certificate issued by the CA
  12821. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12822. cli.enable_server_certificate_verification(false);
  12823. cli.set_connection_timeout(30);
  12824. auto res = cli.Get("/test");
  12825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12826. ASSERT_EQ(StatusCode::OK_200, res->status);
  12827. ASSERT_TRUE(handler_called);
  12828. EXPECT_EQ("authenticated", res->body);
  12829. }
  12830. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12831. using namespace httplib::tls;
  12832. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12833. ASSERT_TRUE(svr.is_valid());
  12834. svr.Get("/test", [](const Request &, Response &res) {
  12835. res.set_content("ok", "text/plain");
  12836. });
  12837. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12838. auto se = detail::scope_exit([&] {
  12839. svr.stop();
  12840. t.join();
  12841. });
  12842. svr.wait_until_ready();
  12843. SSLClient cli(HOST, PORT);
  12844. cli.enable_server_certificate_verification(false);
  12845. cli.set_connection_timeout(30);
  12846. bool cert_checked = false;
  12847. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12848. if (ctx.cert) {
  12849. auto sans = ctx.sans();
  12850. // Test certificate may or may not have SANs - just verify the API
  12851. // works If SANs exist, verify the types are valid
  12852. for (const auto &san : sans) {
  12853. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12854. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12855. san.type == SanType::OTHER);
  12856. EXPECT_FALSE(san.value.empty());
  12857. }
  12858. cert_checked = true;
  12859. }
  12860. return true;
  12861. });
  12862. auto res = cli.Get("/test");
  12863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12864. EXPECT_TRUE(cert_checked);
  12865. }
  12866. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12867. using namespace httplib::tls;
  12868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12869. ASSERT_TRUE(svr.is_valid());
  12870. svr.Get("/test", [](const Request &, Response &res) {
  12871. res.set_content("ok", "text/plain");
  12872. });
  12873. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12874. auto se = detail::scope_exit([&] {
  12875. svr.stop();
  12876. t.join();
  12877. });
  12878. svr.wait_until_ready();
  12879. SSLClient cli(HOST, PORT);
  12880. cli.enable_server_certificate_verification(false);
  12881. cli.set_connection_timeout(30);
  12882. bool validity_checked = false;
  12883. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12884. if (ctx.cert) {
  12885. time_t not_before = 0, not_after = 0;
  12886. bool result = ctx.validity(not_before, not_after);
  12887. EXPECT_TRUE(result);
  12888. // Verify that not_before < now < not_after for a valid cert
  12889. time_t now = time(nullptr);
  12890. EXPECT_LT(not_before, now);
  12891. EXPECT_GT(not_after, now);
  12892. validity_checked = true;
  12893. }
  12894. return true;
  12895. });
  12896. auto res = cli.Get("/test");
  12897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12898. EXPECT_TRUE(validity_checked);
  12899. }
  12900. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12901. using namespace httplib::tls;
  12902. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12903. ASSERT_TRUE(svr.is_valid());
  12904. svr.Get("/test", [](const Request &, Response &res) {
  12905. res.set_content("ok", "text/plain");
  12906. });
  12907. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12908. auto se = detail::scope_exit([&] {
  12909. svr.stop();
  12910. t.join();
  12911. });
  12912. svr.wait_until_ready();
  12913. SSLClient cli(HOST, PORT);
  12914. cli.enable_server_certificate_verification(false);
  12915. cli.set_connection_timeout(30);
  12916. bool serial_checked = false;
  12917. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12918. if (ctx.cert) {
  12919. std::string serial = ctx.serial();
  12920. EXPECT_FALSE(serial.empty());
  12921. // Serial should be a hex string
  12922. for (char c : serial) {
  12923. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12924. (c >= 'a' && c <= 'f'));
  12925. }
  12926. serial_checked = true;
  12927. }
  12928. return true;
  12929. });
  12930. auto res = cli.Get("/test");
  12931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12932. EXPECT_TRUE(serial_checked);
  12933. }
  12934. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12935. // Test 1: Valid CA file - no error should be recorded
  12936. {
  12937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12938. CLIENT_CA_CERT_FILE);
  12939. ASSERT_TRUE(svr.is_valid());
  12940. // With valid setup, last_ssl_error should be 0
  12941. EXPECT_EQ(0, svr.ssl_last_error());
  12942. }
  12943. // Test 2: Invalid CA file content
  12944. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12945. {
  12946. // Create a temporary file with completely invalid content
  12947. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12948. {
  12949. std::ofstream ofs(temp_invalid_ca);
  12950. ofs << "This is not a certificate file at all\n";
  12951. ofs << "Just plain text content\n";
  12952. }
  12953. // Create server with invalid CA file
  12954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12955. // Clean up temporary file
  12956. std::remove(temp_invalid_ca);
  12957. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12958. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12959. // Note: SSL_CTX_load_verify_locations typically fails first,
  12960. // but our error handling code path is still exercised
  12961. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12962. }
  12963. }
  12964. TEST(VerifyCallbackTest, VerifyContextFields) {
  12965. using namespace httplib::tls;
  12966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12967. ASSERT_TRUE(svr.is_valid());
  12968. svr.Get("/test", [](const Request &, Response &res) {
  12969. res.set_content("ok", "text/plain");
  12970. });
  12971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12972. auto se = detail::scope_exit([&] {
  12973. svr.stop();
  12974. t.join();
  12975. });
  12976. svr.wait_until_ready();
  12977. SSLClient cli(HOST, PORT);
  12978. cli.enable_server_certificate_verification(false);
  12979. cli.set_connection_timeout(30);
  12980. int callback_count = 0;
  12981. bool saw_leaf_cert = false;
  12982. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12983. if (ctx.cert) {
  12984. callback_count++;
  12985. // We should see at least one certificate (the leaf)
  12986. std::string cn = ctx.subject_cn();
  12987. if (!cn.empty()) { saw_leaf_cert = true; }
  12988. // Verify context fields are populated
  12989. EXPECT_NE(ctx.session, nullptr);
  12990. EXPECT_GE(ctx.depth, 0);
  12991. }
  12992. return true;
  12993. });
  12994. auto res = cli.Get("/test");
  12995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12996. EXPECT_GT(callback_count, 0);
  12997. EXPECT_TRUE(saw_leaf_cert);
  12998. }
  12999. // Each client's verifier is stored with its own TLS context, so configuring a
  13000. // second client on the same thread must not replace the first one's.
  13001. TEST(VerifyCallbackTest, PerClientVerifiersOnSameThread) {
  13002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13003. ASSERT_TRUE(svr.is_valid());
  13004. svr.Get("/test", [](const Request &, Response &res) {
  13005. res.set_content("ok", "text/plain");
  13006. });
  13007. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13008. auto se = detail::scope_exit([&] {
  13009. svr.stop();
  13010. t.join();
  13011. });
  13012. svr.wait_until_ready();
  13013. std::atomic<int> count1{0};
  13014. std::atomic<int> count2{0};
  13015. SSLClient cli1(HOST, PORT);
  13016. cli1.enable_server_certificate_verification(false);
  13017. cli1.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13018. count1++;
  13019. return true;
  13020. });
  13021. SSLClient cli2(HOST, PORT);
  13022. cli2.enable_server_certificate_verification(false);
  13023. cli2.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13024. count2++;
  13025. return true;
  13026. });
  13027. auto res1 = cli1.Get("/test");
  13028. ASSERT_TRUE(res1) << "Error: " << to_string(res1.error());
  13029. EXPECT_GT(count1.load(), 0);
  13030. EXPECT_EQ(0, count2.load());
  13031. count1 = 0;
  13032. auto res2 = cli2.Get("/test");
  13033. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  13034. EXPECT_EQ(0, count1.load());
  13035. EXPECT_GT(count2.load(), 0);
  13036. }
  13037. // A verifier set on one thread must still run when the request is made from
  13038. // another thread.
  13039. TEST(VerifyCallbackTest, VerifierRunsOnAnotherThread) {
  13040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13041. ASSERT_TRUE(svr.is_valid());
  13042. svr.Get("/test", [](const Request &, Response &res) {
  13043. res.set_content("ok", "text/plain");
  13044. });
  13045. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13046. auto se = detail::scope_exit([&] {
  13047. svr.stop();
  13048. t.join();
  13049. });
  13050. svr.wait_until_ready();
  13051. std::atomic<int> count{0};
  13052. SSLClient cli(HOST, PORT);
  13053. cli.enable_server_certificate_verification(false);
  13054. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13055. count++;
  13056. return true;
  13057. });
  13058. Result res;
  13059. thread worker([&]() { res = cli.Get("/test"); });
  13060. worker.join();
  13061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13062. EXPECT_GT(count.load(), 0);
  13063. }
  13064. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13065. using httplib::tls::TlsError;
  13066. // Test that verify_error_to_string returns empty for success
  13067. std::string success_str = TlsError::verify_error_to_string(0);
  13068. EXPECT_TRUE(success_str.empty());
  13069. // Test that verify_error_to_string returns non-empty for error codes
  13070. // Using a common error code (certificate expired)
  13071. std::string error_str =
  13072. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13073. EXPECT_FALSE(error_str.empty());
  13074. }
  13075. TEST(SessionVerifierTest, CertificateAccepted) {
  13076. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13077. ASSERT_TRUE(svr.is_valid());
  13078. svr.Get("/test", [](const Request &, Response &res) {
  13079. res.set_content("ok", "text/plain");
  13080. });
  13081. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13082. auto se = detail::scope_exit([&] {
  13083. svr.stop();
  13084. t.join();
  13085. });
  13086. svr.wait_until_ready();
  13087. SSLClient cli(HOST, PORT);
  13088. cli.enable_server_certificate_verification(false);
  13089. cli.set_connection_timeout(30);
  13090. bool callback_called = false;
  13091. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13092. EXPECT_NE(session, nullptr);
  13093. callback_called = true;
  13094. return SSLVerifierResponse::CertificateAccepted;
  13095. });
  13096. auto res = cli.Get("/test");
  13097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13098. EXPECT_EQ(200, res->status);
  13099. EXPECT_TRUE(callback_called);
  13100. }
  13101. TEST(SessionVerifierTest, CertificateRejected) {
  13102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13103. ASSERT_TRUE(svr.is_valid());
  13104. svr.Get("/test", [](const Request &, Response &res) {
  13105. res.set_content("ok", "text/plain");
  13106. });
  13107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13108. auto se = detail::scope_exit([&] {
  13109. svr.stop();
  13110. t.join();
  13111. });
  13112. svr.wait_until_ready();
  13113. SSLClient cli(HOST, PORT);
  13114. cli.enable_server_certificate_verification(false);
  13115. cli.set_connection_timeout(30);
  13116. bool callback_called = false;
  13117. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13118. EXPECT_NE(session, nullptr);
  13119. callback_called = true;
  13120. return SSLVerifierResponse::CertificateRejected;
  13121. });
  13122. auto res = cli.Get("/test");
  13123. EXPECT_FALSE(res);
  13124. EXPECT_TRUE(callback_called);
  13125. }
  13126. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13128. ASSERT_TRUE(svr.is_valid());
  13129. svr.Get("/test", [](const Request &, Response &res) {
  13130. res.set_content("ok", "text/plain");
  13131. });
  13132. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13133. auto se = detail::scope_exit([&] {
  13134. svr.stop();
  13135. t.join();
  13136. });
  13137. svr.wait_until_ready();
  13138. // NoDecisionMade with verification disabled should succeed (no default check)
  13139. SSLClient cli(HOST, PORT);
  13140. cli.enable_server_certificate_verification(false);
  13141. cli.set_connection_timeout(30);
  13142. bool callback_called = false;
  13143. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13144. EXPECT_NE(session, nullptr);
  13145. callback_called = true;
  13146. return SSLVerifierResponse::NoDecisionMade;
  13147. });
  13148. auto res = cli.Get("/test");
  13149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13150. EXPECT_EQ(200, res->status);
  13151. EXPECT_TRUE(callback_called);
  13152. }
  13153. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13154. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13155. ASSERT_TRUE(svr.is_valid());
  13156. svr.Get("/test", [](const Request &, Response &res) {
  13157. res.set_content("ok", "text/plain");
  13158. });
  13159. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13160. auto se = detail::scope_exit([&] {
  13161. svr.stop();
  13162. t.join();
  13163. });
  13164. svr.wait_until_ready();
  13165. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13166. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13167. // so we only check that the request fails, not whether the callback was
  13168. // called.
  13169. SSLClient cli(HOST, PORT);
  13170. cli.enable_server_certificate_verification(true);
  13171. cli.set_connection_timeout(30);
  13172. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13173. EXPECT_NE(session, nullptr);
  13174. return SSLVerifierResponse::NoDecisionMade;
  13175. });
  13176. auto res = cli.Get("/test");
  13177. EXPECT_FALSE(res);
  13178. }
  13179. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13180. // Test SSL server using PemMemory constructor with client CA certificates
  13181. // Read PEM files
  13182. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13183. read_file(SERVER_CERT_FILE, server_cert_pem);
  13184. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13185. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13186. // Create SSLServer with PemMemory constructor including client CA
  13187. SSLServer::PemMemory server_pem = {
  13188. server_cert_pem.c_str(),
  13189. server_cert_pem.size(),
  13190. server_key_pem.c_str(),
  13191. server_key_pem.size(),
  13192. client_ca_pem.c_str(),
  13193. client_ca_pem.size(),
  13194. nullptr // no password for server key
  13195. };
  13196. SSLServer svr(server_pem);
  13197. ASSERT_TRUE(svr.is_valid());
  13198. // No SSL error should be recorded for valid setup
  13199. EXPECT_EQ(0, svr.ssl_last_error());
  13200. // Set up server endpoints
  13201. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13202. res.set_content("ok", "text/plain");
  13203. });
  13204. // Start server in a thread
  13205. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13206. svr.wait_until_ready();
  13207. // Connect with client certificate (using constructor with paths)
  13208. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13209. cli.enable_server_certificate_verification(false);
  13210. auto res = cli.Get("/test-pem-ca");
  13211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13212. EXPECT_EQ(200, res->status);
  13213. EXPECT_EQ("ok", res->body);
  13214. svr.stop();
  13215. server_thread.join();
  13216. }
  13217. #endif
  13218. #ifdef _WIN32
  13219. TEST(CleanupTest, WSACleanup) {
  13220. int ret = WSACleanup();
  13221. ASSERT_EQ(0, ret);
  13222. }
  13223. #endif
  13224. #ifndef CPPHTTPLIB_SSL_ENABLED
  13225. TEST(NoSSLSupport, SimpleInterface) {
  13226. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13227. }
  13228. #endif
  13229. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13230. TEST(InvalidScheme, SimpleInterface) {
  13231. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13232. }
  13233. #endif
  13234. TEST(NoScheme, SimpleInterface) {
  13235. Client cli("yahoo.com:80");
  13236. ASSERT_TRUE(cli.is_valid());
  13237. }
  13238. TEST(SendAPI, SimpleInterface_Online) {
  13239. Client cli("http://yahoo.com");
  13240. Request req;
  13241. req.method = "GET";
  13242. req.path = "/";
  13243. auto res = cli.send(req);
  13244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13245. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13246. }
  13247. TEST(SendAPI, WithParamsInRequest) {
  13248. Server svr;
  13249. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13250. EXPECT_TRUE(req.has_param("test"));
  13251. EXPECT_EQ("test_value", req.get_param_value("test"));
  13252. });
  13253. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. Client cli(HOST, PORT);
  13261. {
  13262. Request req;
  13263. req.method = "GET";
  13264. req.path = "/";
  13265. req.params.emplace("test", "test_value");
  13266. auto res = cli.send(req);
  13267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13268. }
  13269. {
  13270. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13272. }
  13273. }
  13274. TEST(ClientImplMethods, GetSocketTest) {
  13275. httplib::Server svr;
  13276. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13277. res.status = StatusCode::OK_200;
  13278. });
  13279. auto port = svr.bind_to_any_port("127.0.0.1");
  13280. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13281. auto se = detail::scope_exit([&] {
  13282. svr.stop();
  13283. thread.join();
  13284. ASSERT_FALSE(svr.is_running());
  13285. });
  13286. svr.wait_until_ready();
  13287. {
  13288. httplib::Client cli("127.0.0.1", port);
  13289. cli.set_keep_alive(true);
  13290. // Use the behavior of cpp-httplib of opening the connection
  13291. // only when the first request happens. If that changes,
  13292. // this test would be obsolete.
  13293. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13294. // This also implicitly tests the server. But other tests would fail much
  13295. // earlier than this one to be considered.
  13296. auto res = cli.Get("/");
  13297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13298. EXPECT_EQ(StatusCode::OK_200, res->status);
  13299. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13300. }
  13301. }
  13302. #ifdef CPPHTTPLIB_SSL_ENABLED
  13303. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13304. Client cli("http://yahoo.com");
  13305. auto res = cli.Get("/");
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13308. cli.set_follow_location(true);
  13309. res = cli.Get("/");
  13310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13311. EXPECT_EQ(StatusCode::OK_200, res->status);
  13312. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13313. }
  13314. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13315. Client cli("https://yahoo.com");
  13316. auto res = cli.Get("/");
  13317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13318. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13319. cli.set_follow_location(true);
  13320. res = cli.Get("/");
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. EXPECT_EQ(StatusCode::OK_200, res->status);
  13323. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13324. }
  13325. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13326. Client cli("https://yahoo.com");
  13327. auto res = cli.Get("/");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. ASSERT_FALSE(!res);
  13330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13331. ASSERT_FALSE(res == nullptr);
  13332. ASSERT_TRUE(res != nullptr);
  13333. EXPECT_EQ(Error::Success, res.error());
  13334. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13335. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13336. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13337. cli.set_follow_location(true);
  13338. res = cli.Get("/");
  13339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13340. EXPECT_EQ(Error::Success, res.error());
  13341. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13342. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13343. EXPECT_EQ(StatusCode::OK_200, res->status);
  13344. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13345. }
  13346. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13347. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13348. Client cli("https://cdnjs.cloudflare.com");
  13349. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13350. Headers{{"Accept-Encoding", "br"}});
  13351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13352. EXPECT_EQ(StatusCode::OK_200, res->status);
  13353. EXPECT_EQ(287630U, res->body.size());
  13354. EXPECT_EQ("application/javascript; charset=utf-8",
  13355. res->get_header_value("Content-Type"));
  13356. }
  13357. #endif
  13358. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13359. #undef REDIR_HOST // Silence compiler warning
  13360. #define REDIR_HOST "https://httpbingo.org"
  13361. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13362. Client cli(REDIR_HOST);
  13363. cli.set_follow_location(true);
  13364. auto res =
  13365. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13367. EXPECT_EQ(StatusCode::OK_200, res->status);
  13368. }
  13369. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13370. Client cli(REDIR_HOST);
  13371. cli.set_follow_location(true);
  13372. Params params;
  13373. params.emplace("url", "http://example.com");
  13374. params.emplace("status_code", "302");
  13375. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13377. EXPECT_EQ(StatusCode::OK_200, res->status);
  13378. }
  13379. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13380. Client cli(REDIR_HOST);
  13381. cli.set_follow_location(true);
  13382. Params params;
  13383. params.emplace("url", "http://example.com");
  13384. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13386. EXPECT_EQ(StatusCode::OK_200, res->status);
  13387. }
  13388. TEST(HttpToHttpsRedirectTest, CertFile) {
  13389. auto ssl_port = PORT + 1;
  13390. Server svr;
  13391. ASSERT_TRUE(svr.is_valid());
  13392. svr.Get("/index", [&](const Request &, Response &res) {
  13393. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13394. "/index");
  13395. svr.stop();
  13396. });
  13397. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13398. ASSERT_TRUE(ssl_svr.is_valid());
  13399. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13400. res.set_content("test", "text/plain");
  13401. ssl_svr.stop();
  13402. });
  13403. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13404. thread t2 =
  13405. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13406. auto se = detail::scope_exit([&] {
  13407. t2.join();
  13408. t.join();
  13409. ASSERT_FALSE(svr.is_running());
  13410. });
  13411. svr.wait_until_ready();
  13412. ssl_svr.wait_until_ready();
  13413. Client cli("127.0.0.1", PORT);
  13414. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13415. cli.enable_server_certificate_verification(true);
  13416. cli.set_follow_location(true);
  13417. cli.set_connection_timeout(30);
  13418. auto res = cli.Get("/index");
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. ASSERT_EQ(StatusCode::OK_200, res->status);
  13421. }
  13422. TEST(SSLClientRedirectTest, CertFile) {
  13423. auto ssl_port = PORT + 1;
  13424. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13425. ASSERT_TRUE(ssl_svr1.is_valid());
  13426. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13427. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13428. "/index");
  13429. ssl_svr1.stop();
  13430. });
  13431. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13432. ASSERT_TRUE(ssl_svr2.is_valid());
  13433. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13434. res.set_content("test", "text/plain");
  13435. ssl_svr2.stop();
  13436. });
  13437. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13438. thread t2 =
  13439. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13440. auto se = detail::scope_exit([&] {
  13441. t2.join();
  13442. t.join();
  13443. ASSERT_FALSE(ssl_svr1.is_running());
  13444. });
  13445. ssl_svr1.wait_until_ready();
  13446. ssl_svr2.wait_until_ready();
  13447. SSLClient cli("127.0.0.1", PORT);
  13448. std::string cert;
  13449. read_file(SERVER_CERT2_FILE, cert);
  13450. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13451. cli.enable_server_certificate_verification(true);
  13452. cli.set_follow_location(true);
  13453. cli.set_connection_timeout(30);
  13454. auto res = cli.Get("/index");
  13455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13456. ASSERT_EQ(StatusCode::OK_200, res->status);
  13457. }
  13458. // A store set via set_ca_cert_store() must be carried over to the client that
  13459. // follows a cross-host redirect, rather than replaced by the system CAs.
  13460. TEST(SSLClientRedirectTest, SetCaCertStore) {
  13461. auto ssl_port = PORT + 1;
  13462. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13463. ASSERT_TRUE(ssl_svr1.is_valid());
  13464. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13465. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13466. "/index");
  13467. });
  13468. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13469. ASSERT_TRUE(ssl_svr2.is_valid());
  13470. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13471. res.set_content("test", "text/plain");
  13472. });
  13473. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13474. thread t2 =
  13475. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13476. auto se = detail::scope_exit([&] {
  13477. ssl_svr2.stop();
  13478. ssl_svr1.stop();
  13479. t2.join();
  13480. t.join();
  13481. ASSERT_FALSE(ssl_svr1.is_running());
  13482. });
  13483. ssl_svr1.wait_until_ready();
  13484. ssl_svr2.wait_until_ready();
  13485. SSLClient cli("127.0.0.1", PORT);
  13486. std::string cert;
  13487. read_file(SERVER_CERT2_FILE, cert);
  13488. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13489. cli.enable_server_certificate_verification(true);
  13490. cli.set_follow_location(true);
  13491. cli.set_connection_timeout(30);
  13492. auto res = cli.Get("/index");
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. ASSERT_EQ(StatusCode::OK_200, res->status);
  13495. }
  13496. // The session verifier must also run for the host a redirect leads to.
  13497. TEST(SSLClientRedirectTest, SessionVerifier) {
  13498. auto ssl_port = PORT + 1;
  13499. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13500. ASSERT_TRUE(ssl_svr1.is_valid());
  13501. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13502. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13503. "/index");
  13504. });
  13505. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13506. ASSERT_TRUE(ssl_svr2.is_valid());
  13507. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13508. res.set_content("test", "text/plain");
  13509. });
  13510. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13511. thread t2 =
  13512. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13513. auto se = detail::scope_exit([&] {
  13514. ssl_svr2.stop();
  13515. ssl_svr1.stop();
  13516. t2.join();
  13517. t.join();
  13518. ASSERT_FALSE(ssl_svr1.is_running());
  13519. });
  13520. ssl_svr1.wait_until_ready();
  13521. ssl_svr2.wait_until_ready();
  13522. SSLClient cli("127.0.0.1", PORT);
  13523. std::string cert;
  13524. read_file(SERVER_CERT2_FILE, cert);
  13525. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13526. cli.enable_server_certificate_verification(true);
  13527. cli.set_follow_location(true);
  13528. cli.set_connection_timeout(30);
  13529. // Accept the first host only.
  13530. std::atomic<int> sessions{0};
  13531. cli.set_session_verifier([&](tls::session_t) -> SSLVerifierResponse {
  13532. return sessions++ == 0 ? SSLVerifierResponse::CertificateAccepted
  13533. : SSLVerifierResponse::CertificateRejected;
  13534. });
  13535. auto res = cli.Get("/index");
  13536. ASSERT_FALSE(res);
  13537. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13538. EXPECT_EQ(2, sessions.load());
  13539. }
  13540. // So must the verifier given to set_server_certificate_verifier().
  13541. TEST(SSLClientRedirectTest, ServerCertificateVerifier) {
  13542. auto ssl_port = PORT + 1;
  13543. std::atomic<bool> redirected{false};
  13544. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13545. ASSERT_TRUE(ssl_svr1.is_valid());
  13546. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13547. redirected = true;
  13548. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13549. "/index");
  13550. });
  13551. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13552. ASSERT_TRUE(ssl_svr2.is_valid());
  13553. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13554. res.set_content("test", "text/plain");
  13555. });
  13556. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13557. thread t2 =
  13558. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13559. auto se = detail::scope_exit([&] {
  13560. ssl_svr2.stop();
  13561. ssl_svr1.stop();
  13562. t2.join();
  13563. t.join();
  13564. ASSERT_FALSE(ssl_svr1.is_running());
  13565. });
  13566. ssl_svr1.wait_until_ready();
  13567. ssl_svr2.wait_until_ready();
  13568. SSLClient cli("127.0.0.1", PORT);
  13569. std::string cert;
  13570. read_file(SERVER_CERT2_FILE, cert);
  13571. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13572. cli.enable_server_certificate_verification(true);
  13573. cli.set_follow_location(true);
  13574. cli.set_connection_timeout(30);
  13575. // Accept the host that redirects only; the verifier runs once per
  13576. // certificate in the chain, so count the calls made after the redirect.
  13577. std::atomic<int> calls_after_redirect{0};
  13578. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13579. if (!redirected) { return true; }
  13580. calls_after_redirect++;
  13581. return false;
  13582. });
  13583. auto res = cli.Get("/index");
  13584. ASSERT_FALSE(res);
  13585. EXPECT_LT(0, calls_after_redirect.load());
  13586. }
  13587. #endif
  13588. #ifdef CPPHTTPLIB_SSL_ENABLED
  13589. // Test that set_ca_cert_store() skips system certs (consistent with
  13590. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13591. // should be trusted - system certs should NOT be loaded.
  13592. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13593. // Load a specific cert that is NOT a system CA cert
  13594. std::string cert;
  13595. read_file(SERVER_CERT2_FILE, cert);
  13596. SSLClient cli("google.com");
  13597. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13598. cli.enable_server_certificate_verification(true);
  13599. // This should FAIL because:
  13600. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13601. // 2. System certs should NOT be loaded when custom store is set
  13602. // If system certs WERE loaded, this would succeed
  13603. auto res = cli.Get("/");
  13604. ASSERT_FALSE(res);
  13605. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13606. }
  13607. // Same as above, but through the native store handle path. Regression test:
  13608. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13609. // merged system certs into the user-provided store.
  13610. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13611. std::string cert;
  13612. read_file(SERVER_CERT2_FILE, cert);
  13613. SSLClient cli("google.com");
  13614. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13615. cli.enable_server_certificate_verification(true);
  13616. auto res = cli.Get("/");
  13617. ASSERT_FALSE(res);
  13618. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13619. }
  13620. // A custom store set via the native handle must still verify a server whose
  13621. // cert it does contain.
  13622. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13623. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13624. ASSERT_TRUE(svr.is_valid());
  13625. svr.Get("/test", [&](const Request &, Response &res) {
  13626. res.set_content("test", "text/plain");
  13627. });
  13628. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13629. auto se = detail::scope_exit([&] {
  13630. svr.stop();
  13631. t.join();
  13632. ASSERT_FALSE(svr.is_running());
  13633. });
  13634. svr.wait_until_ready();
  13635. SSLClient cli("127.0.0.1", PORT);
  13636. std::string cert;
  13637. read_file(SERVER_CERT2_FILE, cert);
  13638. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13639. cli.enable_server_certificate_verification(true);
  13640. cli.set_connection_timeout(30);
  13641. auto res = cli.Get("/test");
  13642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13643. ASSERT_EQ(StatusCode::OK_200, res->status);
  13644. }
  13645. // CA certs loaded through the universal Client must be transferred to the
  13646. // client created internally for following an HTTPS redirect. Regression test:
  13647. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13648. // the CA data for redirect transfer.
  13649. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13650. auto ssl_port = PORT + 1;
  13651. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13652. ASSERT_TRUE(ssl_svr1.is_valid());
  13653. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13654. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13655. "/index");
  13656. });
  13657. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13658. ASSERT_TRUE(ssl_svr2.is_valid());
  13659. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13660. res.set_content("test", "text/plain");
  13661. });
  13662. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13663. thread t2 =
  13664. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13665. auto se = detail::scope_exit([&] {
  13666. ssl_svr2.stop();
  13667. ssl_svr1.stop();
  13668. t2.join();
  13669. t.join();
  13670. ASSERT_FALSE(ssl_svr1.is_running());
  13671. });
  13672. ssl_svr1.wait_until_ready();
  13673. ssl_svr2.wait_until_ready();
  13674. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13675. std::string cert;
  13676. read_file(SERVER_CERT2_FILE, cert);
  13677. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13678. cli.enable_server_certificate_verification(true);
  13679. cli.set_follow_location(true);
  13680. cli.set_connection_timeout(30);
  13681. auto res = cli.Get("/index");
  13682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13683. ASSERT_EQ(StatusCode::OK_200, res->status);
  13684. }
  13685. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13686. // so a host signed by a system CA verifies even though a custom CA is set
  13687. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13688. std::string cert;
  13689. read_file(SERVER_CERT2_FILE, cert);
  13690. SSLClient cli("google.com");
  13691. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13692. cli.enable_system_ca(true);
  13693. cli.enable_server_certificate_verification(true);
  13694. auto res = cli.Get("/");
  13695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13696. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13697. }
  13698. // The custom CA remains effective when combined with the system CA
  13699. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13700. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13701. ASSERT_TRUE(svr.is_valid());
  13702. svr.Get("/test", [&](const Request &, Response &res) {
  13703. res.set_content("test", "text/plain");
  13704. });
  13705. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13706. auto se = detail::scope_exit([&] {
  13707. svr.stop();
  13708. t.join();
  13709. ASSERT_FALSE(svr.is_running());
  13710. });
  13711. svr.wait_until_ready();
  13712. SSLClient cli("127.0.0.1", PORT);
  13713. std::string cert;
  13714. read_file(SERVER_CERT2_FILE, cert);
  13715. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13716. cli.enable_system_ca(true);
  13717. cli.enable_server_certificate_verification(true);
  13718. cli.set_connection_timeout(30);
  13719. auto res = cli.Get("/test");
  13720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13721. ASSERT_EQ(StatusCode::OK_200, res->status);
  13722. }
  13723. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13724. // skip chain verification entirely (only the certificate identity was
  13725. // checked), so a server presenting an untrusted certificate with a matching
  13726. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13727. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13728. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. svr.Get("/test", [&](const Request &, Response &res) {
  13731. res.set_content("test", "text/plain");
  13732. });
  13733. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13734. auto se = detail::scope_exit([&] {
  13735. svr.stop();
  13736. t.join();
  13737. ASSERT_FALSE(svr.is_running());
  13738. });
  13739. svr.wait_until_ready();
  13740. SSLClient cli("127.0.0.1", PORT);
  13741. std::string cert;
  13742. // A trusted CA that did not sign the server certificate. The server cert
  13743. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13744. // this connection.
  13745. read_file(CLIENT_CA_CERT_FILE, cert);
  13746. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13747. cli.enable_server_certificate_verification(true);
  13748. cli.set_connection_timeout(30);
  13749. auto res = cli.Get("/test");
  13750. ASSERT_FALSE(res);
  13751. }
  13752. // enable_system_ca(false) prevents system CA loading entirely
  13753. TEST(SSLClientTest, DisableSystemCa_Online) {
  13754. SSLClient cli("google.com");
  13755. cli.enable_system_ca(false);
  13756. cli.enable_server_certificate_verification(true);
  13757. auto res = cli.Get("/");
  13758. ASSERT_FALSE(res);
  13759. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13760. // itself when the CA chain is empty
  13761. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13762. res.error() == Error::SSLConnection);
  13763. }
  13764. // The universal Client forwards enable_system_ca()
  13765. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13766. std::string cert;
  13767. read_file(SERVER_CERT2_FILE, cert);
  13768. Client cli("https://google.com");
  13769. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13770. cli.enable_system_ca(true);
  13771. cli.enable_server_certificate_verification(true);
  13772. auto res = cli.Get("/");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13775. }
  13776. // The system CA policy must carry over to the client created internally for
  13777. // following a cross-host HTTPS redirect
  13778. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13779. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13780. ASSERT_TRUE(svr.is_valid());
  13781. svr.Get("/index", [&](const Request &, Response &res) {
  13782. res.set_redirect("https://www.google.com/");
  13783. });
  13784. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13785. auto se = detail::scope_exit([&] {
  13786. svr.stop();
  13787. t.join();
  13788. ASSERT_FALSE(svr.is_running());
  13789. });
  13790. svr.wait_until_ready();
  13791. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13792. std::string cert;
  13793. read_file(SERVER_CERT2_FILE, cert);
  13794. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13795. cli.enable_system_ca(true);
  13796. cli.enable_server_certificate_verification(true);
  13797. cli.set_follow_location(true);
  13798. cli.set_connection_timeout(30);
  13799. // Receiving any response proves the redirect client completed the TLS
  13800. // handshake with a system-CA-signed host
  13801. auto res = cli.Get("/index");
  13802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13803. }
  13804. TEST(MultipartFormDataTest, LargeData) {
  13805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13806. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13807. const ContentReader &content_reader) {
  13808. if (req.is_multipart_form_data()) {
  13809. std::vector<FormData> items;
  13810. content_reader(
  13811. [&](const FormData &file) {
  13812. items.push_back(file);
  13813. return true;
  13814. },
  13815. [&](const char *data, size_t data_length) {
  13816. items.back().content.append(data, data_length);
  13817. return true;
  13818. });
  13819. EXPECT_TRUE(std::string(items[0].name) == "document");
  13820. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13821. EXPECT_TRUE(items[0].filename == "2MB_data");
  13822. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13823. EXPECT_TRUE(items[1].name == "hello");
  13824. EXPECT_TRUE(items[1].content == "world");
  13825. EXPECT_TRUE(items[1].filename == "");
  13826. EXPECT_TRUE(items[1].content_type == "");
  13827. } else {
  13828. std::string body;
  13829. content_reader([&](const char *data, size_t data_length) {
  13830. body.append(data, data_length);
  13831. return true;
  13832. });
  13833. }
  13834. });
  13835. auto port = svr.bind_to_any_port(HOST);
  13836. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13837. auto se = detail::scope_exit([&] {
  13838. svr.stop();
  13839. t.join();
  13840. ASSERT_FALSE(svr.is_running());
  13841. });
  13842. svr.wait_until_ready();
  13843. {
  13844. std::string data(1024 * 1024 * 2, '.');
  13845. std::stringstream buffer;
  13846. buffer << data;
  13847. SSLClient cli(HOST, port);
  13848. cli.enable_server_certificate_verification(false);
  13849. UploadFormDataItems items{
  13850. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13851. {"hello", "world", "", ""},
  13852. };
  13853. auto res = cli.Post("/post", items);
  13854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13855. ASSERT_EQ(StatusCode::OK_200, res->status);
  13856. }
  13857. }
  13858. TEST(MultipartFormDataTest, DataProviderItems) {
  13859. std::random_device seed_gen;
  13860. std::mt19937 random(seed_gen());
  13861. std::string rand1;
  13862. rand1.resize(1000);
  13863. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13864. std::string rand2;
  13865. rand2.resize(3000);
  13866. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13868. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13869. const ContentReader &content_reader) {
  13870. ASSERT_FALSE(req.is_multipart_form_data());
  13871. std::string body;
  13872. content_reader([&](const char *data, size_t data_length) {
  13873. body.append(data, data_length);
  13874. return true;
  13875. });
  13876. EXPECT_EQ(body, "");
  13877. });
  13878. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13879. const ContentReader &content_reader) {
  13880. ASSERT_TRUE(req.is_multipart_form_data());
  13881. std::vector<FormData> items;
  13882. content_reader(
  13883. [&](const FormData &file) {
  13884. items.push_back(file);
  13885. return true;
  13886. },
  13887. [&](const char *data, size_t data_length) {
  13888. items.back().content.append(data, data_length);
  13889. return true;
  13890. });
  13891. ASSERT_TRUE(items.size() == 2);
  13892. EXPECT_EQ(std::string(items[0].name), "name1");
  13893. EXPECT_EQ(items[0].content, "Testing123");
  13894. EXPECT_EQ(items[0].filename, "filename1");
  13895. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13896. EXPECT_EQ(items[1].name, "name2");
  13897. EXPECT_EQ(items[1].content, "Testing456");
  13898. EXPECT_EQ(items[1].filename, "");
  13899. EXPECT_EQ(items[1].content_type, "");
  13900. });
  13901. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13902. const ContentReader &content_reader) {
  13903. ASSERT_TRUE(req.is_multipart_form_data());
  13904. std::vector<FormData> items;
  13905. content_reader(
  13906. [&](const FormData &file) {
  13907. items.push_back(file);
  13908. return true;
  13909. },
  13910. [&](const char *data, size_t data_length) {
  13911. items.back().content.append(data, data_length);
  13912. return true;
  13913. });
  13914. ASSERT_TRUE(items.size() == 2);
  13915. EXPECT_EQ(items[0].name, "name3");
  13916. EXPECT_EQ(items[0].content, rand1);
  13917. EXPECT_EQ(items[0].filename, "filename3");
  13918. EXPECT_EQ(items[0].content_type, "");
  13919. EXPECT_EQ(items[1].name, "name4");
  13920. EXPECT_EQ(items[1].content, rand2);
  13921. EXPECT_EQ(items[1].filename, "filename4");
  13922. EXPECT_EQ(items[1].content_type, "");
  13923. });
  13924. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13925. const ContentReader &content_reader) {
  13926. ASSERT_TRUE(req.is_multipart_form_data());
  13927. std::vector<FormData> items;
  13928. content_reader(
  13929. [&](const FormData &file) {
  13930. items.push_back(file);
  13931. return true;
  13932. },
  13933. [&](const char *data, size_t data_length) {
  13934. items.back().content.append(data, data_length);
  13935. return true;
  13936. });
  13937. ASSERT_TRUE(items.size() == 4);
  13938. EXPECT_EQ(std::string(items[0].name), "name1");
  13939. EXPECT_EQ(items[0].content, "Testing123");
  13940. EXPECT_EQ(items[0].filename, "filename1");
  13941. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13942. EXPECT_EQ(items[1].name, "name2");
  13943. EXPECT_EQ(items[1].content, "Testing456");
  13944. EXPECT_EQ(items[1].filename, "");
  13945. EXPECT_EQ(items[1].content_type, "");
  13946. EXPECT_EQ(items[2].name, "name3");
  13947. EXPECT_EQ(items[2].content, rand1);
  13948. EXPECT_EQ(items[2].filename, "filename3");
  13949. EXPECT_EQ(items[2].content_type, "");
  13950. EXPECT_EQ(items[3].name, "name4");
  13951. EXPECT_EQ(items[3].content, rand2);
  13952. EXPECT_EQ(items[3].filename, "filename4");
  13953. EXPECT_EQ(items[3].content_type, "");
  13954. });
  13955. auto port = svr.bind_to_any_port("localhost");
  13956. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13957. auto se = detail::scope_exit([&] {
  13958. svr.stop();
  13959. t.join();
  13960. ASSERT_FALSE(svr.is_running());
  13961. });
  13962. svr.wait_until_ready();
  13963. {
  13964. SSLClient cli("localhost", port);
  13965. cli.enable_server_certificate_verification(false);
  13966. UploadFormDataItems items{
  13967. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13968. {"name2", "Testing456", "", ""}, // not a file
  13969. };
  13970. {
  13971. auto res = cli.Post("/post-none", {}, {}, {});
  13972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13973. ASSERT_EQ(StatusCode::OK_200, res->status);
  13974. }
  13975. FormDataProviderItems providers;
  13976. {
  13977. auto res =
  13978. cli.Post("/post-items", {}, items, providers); // empty providers
  13979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13980. ASSERT_EQ(StatusCode::OK_200, res->status);
  13981. }
  13982. providers.push_back({"name3",
  13983. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13984. // test the offset is given correctly at each step
  13985. if (!offset)
  13986. sink.os.write(rand1.data(), 30);
  13987. else if (offset == 30)
  13988. sink.os.write(rand1.data() + 30, 300);
  13989. else if (offset == 330)
  13990. sink.os.write(rand1.data() + 330, 670);
  13991. else if (offset == rand1.size())
  13992. sink.done();
  13993. return true;
  13994. },
  13995. "filename3",
  13996. {}});
  13997. providers.push_back({"name4",
  13998. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13999. // test the offset is given correctly at each step
  14000. if (!offset)
  14001. sink.os.write(rand2.data(), 2000);
  14002. else if (offset == 2000)
  14003. sink.os.write(rand2.data() + 2000, 1);
  14004. else if (offset == 2001)
  14005. sink.os.write(rand2.data() + 2001, 999);
  14006. else if (offset == rand2.size())
  14007. sink.done();
  14008. return true;
  14009. },
  14010. "filename4",
  14011. {}});
  14012. {
  14013. auto res = cli.Post("/post-providers", {}, {}, providers);
  14014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14015. ASSERT_EQ(StatusCode::OK_200, res->status);
  14016. }
  14017. {
  14018. auto res = cli.Post("/post-both", {}, items, providers);
  14019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14020. ASSERT_EQ(StatusCode::OK_200, res->status);
  14021. }
  14022. }
  14023. }
  14024. TEST(MultipartFormDataTest, BadHeader) {
  14025. Server svr;
  14026. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14027. res.set_content("ok", "text/plain");
  14028. });
  14029. thread t = thread([&] { svr.listen(HOST, PORT); });
  14030. auto se = detail::scope_exit([&] {
  14031. svr.stop();
  14032. t.join();
  14033. ASSERT_FALSE(svr.is_running());
  14034. });
  14035. svr.wait_until_ready();
  14036. const std::string body =
  14037. "This is the preamble. It is to be ignored, though it\r\n"
  14038. "is a handy place for composition agents to include an\r\n"
  14039. "explanatory note to non-MIME conformant readers.\r\n"
  14040. "\r\n"
  14041. "\r\n"
  14042. "--simple boundary\r\n"
  14043. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14044. ": BAD...\r\n"
  14045. "\r\n"
  14046. "value1\r\n"
  14047. "--simple boundary\r\n"
  14048. "Content-Disposition: form-data; name=\"field2\"; "
  14049. "filename=\"example.txt\"\r\n"
  14050. "\r\n"
  14051. "value2\r\n"
  14052. "--simple boundary--\r\n"
  14053. "This is the epilogue. It is also to be ignored.\r\n";
  14054. std::string content_type =
  14055. R"(multipart/form-data; boundary="simple boundary")";
  14056. Client cli(HOST, PORT);
  14057. auto res = cli.Post("/post", body, content_type.c_str());
  14058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14059. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14060. }
  14061. TEST(MultipartFormDataTest, WithPreamble) {
  14062. Server svr;
  14063. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14064. res.set_content("ok", "text/plain");
  14065. });
  14066. thread t = thread([&] { svr.listen(HOST, PORT); });
  14067. auto se = detail::scope_exit([&] {
  14068. svr.stop();
  14069. t.join();
  14070. ASSERT_FALSE(svr.is_running());
  14071. });
  14072. svr.wait_until_ready();
  14073. const std::string body =
  14074. "This is the preamble. It is to be ignored, though it\r\n"
  14075. "is a handy place for composition agents to include an\r\n"
  14076. "explanatory note to non-MIME conformant readers.\r\n"
  14077. "\r\n"
  14078. "\r\n"
  14079. "--simple boundary\r\n"
  14080. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14081. "\r\n"
  14082. "value1\r\n"
  14083. "--simple boundary\r\n"
  14084. "Content-Disposition: form-data; name=\"field2\"; "
  14085. "filename=\"example.txt\"\r\n"
  14086. "\r\n"
  14087. "value2\r\n"
  14088. "--simple boundary--\r\n"
  14089. "This is the epilogue. It is also to be ignored.\r\n";
  14090. std::string content_type =
  14091. R"(multipart/form-data; boundary="simple boundary")";
  14092. Client cli(HOST, PORT);
  14093. auto res = cli.Post("/post", body, content_type.c_str());
  14094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14095. EXPECT_EQ(StatusCode::OK_200, res->status);
  14096. }
  14097. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14099. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14100. const ContentReader &content_reader) {
  14101. if (req.is_multipart_form_data()) {
  14102. std::vector<FormData> items;
  14103. content_reader(
  14104. [&](const FormData &file) {
  14105. items.push_back(file);
  14106. return true;
  14107. },
  14108. [&](const char *data, size_t data_length) {
  14109. items.back().content.append(data, data_length);
  14110. return true;
  14111. });
  14112. EXPECT_TRUE(std::string(items[0].name) == "document");
  14113. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14114. EXPECT_TRUE(items[0].filename == "2MB_data");
  14115. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14116. EXPECT_TRUE(items[1].name == "hello");
  14117. EXPECT_TRUE(items[1].content == "world");
  14118. EXPECT_TRUE(items[1].filename == "");
  14119. EXPECT_TRUE(items[1].content_type == "");
  14120. } else {
  14121. std::string body;
  14122. content_reader([&](const char *data, size_t data_length) {
  14123. body.append(data, data_length);
  14124. return true;
  14125. });
  14126. }
  14127. });
  14128. auto port = svr.bind_to_any_port("localhost");
  14129. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14130. auto se = detail::scope_exit([&] {
  14131. svr.stop();
  14132. t.join();
  14133. ASSERT_FALSE(svr.is_running());
  14134. });
  14135. svr.wait_until_ready();
  14136. {
  14137. std::string data(1024 * 1024 * 2, '.');
  14138. std::stringstream buffer;
  14139. buffer << data;
  14140. SSLClient cli("localhost", port);
  14141. cli.enable_server_certificate_verification(false);
  14142. UploadFormDataItems items{
  14143. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14144. {"hello", "world", "", ""},
  14145. };
  14146. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14148. ASSERT_EQ(StatusCode::OK_200, res->status);
  14149. }
  14150. }
  14151. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14152. std::string data(1024 * 1024 * 2, '&');
  14153. std::stringstream buffer;
  14154. buffer << data;
  14155. Client cli("https://localhost:8080");
  14156. UploadFormDataItems items{
  14157. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14158. {"hello", "world", "", ""},
  14159. };
  14160. for (const char &c : " \t\r\n") {
  14161. auto res =
  14162. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14163. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14164. ASSERT_FALSE(res);
  14165. }
  14166. }
  14167. TEST(MultipartFormDataTest, PutFormData) {
  14168. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14169. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14170. const ContentReader &content_reader) {
  14171. if (req.is_multipart_form_data()) {
  14172. std::vector<FormData> items;
  14173. content_reader(
  14174. [&](const FormData &file) {
  14175. items.push_back(file);
  14176. return true;
  14177. },
  14178. [&](const char *data, size_t data_length) {
  14179. items.back().content.append(data, data_length);
  14180. return true;
  14181. });
  14182. EXPECT_TRUE(std::string(items[0].name) == "document");
  14183. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14184. EXPECT_TRUE(items[0].filename == "2MB_data");
  14185. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14186. EXPECT_TRUE(items[1].name == "hello");
  14187. EXPECT_TRUE(items[1].content == "world");
  14188. EXPECT_TRUE(items[1].filename == "");
  14189. EXPECT_TRUE(items[1].content_type == "");
  14190. } else {
  14191. std::string body;
  14192. content_reader([&](const char *data, size_t data_length) {
  14193. body.append(data, data_length);
  14194. return true;
  14195. });
  14196. }
  14197. });
  14198. auto port = svr.bind_to_any_port("localhost");
  14199. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14200. auto se = detail::scope_exit([&] {
  14201. svr.stop();
  14202. t.join();
  14203. ASSERT_FALSE(svr.is_running());
  14204. });
  14205. svr.wait_until_ready();
  14206. {
  14207. std::string data(1024 * 1024 * 2, '&');
  14208. std::stringstream buffer;
  14209. buffer << data;
  14210. SSLClient cli("localhost", port);
  14211. cli.enable_server_certificate_verification(false);
  14212. UploadFormDataItems items{
  14213. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14214. {"hello", "world", "", ""},
  14215. };
  14216. auto res = cli.Put("/put", items);
  14217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14218. ASSERT_EQ(StatusCode::OK_200, res->status);
  14219. }
  14220. }
  14221. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14222. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14223. svr.Put("/put_customboundary",
  14224. [&](const Request &req, const Response & /*res*/,
  14225. const ContentReader &content_reader) {
  14226. if (req.is_multipart_form_data()) {
  14227. std::vector<FormData> items;
  14228. content_reader(
  14229. [&](const FormData &file) {
  14230. items.push_back(file);
  14231. return true;
  14232. },
  14233. [&](const char *data, size_t data_length) {
  14234. items.back().content.append(data, data_length);
  14235. return true;
  14236. });
  14237. EXPECT_TRUE(std::string(items[0].name) == "document");
  14238. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14239. EXPECT_TRUE(items[0].filename == "2MB_data");
  14240. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14241. EXPECT_TRUE(items[1].name == "hello");
  14242. EXPECT_TRUE(items[1].content == "world");
  14243. EXPECT_TRUE(items[1].filename == "");
  14244. EXPECT_TRUE(items[1].content_type == "");
  14245. } else {
  14246. std::string body;
  14247. content_reader([&](const char *data, size_t data_length) {
  14248. body.append(data, data_length);
  14249. return true;
  14250. });
  14251. }
  14252. });
  14253. auto port = svr.bind_to_any_port("localhost");
  14254. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14255. auto se = detail::scope_exit([&] {
  14256. svr.stop();
  14257. t.join();
  14258. ASSERT_FALSE(svr.is_running());
  14259. });
  14260. svr.wait_until_ready();
  14261. {
  14262. std::string data(1024 * 1024 * 2, '&');
  14263. std::stringstream buffer;
  14264. buffer << data;
  14265. SSLClient cli("localhost", port);
  14266. cli.enable_server_certificate_verification(false);
  14267. UploadFormDataItems items{
  14268. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14269. {"hello", "world", "", ""},
  14270. };
  14271. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14273. ASSERT_EQ(StatusCode::OK_200, res->status);
  14274. }
  14275. }
  14276. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14277. std::string data(1024 * 1024 * 2, '&');
  14278. std::stringstream buffer;
  14279. buffer << data;
  14280. Client cli("https://localhost:8080");
  14281. cli.enable_server_certificate_verification(false);
  14282. UploadFormDataItems items{
  14283. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14284. {"hello", "world", "", ""},
  14285. };
  14286. for (const char &c : " \t\r\n") {
  14287. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14288. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14289. ASSERT_FALSE(res);
  14290. }
  14291. }
  14292. TEST(MultipartFormDataTest, AlternateFilename) {
  14293. auto handled = false;
  14294. Server svr;
  14295. svr.Post("/test", [&](const Request &req, Response &res) {
  14296. ASSERT_EQ(2u, req.form.files.size());
  14297. ASSERT_EQ(1u, req.form.fields.size());
  14298. // Test files
  14299. const auto &file1 = req.form.get_file("file1");
  14300. ASSERT_EQ("file1", file1.name);
  14301. ASSERT_EQ("A.txt", file1.filename);
  14302. ASSERT_EQ("text/plain", file1.content_type);
  14303. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14304. const auto &file2 = req.form.get_file("file2");
  14305. ASSERT_EQ("file2", file2.name);
  14306. ASSERT_EQ("a.html", file2.filename);
  14307. ASSERT_EQ("text/html", file2.content_type);
  14308. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14309. file2.content);
  14310. // Test text field
  14311. const auto &text = req.form.get_field("text");
  14312. ASSERT_EQ("text default", text);
  14313. res.set_content("ok", "text/plain");
  14314. handled = true;
  14315. });
  14316. thread t = thread([&] { svr.listen(HOST, PORT); });
  14317. auto se = detail::scope_exit([&] {
  14318. svr.stop();
  14319. t.join();
  14320. ASSERT_FALSE(svr.is_running());
  14321. ASSERT_TRUE(handled);
  14322. });
  14323. svr.wait_until_ready();
  14324. auto req = "POST /test HTTP/1.1\r\n"
  14325. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14326. "Content-Length: 399\r\n"
  14327. "\r\n"
  14328. "----------\r\n"
  14329. "Content-Disposition: form-data; name=\"text\"\r\n"
  14330. "\r\n"
  14331. "text default\r\n"
  14332. "----------\r\n"
  14333. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14334. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14335. "Content-Type: text/plain\r\n"
  14336. "\r\n"
  14337. "Content of a.txt.\r\n"
  14338. "\r\n"
  14339. "----------\r\n"
  14340. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14341. "\"a.html\"\r\n"
  14342. "Content-Type: text/html\r\n"
  14343. "\r\n"
  14344. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14345. "\r\n"
  14346. "------------\r\n";
  14347. ASSERT_TRUE(send_request(1, req));
  14348. }
  14349. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14350. auto handled = false;
  14351. Server svr;
  14352. svr.Post("/test", [&](const Request &req, Response &res) {
  14353. // Case-insensitive "utf-8''" prefix with a long value
  14354. const auto &file = req.form.get_file("file1");
  14355. ASSERT_EQ("file1", file.name);
  14356. // 8000 chars exercises both the Content-Disposition parser and the
  14357. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14358. // Prior to the fix, std::regex_match on this header would cause O(N)
  14359. // stack recursion in libstdc++, leading to SIGSEGV.
  14360. std::string expected_filename(8000, 'A');
  14361. ASSERT_EQ(expected_filename, file.filename);
  14362. res.set_content("ok", "text/plain");
  14363. handled = true;
  14364. });
  14365. thread t = thread([&] { svr.listen(HOST, PORT); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. ASSERT_FALSE(svr.is_running());
  14370. ASSERT_TRUE(handled);
  14371. });
  14372. svr.wait_until_ready();
  14373. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14374. // Regression test for GHSA-qq6v-r583-3h69
  14375. std::string long_filename(8000, 'A');
  14376. std::string body = "----------\r\n"
  14377. "Content-Disposition: form-data; name=\"file1\"; "
  14378. "filename*=\"Utf-8''" +
  14379. long_filename +
  14380. "\"\r\n"
  14381. "\r\n"
  14382. "hello\r\n"
  14383. "------------\r\n";
  14384. auto req = "POST /test HTTP/1.1\r\n"
  14385. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14386. "Content-Length: " +
  14387. std::to_string(body.size()) + "\r\n\r\n" + body;
  14388. ASSERT_TRUE(send_request(1, req));
  14389. }
  14390. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14391. auto handled = false;
  14392. Server svr;
  14393. svr.Post("/test", [&](const Request &req, Response &) {
  14394. ASSERT_EQ(2u, req.form.fields.size());
  14395. const auto &text1 = req.form.get_field("text1");
  14396. ASSERT_EQ("text1", text1);
  14397. const auto &text2 = req.form.get_field("text2");
  14398. ASSERT_EQ("text2", text2);
  14399. handled = true;
  14400. });
  14401. thread t = thread([&] { svr.listen(HOST, PORT); });
  14402. auto se = detail::scope_exit([&] {
  14403. svr.stop();
  14404. t.join();
  14405. ASSERT_FALSE(svr.is_running());
  14406. ASSERT_TRUE(handled);
  14407. });
  14408. svr.wait_until_ready();
  14409. auto req = "POST /test HTTP/1.1\r\n"
  14410. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14411. "Content-Length: 146\r\n"
  14412. "\r\n----------\r\n"
  14413. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14414. "\r\n"
  14415. "text1"
  14416. "\r\n----------\r\n"
  14417. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14418. "\r\n"
  14419. "text2"
  14420. "\r\n------------";
  14421. std::string response;
  14422. ASSERT_TRUE(send_request(1, req, &response));
  14423. ASSERT_EQ("200", response.substr(9, 3));
  14424. }
  14425. TEST(MultipartFormDataTest, ContentLength) {
  14426. auto handled = false;
  14427. Server svr;
  14428. svr.Post("/test", [&](const Request &req, Response &) {
  14429. ASSERT_EQ(2u, req.form.fields.size());
  14430. const auto &text1 = req.form.get_field("text1");
  14431. ASSERT_EQ("text1", text1);
  14432. const auto &text2 = req.form.get_field("text2");
  14433. ASSERT_EQ("text2", text2);
  14434. handled = true;
  14435. });
  14436. thread t = thread([&] { svr.listen(HOST, PORT); });
  14437. auto se = detail::scope_exit([&] {
  14438. svr.stop();
  14439. t.join();
  14440. ASSERT_FALSE(svr.is_running());
  14441. ASSERT_TRUE(handled);
  14442. });
  14443. svr.wait_until_ready();
  14444. auto req = "POST /test HTTP/1.1\r\n"
  14445. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14446. "Content-Length: 167\r\n"
  14447. "\r\n----------\r\n"
  14448. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14449. "Content-Length: 5\r\n"
  14450. "\r\n"
  14451. "text1"
  14452. "\r\n----------\r\n"
  14453. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14454. "\r\n"
  14455. "text2"
  14456. "\r\n------------\r\n";
  14457. std::string response;
  14458. ASSERT_TRUE(send_request(1, req, &response));
  14459. ASSERT_EQ("200", response.substr(9, 3));
  14460. }
  14461. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14462. auto handled = false;
  14463. Server svr;
  14464. svr.Post("/test", [&](const Request &req, Response &) {
  14465. ASSERT_EQ(2u, req.form.fields.size());
  14466. const auto &text1 = req.form.get_field("text1");
  14467. ASSERT_EQ("text1", text1);
  14468. // TODO: Add header access for text fields if needed
  14469. const auto &text2 = req.form.get_field("text2");
  14470. ASSERT_EQ("text2", text2);
  14471. // TODO: Header access for text fields needs to be implemented
  14472. // auto &headers = it->second.headers;
  14473. // ASSERT_EQ(3U, headers.size());
  14474. // auto custom_header = headers.find("x-whatever");
  14475. // ASSERT_TRUE(custom_header != headers.end());
  14476. // ASSERT_NE("customvalue", custom_header->second);
  14477. // ASSERT_EQ("CustomValue", custom_header->second);
  14478. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14479. handled = true;
  14480. });
  14481. thread t = thread([&] { svr.listen(HOST, PORT); });
  14482. auto se = detail::scope_exit([&] {
  14483. svr.stop();
  14484. t.join();
  14485. ASSERT_FALSE(svr.is_running());
  14486. ASSERT_TRUE(handled);
  14487. });
  14488. svr.wait_until_ready();
  14489. auto req = "POST /test HTTP/1.1\r\n"
  14490. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14491. "Content-Length: 232\r\n"
  14492. "\r\n----------\r\n"
  14493. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14494. "Content-Length: 5\r\n"
  14495. "X-Test: 1\r\n"
  14496. "\r\n"
  14497. "text1"
  14498. "\r\n----------\r\n"
  14499. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14500. "Content-Type: text/plain\r\n"
  14501. "X-Whatever: CustomValue\r\n"
  14502. "\r\n"
  14503. "text2"
  14504. "\r\n------------\r\n"
  14505. "That should be disregarded. Not even read";
  14506. std::string response;
  14507. ASSERT_TRUE(send_request(1, req, &response));
  14508. ASSERT_EQ("200", response.substr(9, 3));
  14509. }
  14510. TEST(MultipartFormDataTest, LargeHeader) {
  14511. auto handled = false;
  14512. Server svr;
  14513. svr.Post("/test", [&](const Request &req, Response &) {
  14514. ASSERT_EQ(1u, req.form.fields.size());
  14515. const auto &text = req.form.get_field("name1");
  14516. ASSERT_EQ("text1", text);
  14517. handled = true;
  14518. });
  14519. thread t = thread([&] { svr.listen(HOST, PORT); });
  14520. auto se = detail::scope_exit([&] {
  14521. svr.stop();
  14522. t.join();
  14523. ASSERT_FALSE(svr.is_running());
  14524. ASSERT_TRUE(handled);
  14525. });
  14526. svr.wait_until_ready();
  14527. auto boundary = std::string("cpp-httplib-multipart-data");
  14528. std::string content = "--" + boundary +
  14529. "\r\n"
  14530. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14531. "\r\n"
  14532. "text1\r\n"
  14533. "--" +
  14534. boundary + "--\r\n";
  14535. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14536. "Content-Type: multipart/form-data;boundary=" +
  14537. boundary +
  14538. "\r\n"
  14539. "Content-Length: " +
  14540. std::to_string(content.size()) +
  14541. "\r\n"
  14542. "Dummy-Header: ";
  14543. std::string header_suffix = "\r\n"
  14544. "\r\n";
  14545. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14546. size_t header_dummy_size =
  14547. read_buff_size -
  14548. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14549. auto header_dummy = std::string(header_dummy_size, '@');
  14550. auto req = header_prefix + header_dummy + header_suffix + content;
  14551. std::string response;
  14552. ASSERT_TRUE(send_request(1, req, &response));
  14553. ASSERT_EQ("200", response.substr(9, 3));
  14554. }
  14555. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14556. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14557. // (not chunked Transfer-Encoding) after the streaming refactor.
  14558. auto handled = false;
  14559. Server svr;
  14560. svr.Post("/upload", [&](const Request &req, Response &res) {
  14561. auto cl_it = req.headers.find("Content-Length");
  14562. EXPECT_TRUE(cl_it != req.headers.end());
  14563. auto te_it = req.headers.find("Transfer-Encoding");
  14564. EXPECT_TRUE(te_it == req.headers.end());
  14565. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14566. res.set_content("ok", "text/plain");
  14567. handled = true;
  14568. });
  14569. auto port = svr.bind_to_any_port(HOST);
  14570. auto t = thread([&] { svr.listen_after_bind(); });
  14571. auto se = detail::scope_exit([&] {
  14572. svr.stop();
  14573. t.join();
  14574. ASSERT_FALSE(svr.is_running());
  14575. ASSERT_TRUE(handled);
  14576. });
  14577. svr.wait_until_ready();
  14578. UploadFormDataItems items = {
  14579. {"field1", "hello", "", "text/plain"},
  14580. {"file1", "world", "test.txt", "application/octet-stream"},
  14581. };
  14582. Client cli(HOST, port);
  14583. auto res = cli.Post("/upload", {}, items);
  14584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14585. EXPECT_EQ(StatusCode::OK_200, res->status);
  14586. }
  14587. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14588. // Verify that make_multipart_content_provider coalesces many small segments
  14589. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14590. constexpr size_t kItemCount = 1000;
  14591. UploadFormDataItems items;
  14592. items.reserve(kItemCount);
  14593. for (size_t i = 0; i < kItemCount; i++) {
  14594. items.push_back(
  14595. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14596. }
  14597. const std::string boundary = "----test-boundary";
  14598. auto content_length = detail::get_multipart_content_length(items, boundary);
  14599. auto provider = detail::make_multipart_content_provider(items, boundary);
  14600. // Drive the provider the same way write_content_with_progress does
  14601. size_t write_count = 0;
  14602. size_t total_bytes = 0;
  14603. DataSink sink;
  14604. size_t offset = 0;
  14605. sink.write = [&](const char *d, size_t l) -> bool {
  14606. (void)d;
  14607. write_count++;
  14608. total_bytes += l;
  14609. offset += l;
  14610. return true;
  14611. };
  14612. sink.is_writable = []() -> bool { return true; };
  14613. while (offset < content_length) {
  14614. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14615. }
  14616. EXPECT_EQ(content_length, total_bytes);
  14617. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14618. // With buffering into 64KB blocks, write_count should be much smaller.
  14619. auto segment_count = 3 * kItemCount + 1;
  14620. EXPECT_LT(write_count, segment_count / 10);
  14621. }
  14622. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14623. // Integration test: send many UploadFormDataItems and verify the server
  14624. // receives all of them correctly (#2410).
  14625. constexpr size_t kItemCount = 500;
  14626. auto handled = false;
  14627. Server svr;
  14628. svr.Post("/upload", [&](const Request &req, Response &res) {
  14629. EXPECT_EQ(kItemCount, req.form.fields.size());
  14630. for (size_t i = 0; i < kItemCount; i++) {
  14631. auto key = "field" + std::to_string(i);
  14632. auto val = "value" + std::to_string(i);
  14633. auto it = req.form.fields.find(key);
  14634. if (it != req.form.fields.end()) {
  14635. EXPECT_EQ(val, it->second.content);
  14636. } else {
  14637. ADD_FAILURE() << "Missing field: " << key;
  14638. }
  14639. }
  14640. res.set_content("ok", "text/plain");
  14641. handled = true;
  14642. });
  14643. auto port = svr.bind_to_any_port(HOST);
  14644. auto t = thread([&] { svr.listen_after_bind(); });
  14645. auto se = detail::scope_exit([&] {
  14646. svr.stop();
  14647. t.join();
  14648. ASSERT_FALSE(svr.is_running());
  14649. ASSERT_TRUE(handled);
  14650. });
  14651. svr.wait_until_ready();
  14652. UploadFormDataItems items;
  14653. items.reserve(kItemCount);
  14654. for (size_t i = 0; i < kItemCount; i++) {
  14655. items.push_back(
  14656. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14657. }
  14658. Client cli(HOST, port);
  14659. auto res = cli.Post("/upload", items);
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ(StatusCode::OK_200, res->status);
  14662. }
  14663. TEST(MultipartFormDataTest, MakeFileProvider) {
  14664. // Verify make_file_provider sends a file's contents correctly.
  14665. const std::string file_content(4096, 'Z');
  14666. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14667. {
  14668. std::ofstream ofs(tmp_path, std::ios::binary);
  14669. ofs.write(file_content.data(),
  14670. static_cast<std::streamsize>(file_content.size()));
  14671. }
  14672. auto handled = false;
  14673. Server svr;
  14674. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14675. const ContentReader &content_reader) {
  14676. ASSERT_TRUE(req.is_multipart_form_data());
  14677. std::vector<FormData> items;
  14678. content_reader(
  14679. [&](const FormData &file) {
  14680. items.push_back(file);
  14681. return true;
  14682. },
  14683. [&](const char *data, size_t data_length) {
  14684. items.back().content.append(data, data_length);
  14685. return true;
  14686. });
  14687. ASSERT_EQ(1u, items.size());
  14688. EXPECT_EQ("myfile", items[0].name);
  14689. EXPECT_EQ("data.bin", items[0].filename);
  14690. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14691. EXPECT_EQ(file_content, items[0].content);
  14692. handled = true;
  14693. });
  14694. auto port = svr.bind_to_any_port(HOST);
  14695. auto t = thread([&] { svr.listen_after_bind(); });
  14696. auto se = detail::scope_exit([&] {
  14697. svr.stop();
  14698. t.join();
  14699. ASSERT_FALSE(svr.is_running());
  14700. ASSERT_TRUE(handled);
  14701. std::remove(tmp_path.c_str());
  14702. });
  14703. svr.wait_until_ready();
  14704. FormDataProviderItems providers;
  14705. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14706. "application/octet-stream"));
  14707. Client cli(HOST, port);
  14708. auto res = cli.Post("/upload", {}, {}, providers);
  14709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14710. EXPECT_EQ(StatusCode::OK_200, res->status);
  14711. }
  14712. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14713. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14714. // (100) headers is rejected with a 400 Bad Request response.
  14715. Server svr;
  14716. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14717. res.set_content("ok", "text/plain");
  14718. });
  14719. thread t = thread([&] { svr.listen(HOST, PORT); });
  14720. auto se = detail::scope_exit([&] {
  14721. svr.stop();
  14722. t.join();
  14723. ASSERT_FALSE(svr.is_running());
  14724. });
  14725. svr.wait_until_ready();
  14726. // Build a multipart part with 101 custom headers (exceeding
  14727. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14728. std::stringstream body;
  14729. body << "--simpleboundary\r\n"
  14730. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14731. for (int i = 0; i < 101; i++) {
  14732. body << "X-Custom-Header-" << i << ": value\r\n";
  14733. }
  14734. body << "\r\n"
  14735. << "value1\r\n"
  14736. << "--simpleboundary--\r\n";
  14737. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14738. Client cli(HOST, PORT);
  14739. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14741. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14742. }
  14743. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14744. // A body that never contains the declared boundary must not be accumulated
  14745. // while the parser waits for it. Buffering it would also make every read
  14746. // rescan everything seen so far, which is quadratic in the body size.
  14747. Server svr;
  14748. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14749. res.set_content("ok", "text/plain");
  14750. });
  14751. auto port = svr.bind_to_any_port(HOST);
  14752. thread t = thread([&] { svr.listen_after_bind(); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. ASSERT_FALSE(svr.is_running());
  14757. });
  14758. svr.wait_until_ready();
  14759. Client cli(HOST, port);
  14760. cli.set_read_timeout(60, 0);
  14761. cli.set_write_timeout(60, 0);
  14762. // '-' is the worst case: it matches the first character of the boundary, so
  14763. // every position has to be checked against it.
  14764. auto post_dashes = [&](size_t size) {
  14765. const std::string body(size, '-');
  14766. auto start = std::chrono::steady_clock::now();
  14767. auto res =
  14768. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14769. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14770. std::chrono::steady_clock::now() - start)
  14771. .count();
  14772. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14773. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14774. return ms;
  14775. };
  14776. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14777. // Windows.
  14778. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14779. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14780. // Comparing the two sizes rather than checking an absolute duration keeps
  14781. // this meaningful across build types and CI load, both of which move the
  14782. // absolute numbers by more than an order of magnitude. Four times the bytes
  14783. // costs about four times the time when parsing is linear, and about sixteen
  14784. // times when the body is buffered and rescanned.
  14785. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14786. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14787. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14788. << "ms, which suggests the body is being buffered and rescanned";
  14789. }
  14790. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14791. // A boundary can only be followed by CRLF or by "--", so anything else is
  14792. // malformed no matter what comes next. The parser must say so right away
  14793. // instead of buffering the rest of the declared body.
  14794. Server svr;
  14795. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14796. res.set_content("ok", "text/plain");
  14797. });
  14798. auto port = svr.bind_to_any_port(HOST);
  14799. thread t = thread([&] { svr.listen_after_bind(); });
  14800. auto se = detail::scope_exit([&] {
  14801. svr.stop();
  14802. t.join();
  14803. ASSERT_FALSE(svr.is_running());
  14804. });
  14805. svr.wait_until_ready();
  14806. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14807. // buffers instead of failing would still be waiting for the remaining bytes.
  14808. const std::string body = "--zzzz\r\n"
  14809. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14810. "\r\n"
  14811. "text1"
  14812. "\r\n--zzzzXX";
  14813. const std::string req = "POST /post HTTP/1.1\r\n"
  14814. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14815. "Content-Length: 1048576\r\n"
  14816. "\r\n" +
  14817. body;
  14818. std::string response;
  14819. ASSERT_TRUE(send_request(3, req, &response, port));
  14820. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14821. EXPECT_EQ("400", response.substr(9, 3));
  14822. }
  14823. // Posts a multipart body split into two writes, so that the server sees the
  14824. // split at whatever offset the caller chose, and expects the single "text1"
  14825. // field to come through.
  14826. static void expect_split_multipart_ok(const std::string &body1,
  14827. const std::string &body2) {
  14828. auto handled = false;
  14829. Server svr;
  14830. svr.Post("/post", [&](const Request &req, Response &) {
  14831. EXPECT_EQ(1u, req.form.fields.size());
  14832. EXPECT_EQ("text1", req.form.get_field("text1"));
  14833. handled = true;
  14834. });
  14835. auto port = svr.bind_to_any_port(HOST);
  14836. thread t = thread([&] { svr.listen_after_bind(); });
  14837. auto se = detail::scope_exit([&] {
  14838. svr.stop();
  14839. t.join();
  14840. ASSERT_FALSE(svr.is_running());
  14841. ASSERT_TRUE(handled);
  14842. });
  14843. svr.wait_until_ready();
  14844. // "Connection: close" makes the server close once it has answered, so the
  14845. // response drain ends immediately instead of idling until the read timeout.
  14846. const std::string head =
  14847. "POST /post HTTP/1.1\r\n"
  14848. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14849. "Connection: close\r\n"
  14850. "Content-Length: " +
  14851. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14852. std::string response;
  14853. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14854. ASSERT_GE(response.size(), 12u) << "no response";
  14855. EXPECT_EQ("200", response.substr(9, 3));
  14856. }
  14857. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14858. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14859. // ignored, including when it does not arrive in the same read as the
  14860. // close-delimiter itself.
  14861. expect_split_multipart_ok("--zzzz\r\n"
  14862. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14863. "\r\n"
  14864. "text1"
  14865. "\r\n--zzzz--",
  14866. "\r\nthis epilogue must be ignored\r\n");
  14867. }
  14868. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14869. // The initial boundary may be preceded by a preamble of any length and may
  14870. // straddle a read boundary. Discarding data while waiting for it must not
  14871. // throw away a partial boundary sitting at the end of the buffer.
  14872. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14873. "zz\r\n"
  14874. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14875. "\r\n"
  14876. "text1"
  14877. "\r\n--zzzz--\r\n");
  14878. }
  14879. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14880. // The received boundary was only checked for being non-empty, so it could be
  14881. // as long as a header is allowed to be. The parser scans the body for
  14882. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14883. // costs a nearly full comparison at nearly every position, making the
  14884. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14885. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14886. Server svr;
  14887. svr.Post("/post", [](const Request &req, Response &res) {
  14888. EXPECT_EQ(1u, req.form.fields.size());
  14889. EXPECT_EQ("text1", req.form.get_field("text1"));
  14890. res.set_content("ok", "text/plain");
  14891. });
  14892. auto port = svr.bind_to_any_port(HOST);
  14893. thread t = thread([&] { svr.listen_after_bind(); });
  14894. auto se = detail::scope_exit([&] {
  14895. svr.stop();
  14896. t.join();
  14897. ASSERT_FALSE(svr.is_running());
  14898. });
  14899. svr.wait_until_ready();
  14900. Client cli(HOST, port);
  14901. auto post_with_boundary_of_length = [&](size_t len) {
  14902. const std::string boundary(len, 'a');
  14903. const std::string body =
  14904. "--" + boundary +
  14905. "\r\n"
  14906. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14907. "\r\n"
  14908. "text1"
  14909. "\r\n--" +
  14910. boundary + "--\r\n";
  14911. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14912. };
  14913. auto res = post_with_boundary_of_length(70);
  14914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14915. EXPECT_EQ(StatusCode::OK_200, res->status);
  14916. res = post_with_boundary_of_length(71);
  14917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14918. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14919. }
  14920. TEST(MakeFileBodyTest, Basic) {
  14921. const std::string file_content(4096, 'Z');
  14922. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14923. {
  14924. std::ofstream ofs(tmp_path, std::ios::binary);
  14925. ofs.write(file_content.data(),
  14926. static_cast<std::streamsize>(file_content.size()));
  14927. }
  14928. auto handled = false;
  14929. Server svr;
  14930. svr.Post("/upload", [&](const Request &req, Response &res) {
  14931. EXPECT_EQ(file_content, req.body);
  14932. handled = true;
  14933. res.status = StatusCode::OK_200;
  14934. });
  14935. auto port = svr.bind_to_any_port(HOST);
  14936. auto t = thread([&] { svr.listen_after_bind(); });
  14937. auto se = detail::scope_exit([&] {
  14938. svr.stop();
  14939. t.join();
  14940. ASSERT_FALSE(svr.is_running());
  14941. ASSERT_TRUE(handled);
  14942. std::remove(tmp_path.c_str());
  14943. });
  14944. svr.wait_until_ready();
  14945. auto fb = make_file_body(tmp_path);
  14946. ASSERT_GT(fb.first, 0u);
  14947. Client cli(HOST, port);
  14948. auto res =
  14949. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14951. EXPECT_EQ(StatusCode::OK_200, res->status);
  14952. }
  14953. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14954. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14955. {
  14956. std::ofstream ofs(path, std::ios::binary);
  14957. const std::string content(100, 'A');
  14958. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14959. }
  14960. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14961. auto body = make_file_body(path);
  14962. ASSERT_EQ(100u, body.first);
  14963. ASSERT_TRUE(static_cast<bool>(body.second));
  14964. // Rewritten shorter after its length was measured - and, on a server, after
  14965. // that length has already gone out as Content-Length.
  14966. {
  14967. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14968. const std::string content(10, 'A');
  14969. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14970. }
  14971. std::string written;
  14972. DataSink sink;
  14973. sink.write = [&](const char *d, size_t l) {
  14974. written.append(d, l);
  14975. return true;
  14976. };
  14977. // The provider has to report failure. write_content_with_progress() advances
  14978. // its offset only by what was written, so a provider that returns true
  14979. // without completing the length it promised is called again straight away,
  14980. // and again.
  14981. EXPECT_FALSE(body.second(0, body.first, sink));
  14982. EXPECT_EQ(std::string(10, 'A'), written);
  14983. }
  14984. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14985. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14986. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14987. {
  14988. std::ofstream ofs(path, std::ios::binary);
  14989. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14990. }
  14991. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14992. auto body = make_file_body(path);
  14993. ASSERT_EQ(content.size(), body.first);
  14994. ASSERT_TRUE(static_cast<bool>(body.second));
  14995. std::string written;
  14996. DataSink sink;
  14997. sink.write = [&](const char *d, size_t l) {
  14998. written.append(d, l);
  14999. return true;
  15000. };
  15001. EXPECT_TRUE(body.second(0, body.first, sink));
  15002. EXPECT_EQ(content, written);
  15003. }
  15004. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15005. static constexpr unsigned int number_of_tasks{1000000};
  15006. std::atomic_uint count{0};
  15007. std::unique_ptr<TaskQueue> task_queue{
  15008. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15009. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15010. auto queued = task_queue->enqueue(
  15011. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15012. EXPECT_TRUE(queued);
  15013. }
  15014. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15015. task_queue->shutdown();
  15016. #else
  15017. EXPECT_NO_THROW(task_queue->shutdown());
  15018. #endif
  15019. EXPECT_EQ(number_of_tasks, count.load());
  15020. }
  15021. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15022. static constexpr unsigned int number_of_tasks{1000000};
  15023. static constexpr unsigned int qlimit{2};
  15024. unsigned int queued_count{0};
  15025. std::atomic_uint count{0};
  15026. std::unique_ptr<TaskQueue> task_queue{
  15027. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15028. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15029. if (task_queue->enqueue(
  15030. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15031. queued_count++;
  15032. }
  15033. }
  15034. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15035. task_queue->shutdown();
  15036. #else
  15037. EXPECT_NO_THROW(task_queue->shutdown());
  15038. #endif
  15039. EXPECT_EQ(queued_count, count.load());
  15040. EXPECT_TRUE(queued_count <= number_of_tasks);
  15041. EXPECT_TRUE(queued_count >= qlimit);
  15042. }
  15043. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15044. // Use a short idle timeout so a dynamic thread spawns, times out and
  15045. // exits during the test, and the pool keeps working afterwards.
  15046. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15047. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15048. /*idle_timeout_sec=*/1}};
  15049. std::atomic_uint count{0};
  15050. std::condition_variable cv;
  15051. std::mutex mtx;
  15052. bool release = false;
  15053. // Block the base thread so the second task spawns a dynamic thread.
  15054. EXPECT_TRUE(task_queue->enqueue([&] {
  15055. std::unique_lock<std::mutex> lock(mtx);
  15056. while (!release) {
  15057. cv.wait(lock);
  15058. }
  15059. count++;
  15060. }));
  15061. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15062. // Let the dynamic thread finish its task and exceed the idle timeout.
  15063. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15064. {
  15065. std::unique_lock<std::mutex> lock(mtx);
  15066. release = true;
  15067. }
  15068. cv.notify_all();
  15069. // The pool must still accept and run tasks after the dynamic thread exited.
  15070. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15071. task_queue->shutdown();
  15072. EXPECT_EQ(3u, count.load());
  15073. }
  15074. TEST(TaskQueueTest, MaxQueuedRequests) {
  15075. static constexpr unsigned int qlimit{3};
  15076. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15077. std::condition_variable sem_cv;
  15078. std::mutex sem_mtx;
  15079. int credits = 0;
  15080. bool queued;
  15081. /* Fill up the queue with tasks that will block until we give them credits to
  15082. * complete. */
  15083. for (unsigned int n = 0; n <= qlimit;) {
  15084. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15085. std::unique_lock<std::mutex> lock(sem_mtx);
  15086. while (credits <= 0) {
  15087. sem_cv.wait(lock);
  15088. }
  15089. /* Consume the credit and signal the test code if they are all gone. */
  15090. if (--credits == 0) { sem_cv.notify_one(); }
  15091. });
  15092. if (n < qlimit) {
  15093. /* The first qlimit enqueues must succeed. */
  15094. EXPECT_TRUE(queued);
  15095. } else {
  15096. /* The last one will succeed only when the worker thread
  15097. * starts and dequeues the first blocking task. Although
  15098. * not necessary for the correctness of this test, we sleep for
  15099. * a short while to avoid busy waiting. */
  15100. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15101. }
  15102. if (queued) { n++; }
  15103. }
  15104. /* Further enqueues must fail since the queue is full. */
  15105. for (auto i = 0; i < 4; i++) {
  15106. queued = task_queue->enqueue([] {});
  15107. EXPECT_FALSE(queued);
  15108. }
  15109. /* Give the credits to allow the previous tasks to complete. */
  15110. {
  15111. std::unique_lock<std::mutex> lock(sem_mtx);
  15112. credits += qlimit + 1;
  15113. }
  15114. sem_cv.notify_all();
  15115. /* Wait for all the credits to be consumed. */
  15116. {
  15117. std::unique_lock<std::mutex> lock(sem_mtx);
  15118. while (credits > 0) {
  15119. sem_cv.wait(lock);
  15120. }
  15121. }
  15122. /* Check that we are able again to enqueue at least qlimit tasks. */
  15123. for (unsigned int i = 0; i < qlimit; i++) {
  15124. queued = task_queue->enqueue([] {});
  15125. EXPECT_TRUE(queued);
  15126. }
  15127. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15128. task_queue->shutdown();
  15129. #else
  15130. EXPECT_NO_THROW(task_queue->shutdown());
  15131. #endif
  15132. }
  15133. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15134. Server svr;
  15135. std::string method;
  15136. std::string body;
  15137. auto has_content_length = false;
  15138. auto has_transfer_encoding = false;
  15139. std::atomic<int> bad_requests{0};
  15140. // Leftover body bytes get parsed as a malformed request and answered with
  15141. // 400
  15142. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15143. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15144. });
  15145. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15146. res.set_redirect("/down", StatusCode::SeeOther_303);
  15147. });
  15148. svr.Get("/down", [&](const Request &req, Response &res) {
  15149. method = req.method;
  15150. body = req.body;
  15151. has_content_length = req.has_header("Content-Length");
  15152. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15153. res.set_content("ok", "text/plain");
  15154. });
  15155. auto port = svr.bind_to_any_port(HOST);
  15156. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. thread.join();
  15160. ASSERT_FALSE(svr.is_running());
  15161. });
  15162. svr.wait_until_ready();
  15163. const std::string payload = "SECRET-BODY";
  15164. auto check = [&](Client &cli, const Result &res) {
  15165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15166. EXPECT_EQ(StatusCode::OK_200, res->status);
  15167. EXPECT_EQ("ok", res->body);
  15168. EXPECT_EQ("GET", method);
  15169. EXPECT_TRUE(body.empty());
  15170. EXPECT_FALSE(has_content_length);
  15171. EXPECT_FALSE(has_transfer_encoding);
  15172. // Nothing of the original body may be left on the connection
  15173. auto res2 = cli.Get("/down");
  15174. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15175. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15176. EXPECT_EQ("ok", res2->body);
  15177. EXPECT_EQ(0, bad_requests);
  15178. };
  15179. // With content length
  15180. {
  15181. Client cli(HOST, port);
  15182. cli.set_keep_alive(true);
  15183. cli.set_follow_location(true);
  15184. auto res = cli.Post(
  15185. "/up", payload.size(),
  15186. [&](size_t offset, size_t length, DataSink &sink) {
  15187. return sink.write(payload.data() + offset, length);
  15188. },
  15189. "text/plain");
  15190. check(cli, res);
  15191. }
  15192. // Without content length (chunked)
  15193. {
  15194. Client cli(HOST, port);
  15195. cli.set_keep_alive(true);
  15196. cli.set_follow_location(true);
  15197. auto res = cli.Post(
  15198. "/up",
  15199. [&](size_t /*offset*/, DataSink &sink) {
  15200. sink.write(payload.data(), payload.size());
  15201. sink.done();
  15202. return true;
  15203. },
  15204. "text/plain");
  15205. check(cli, res);
  15206. }
  15207. }
  15208. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15209. Server svr;
  15210. std::string target;
  15211. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15212. // Echo the still-encoded name back in the Location
  15213. const std::string prefix = "/start/";
  15214. res.status = StatusCode::Found_302;
  15215. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15216. });
  15217. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15218. target = req.target;
  15219. res.set_content("ok", "text/plain");
  15220. });
  15221. auto port = svr.bind_to_any_port(HOST);
  15222. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15223. auto se = detail::scope_exit([&] {
  15224. svr.stop();
  15225. thread.join();
  15226. ASSERT_FALSE(svr.is_running());
  15227. });
  15228. svr.wait_until_ready();
  15229. // Decoding the Location path would turn the first four into a path
  15230. // separator, a query delimiter, a fragment delimiter and a different
  15231. // percent-encoded octet. The rest must keep reaching the server as they are.
  15232. const std::vector<std::string> names = {
  15233. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15234. };
  15235. for (auto path_encode : {true, false}) {
  15236. Client cli(HOST, port);
  15237. cli.set_follow_location(true);
  15238. cli.set_path_encode(path_encode);
  15239. for (const auto &name : names) {
  15240. target.clear();
  15241. auto res = cli.Get("/start/" + name);
  15242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15243. EXPECT_EQ(StatusCode::OK_200, res->status);
  15244. EXPECT_EQ("/dest/" + name, target);
  15245. }
  15246. }
  15247. }
  15248. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15249. Server svr;
  15250. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15251. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15252. });
  15253. svr.Get("/hello", [](const Request &req, Response &res) {
  15254. res.set_content(req.get_param_value("key"), "text/plain");
  15255. });
  15256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15257. auto se = detail::scope_exit([&] {
  15258. svr.stop();
  15259. thread.join();
  15260. ASSERT_FALSE(svr.is_running());
  15261. });
  15262. svr.wait_until_ready();
  15263. {
  15264. Client cli(HOST, PORT);
  15265. cli.set_follow_location(true);
  15266. auto res = cli.Get("/");
  15267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15268. EXPECT_EQ(StatusCode::OK_200, res->status);
  15269. EXPECT_EQ("val&key2=val2", res->body);
  15270. }
  15271. }
  15272. #endif
  15273. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15274. Server svr;
  15275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15276. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15277. });
  15278. svr.Get("/hello", [](const Request &req, Response &res) {
  15279. res.set_content(req.get_param_value("key"), "text/plain");
  15280. });
  15281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15282. auto se = detail::scope_exit([&] {
  15283. svr.stop();
  15284. thread.join();
  15285. ASSERT_FALSE(svr.is_running());
  15286. });
  15287. svr.wait_until_ready();
  15288. {
  15289. Client cli(HOST, PORT);
  15290. cli.set_follow_location(true);
  15291. auto res = cli.Get("/");
  15292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15293. EXPECT_EQ(StatusCode::OK_200, res->status);
  15294. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15295. }
  15296. }
  15297. TEST(RedirectTest, RedirectWithPlusInPath) {
  15298. Server svr;
  15299. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15300. res.set_redirect("/a+b");
  15301. });
  15302. // Route pattern uses regex; escape + as \\+
  15303. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15304. res.set_content(req.path, "text/plain");
  15305. });
  15306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15307. auto se = detail::scope_exit([&] {
  15308. svr.stop();
  15309. thread.join();
  15310. ASSERT_FALSE(svr.is_running());
  15311. });
  15312. svr.wait_until_ready();
  15313. {
  15314. Client cli(HOST, PORT);
  15315. cli.set_follow_location(true);
  15316. auto res = cli.Get("/");
  15317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15318. EXPECT_EQ(StatusCode::OK_200, res->status);
  15319. EXPECT_EQ("/a+b", res->body);
  15320. }
  15321. }
  15322. TEST(RedirectTest, ResolveRelativeLocation) {
  15323. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15324. const std::vector<std::pair<std::string, std::string>> cases = {
  15325. {"g", "/b/c/g"},
  15326. {"./g", "/b/c/g"},
  15327. {"g/", "/b/c/g/"},
  15328. {"?y", "/b/c/d;p?y"},
  15329. {"g?y", "/b/c/g?y"},
  15330. {"#s", "/b/c/d;p?q#s"},
  15331. {"g#s", "/b/c/g#s"},
  15332. {"g?y#s", "/b/c/g?y#s"},
  15333. {";x", "/b/c/;x"},
  15334. {"g;x", "/b/c/g;x"},
  15335. {".", "/b/c/"},
  15336. {"./", "/b/c/"},
  15337. {"..", "/b/"},
  15338. {"../", "/b/"},
  15339. {"../g", "/b/g"},
  15340. {"../..", "/"},
  15341. {"../../", "/"},
  15342. {"../../g", "/g"},
  15343. {"../../../g", "/g"},
  15344. {"g.", "/b/c/g."},
  15345. {".g", "/b/c/.g"},
  15346. {"g..", "/b/c/g.."},
  15347. {"..g", "/b/c/..g"},
  15348. {"./../g", "/b/g"},
  15349. {"./g/.", "/b/c/g/"},
  15350. {"g/./h", "/b/c/g/h"},
  15351. {"g/../h", "/b/c/h"},
  15352. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15353. {"g;x=1/../y", "/b/c/y"},
  15354. {"g?y/./x", "/b/c/g?y/./x"},
  15355. {"g#s/../x", "/b/c/g#s/../x"},
  15356. // Not relative-path references, so left for parse_url.
  15357. {"/g", "/g"},
  15358. {"//g", "//g"},
  15359. {"http://g/x", "http://g/x"},
  15360. {"g:h", "g:h"},
  15361. };
  15362. for (const auto &c : cases) {
  15363. EXPECT_EQ(c.second,
  15364. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15365. << c.first;
  15366. }
  15367. }
  15368. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15369. Server svr;
  15370. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15371. res.set_redirect(req.get_param_value("to"));
  15372. });
  15373. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15374. res.set_content(req.target, "text/plain");
  15375. });
  15376. svr.Get("/other", [](const Request &req, Response &res) {
  15377. res.set_content(req.target, "text/plain");
  15378. });
  15379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15380. auto se = detail::scope_exit([&] {
  15381. svr.stop();
  15382. thread.join();
  15383. ASSERT_FALSE(svr.is_running());
  15384. });
  15385. svr.wait_until_ready();
  15386. const std::vector<std::pair<std::string, std::string>> cases = {
  15387. {"next", "/dir/next"},
  15388. {"./next?x=1", "/dir/next?x=1"},
  15389. {"../other", "/other"},
  15390. };
  15391. for (const auto &c : cases) {
  15392. Client cli(HOST, PORT);
  15393. cli.set_follow_location(true);
  15394. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15395. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15396. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15397. EXPECT_EQ(c.second, res->body) << c.first;
  15398. }
  15399. }
  15400. #ifdef CPPHTTPLIB_SSL_ENABLED
  15401. TEST(RedirectTest, Issue2185_Online) {
  15402. SSLClient client("github.com");
  15403. client.set_follow_location(true);
  15404. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15405. "Coollab-Windows.zip");
  15406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15407. EXPECT_EQ(StatusCode::OK_200, res->status);
  15408. EXPECT_EQ(9920427U, res->body.size());
  15409. }
  15410. #endif
  15411. TEST(VulnerabilityTest, CRLFInjection) {
  15412. Server svr;
  15413. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15414. res.set_content("Hello 1", "text/plain");
  15415. });
  15416. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15417. res.set_content("Hello 2", "text/plain");
  15418. });
  15419. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15420. res.set_content("Hello 3", "text/plain");
  15421. });
  15422. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15423. res.set_content("Hello 4", "text/plain");
  15424. });
  15425. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15426. for (const auto &x : req.headers) {
  15427. auto key = x.first;
  15428. EXPECT_STRNE("evil", key.c_str());
  15429. }
  15430. });
  15431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15432. auto se = detail::scope_exit([&] {
  15433. svr.stop();
  15434. thread.join();
  15435. ASSERT_FALSE(svr.is_running());
  15436. });
  15437. svr.wait_until_ready();
  15438. {
  15439. Client cli(HOST, PORT);
  15440. cli.Post("/test1", "A=B",
  15441. "application/x-www-form-urlencoded\r\nevil: hello1");
  15442. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15443. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15444. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15445. }
  15446. }
  15447. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15448. auto server_thread = std::thread([] {
  15449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15450. default_socket_options(srv);
  15451. sockaddr_in addr{};
  15452. addr.sin_family = AF_INET;
  15453. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15454. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15455. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15456. ::listen(srv, 1);
  15457. sockaddr_in cli_addr{};
  15458. socklen_t cli_len = sizeof(cli_addr);
  15459. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15460. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15461. std::string buf_all;
  15462. char buf[2048];
  15463. ssize_t n;
  15464. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15465. buf_all.append(buf, static_cast<size_t>(n));
  15466. size_t pos;
  15467. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15468. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15469. auto e = request_block.find("\r\n");
  15470. if (e != std::string::npos) {
  15471. auto request_line = request_block.substr(0, e);
  15472. std::string msg =
  15473. "CRLF injection detected in request line: '" + request_line + "'";
  15474. EXPECT_FALSE(true) << msg;
  15475. }
  15476. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15477. ::send(cli,
  15478. #ifdef _WIN32
  15479. static_cast<const char *>(resp.c_str()),
  15480. static_cast<int>(resp.size()),
  15481. #else
  15482. resp.c_str(), resp.size(),
  15483. #endif
  15484. 0);
  15485. buf_all.erase(0, pos + 4);
  15486. }
  15487. }
  15488. detail::close_socket(cli);
  15489. detail::close_socket(srv);
  15490. });
  15491. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15492. auto cli = Client("127.0.0.1", PORT + 1);
  15493. auto headers = Headers{
  15494. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15495. {"Connection", "keep-alive"}};
  15496. auto res = cli.Get("/hi", headers);
  15497. EXPECT_FALSE(res);
  15498. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15499. server_thread.join();
  15500. }
  15501. // A request rejected before any byte reaches the socket must fail right away
  15502. // instead of waiting for a response the server will never send.
  15503. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15504. // The kernel completes the TCP handshake from the listen backlog, so the
  15505. // client connects, but nothing ever reads, responds or closes.
  15506. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15507. default_socket_options(srv);
  15508. sockaddr_in addr{};
  15509. addr.sin_family = AF_INET;
  15510. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15511. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15512. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15513. ASSERT_EQ(0, ::listen(srv, 8));
  15514. auto cli = Client("127.0.0.1", PORT + 1);
  15515. cli.set_read_timeout(10, 0);
  15516. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15517. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15518. std::chrono::steady_clock::now() - start)
  15519. .count();
  15520. };
  15521. {
  15522. Request req;
  15523. req.method = "GE T";
  15524. req.path = "/";
  15525. auto start = std::chrono::steady_clock::now();
  15526. auto res = cli.send(req);
  15527. EXPECT_FALSE(res);
  15528. EXPECT_EQ(Error::Write, res.error());
  15529. EXPECT_LT(elapsed_ms(start), 1000);
  15530. }
  15531. {
  15532. auto start = std::chrono::steady_clock::now();
  15533. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15534. EXPECT_FALSE(res);
  15535. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15536. EXPECT_LT(elapsed_ms(start), 1000);
  15537. }
  15538. EXPECT_FALSE(cli.is_socket_open());
  15539. detail::close_socket(srv);
  15540. }
  15541. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15542. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15543. default_socket_options(srv);
  15544. sockaddr_in addr{};
  15545. addr.sin_family = AF_INET;
  15546. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15547. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15548. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15549. ASSERT_EQ(0, ::listen(srv, 1));
  15550. std::string received;
  15551. auto server_thread = std::thread([&] {
  15552. auto sock = ::accept(srv, nullptr, nullptr);
  15553. if (sock == INVALID_SOCKET) { return; }
  15554. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15555. char buf[2048];
  15556. ssize_t n;
  15557. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15558. received.append(buf, static_cast<size_t>(n));
  15559. }
  15560. detail::close_socket(sock);
  15561. });
  15562. {
  15563. auto cli = Client("127.0.0.1", PORT + 1);
  15564. // "Z" sorts after the default headers, so writing straight to the socket
  15565. // would have sent the request line and those headers before the rejection.
  15566. auto handle =
  15567. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15568. EXPECT_FALSE(handle.is_valid());
  15569. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15570. }
  15571. server_thread.join();
  15572. detail::close_socket(srv);
  15573. EXPECT_TRUE(received.empty()) << received;
  15574. }
  15575. TEST(PathParamsTest, StaticMatch) {
  15576. const auto pattern = "/users/all";
  15577. detail::PathParamsMatcher matcher(pattern);
  15578. Request request;
  15579. request.path = "/users/all";
  15580. ASSERT_TRUE(matcher.match(request));
  15581. std::unordered_map<std::string, std::string> expected_params = {};
  15582. EXPECT_EQ(request.path_params, expected_params);
  15583. }
  15584. TEST(PathParamsTest, StaticMismatch) {
  15585. const auto pattern = "/users/all";
  15586. detail::PathParamsMatcher matcher(pattern);
  15587. Request request;
  15588. request.path = "/users/1";
  15589. ASSERT_FALSE(matcher.match(request));
  15590. }
  15591. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15592. const auto pattern = "/users/:id/subscriptions";
  15593. detail::PathParamsMatcher matcher(pattern);
  15594. Request request;
  15595. request.path = "/users/42/subscriptions";
  15596. ASSERT_TRUE(matcher.match(request));
  15597. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15598. EXPECT_EQ(request.path_params, expected_params);
  15599. }
  15600. TEST(PathParamsTest, SingleParamInTheEnd) {
  15601. const auto pattern = "/users/:id";
  15602. detail::PathParamsMatcher matcher(pattern);
  15603. Request request;
  15604. request.path = "/users/24";
  15605. ASSERT_TRUE(matcher.match(request));
  15606. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15607. EXPECT_EQ(request.path_params, expected_params);
  15608. }
  15609. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15610. const auto pattern = "/users/:id/";
  15611. detail::PathParamsMatcher matcher(pattern);
  15612. Request request;
  15613. request.path = "/users/42/";
  15614. ASSERT_TRUE(matcher.match(request));
  15615. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15616. EXPECT_EQ(request.path_params, expected_params);
  15617. }
  15618. TEST(PathParamsTest, EmptyParam) {
  15619. const auto pattern = "/users/:id/";
  15620. detail::PathParamsMatcher matcher(pattern);
  15621. Request request;
  15622. request.path = "/users//";
  15623. ASSERT_TRUE(matcher.match(request));
  15624. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15625. EXPECT_EQ(request.path_params, expected_params);
  15626. }
  15627. TEST(PathParamsTest, FragmentMismatch) {
  15628. const auto pattern = "/users/:id/";
  15629. detail::PathParamsMatcher matcher(pattern);
  15630. Request request;
  15631. request.path = "/admins/24/";
  15632. ASSERT_FALSE(matcher.match(request));
  15633. }
  15634. TEST(PathParamsTest, ExtraFragments) {
  15635. const auto pattern = "/users/:id";
  15636. detail::PathParamsMatcher matcher(pattern);
  15637. Request request;
  15638. request.path = "/users/42/subscriptions";
  15639. ASSERT_FALSE(matcher.match(request));
  15640. }
  15641. TEST(PathParamsTest, MissingTrailingParam) {
  15642. const auto pattern = "/users/:id";
  15643. detail::PathParamsMatcher matcher(pattern);
  15644. Request request;
  15645. request.path = "/users";
  15646. ASSERT_FALSE(matcher.match(request));
  15647. }
  15648. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15649. const auto pattern = "/users/:id/subscriptions";
  15650. detail::PathParamsMatcher matcher(pattern);
  15651. Request request;
  15652. request.path = "/users/subscriptions";
  15653. ASSERT_FALSE(matcher.match(request));
  15654. }
  15655. TEST(PathParamsTest, MultipleParams) {
  15656. const auto pattern = "/users/:userid/subscriptions/:subid";
  15657. detail::PathParamsMatcher matcher(pattern);
  15658. Request request;
  15659. request.path = "/users/42/subscriptions/2";
  15660. ASSERT_TRUE(matcher.match(request));
  15661. std::unordered_map<std::string, std::string> expected_params = {
  15662. {"userid", "42"}, {"subid", "2"}};
  15663. EXPECT_EQ(request.path_params, expected_params);
  15664. }
  15665. TEST(PathParamsTest, SequenceOfParams) {
  15666. const auto pattern = "/values/:x/:y/:z";
  15667. detail::PathParamsMatcher matcher(pattern);
  15668. Request request;
  15669. request.path = "/values/1/2/3";
  15670. ASSERT_TRUE(matcher.match(request));
  15671. std::unordered_map<std::string, std::string> expected_params = {
  15672. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15673. EXPECT_EQ(request.path_params, expected_params);
  15674. }
  15675. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15676. const auto pattern = "/prefix:suffix";
  15677. detail::PathParamsMatcher matcher(pattern);
  15678. Request request;
  15679. request.path = "/prefix:suffix";
  15680. ASSERT_TRUE(matcher.match(request));
  15681. const std::unordered_map<std::string, std::string> expected_params = {};
  15682. EXPECT_EQ(request.path_params, expected_params);
  15683. }
  15684. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15685. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15686. // calling thread's stack on a long enough path for a quantified pattern;
  15687. // RegexMatcher must refuse to run regex matching on paths beyond
  15688. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15689. detail::RegexMatcher matcher("/files/(.*)");
  15690. Request within_limit;
  15691. within_limit.path = "/files/" + std::string(10, 'A');
  15692. EXPECT_TRUE(matcher.match(within_limit));
  15693. Request over_limit;
  15694. over_limit.path =
  15695. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15696. EXPECT_FALSE(matcher.match(over_limit));
  15697. }
  15698. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15699. Server svr;
  15700. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15701. res.set_content("ok", "text/plain");
  15702. });
  15703. auto port = svr.bind_to_any_port(HOST);
  15704. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15705. auto se = detail::scope_exit([&] {
  15706. svr.stop();
  15707. thread.join();
  15708. ASSERT_FALSE(svr.is_running());
  15709. });
  15710. svr.wait_until_ready();
  15711. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15712. // request URI limit; this used to be able to crash the process.
  15713. std::string path =
  15714. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15715. std::string req = "GET " + path +
  15716. " HTTP/1.1\r\n"
  15717. "Host: " +
  15718. std::string(HOST) + ":" + std::to_string(port) +
  15719. "\r\n"
  15720. "Connection: close\r\n"
  15721. "\r\n";
  15722. std::string response;
  15723. ASSERT_TRUE(send_request(5, req, &response, port));
  15724. EXPECT_NE(std::string::npos, response.find("404"));
  15725. }
  15726. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15727. Server svr;
  15728. auto handler = [](const Request & /*req*/, Response &res) {
  15729. res.set_content("hit", "text/plain");
  15730. };
  15731. // No regex metacharacter, so this one is compared literally
  15732. svr.Get("/literal/route", handler);
  15733. // '.' is a regex metacharacter, so this one must keep regex semantics
  15734. svr.Get("/a.c", handler);
  15735. auto port = svr.bind_to_any_port(HOST);
  15736. std::thread t([&]() { svr.listen_after_bind(); });
  15737. auto se = detail::scope_exit([&] {
  15738. svr.stop();
  15739. t.join();
  15740. ASSERT_FALSE(svr.is_running());
  15741. });
  15742. svr.wait_until_ready();
  15743. Client cli(HOST, port);
  15744. struct {
  15745. const char *path;
  15746. int status;
  15747. } cases[] = {
  15748. {"/literal/route", StatusCode::OK_200},
  15749. {"/literal/routes", StatusCode::NotFound_404},
  15750. {"/literal/rout", StatusCode::NotFound_404},
  15751. {"/abc", StatusCode::OK_200},
  15752. {"/a.c", StatusCode::OK_200},
  15753. };
  15754. for (const auto &x : cases) {
  15755. auto res = cli.Get(x.path);
  15756. ASSERT_TRUE(res) << x.path;
  15757. EXPECT_EQ(x.status, res->status) << x.path;
  15758. }
  15759. }
  15760. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15761. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15762. // from exhausting the stack, so it must only constrain routes that actually
  15763. // run a regular expression. A literal route is matched by comparison and
  15764. // stays usable at any length.
  15765. Server svr;
  15766. const std::string pattern =
  15767. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15768. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15769. res.set_content("hit", "text/plain");
  15770. });
  15771. auto port = svr.bind_to_any_port(HOST);
  15772. std::thread t([&]() { svr.listen_after_bind(); });
  15773. auto se = detail::scope_exit([&] {
  15774. svr.stop();
  15775. t.join();
  15776. ASSERT_FALSE(svr.is_running());
  15777. });
  15778. svr.wait_until_ready();
  15779. Client cli(HOST, port);
  15780. auto res = cli.Get(pattern);
  15781. ASSERT_TRUE(res);
  15782. EXPECT_EQ(StatusCode::OK_200, res->status);
  15783. }
  15784. TEST(ParseUrlTest, VariousPatterns) {
  15785. {
  15786. detail::UrlComponents uc;
  15787. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15788. EXPECT_EQ("http", uc.scheme);
  15789. EXPECT_EQ("example.com", uc.host);
  15790. EXPECT_EQ("8080", uc.port);
  15791. EXPECT_EQ("/path", uc.path);
  15792. EXPECT_EQ("?q=1", uc.query);
  15793. }
  15794. {
  15795. detail::UrlComponents uc;
  15796. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15797. EXPECT_EQ("https", uc.scheme);
  15798. EXPECT_EQ("example.com", uc.host);
  15799. EXPECT_TRUE(uc.port.empty());
  15800. EXPECT_EQ("/path", uc.path);
  15801. }
  15802. {
  15803. detail::UrlComponents uc;
  15804. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15805. EXPECT_EQ("::1", uc.host);
  15806. EXPECT_EQ("8080", uc.port);
  15807. EXPECT_EQ("/path", uc.path);
  15808. }
  15809. {
  15810. detail::UrlComponents uc;
  15811. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15812. }
  15813. {
  15814. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15815. // the path while the connection still targets the bracketed host.
  15816. detail::UrlComponents uc;
  15817. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15818. }
  15819. {
  15820. detail::UrlComponents uc;
  15821. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15822. }
  15823. {
  15824. detail::UrlComponents uc;
  15825. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15826. EXPECT_EQ("::1", uc.host);
  15827. EXPECT_TRUE(uc.port.empty());
  15828. EXPECT_EQ("/path", uc.path);
  15829. }
  15830. {
  15831. detail::UrlComponents uc;
  15832. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15833. EXPECT_TRUE(uc.scheme.empty());
  15834. EXPECT_EQ("example.com", uc.host);
  15835. EXPECT_EQ("/path", uc.path);
  15836. EXPECT_EQ("?q=1", uc.query);
  15837. }
  15838. {
  15839. detail::UrlComponents uc;
  15840. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15841. EXPECT_TRUE(uc.host.empty());
  15842. EXPECT_EQ("/path", uc.path);
  15843. EXPECT_EQ("?q=1", uc.query);
  15844. }
  15845. {
  15846. detail::UrlComponents uc;
  15847. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15848. EXPECT_EQ("example.com", uc.host);
  15849. EXPECT_EQ("8080", uc.port);
  15850. }
  15851. {
  15852. // Unix socket path — must not be parsed as host
  15853. detail::UrlComponents uc;
  15854. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15855. EXPECT_TRUE(uc.host.empty());
  15856. }
  15857. {
  15858. detail::UrlComponents uc;
  15859. ASSERT_TRUE(detail::parse_url("", uc));
  15860. EXPECT_TRUE(uc.host.empty());
  15861. EXPECT_TRUE(uc.path.empty());
  15862. }
  15863. {
  15864. detail::UrlComponents uc;
  15865. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15866. }
  15867. {
  15868. detail::UrlComponents uc;
  15869. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15870. }
  15871. {
  15872. // Accepted by parse_url; callers restrict to http/https
  15873. detail::UrlComponents uc;
  15874. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15875. EXPECT_EQ("ftp", uc.scheme);
  15876. }
  15877. {
  15878. detail::UrlComponents uc;
  15879. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15880. }
  15881. {
  15882. detail::UrlComponents uc;
  15883. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15884. }
  15885. }
  15886. TEST(ParseUrlTest, FragmentHandling) {
  15887. {
  15888. detail::UrlComponents uc;
  15889. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15890. EXPECT_EQ("/path", uc.path);
  15891. EXPECT_TRUE(uc.query.empty());
  15892. }
  15893. {
  15894. detail::UrlComponents uc;
  15895. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15896. EXPECT_TRUE(uc.path.empty());
  15897. EXPECT_TRUE(uc.query.empty());
  15898. }
  15899. }
  15900. TEST(ParseUrlTest, UserinfoHandling) {
  15901. // Userinfo with @ but no colon — host includes @
  15902. detail::UrlComponents uc;
  15903. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15904. EXPECT_EQ("user@host.com", uc.host);
  15905. EXPECT_EQ("/path", uc.path);
  15906. }
  15907. TEST(ParseUrlTest, IPv6EdgeCases) {
  15908. {
  15909. detail::UrlComponents uc;
  15910. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15911. EXPECT_TRUE(uc.scheme.empty());
  15912. EXPECT_EQ("::1", uc.host);
  15913. EXPECT_EQ("8080", uc.port);
  15914. }
  15915. {
  15916. // Zone ID '%25' is not in [a-fA-F0-9:]
  15917. detail::UrlComponents uc;
  15918. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15919. }
  15920. }
  15921. TEST(ParseUrlTest, SchemeEdgeCases) {
  15922. {
  15923. detail::UrlComponents uc;
  15924. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15925. }
  15926. {
  15927. detail::UrlComponents uc;
  15928. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15929. }
  15930. {
  15931. detail::UrlComponents uc;
  15932. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15933. }
  15934. }
  15935. TEST(ParseUrlTest, PortEdgeCases) {
  15936. {
  15937. detail::UrlComponents uc;
  15938. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15939. EXPECT_TRUE(uc.port.empty());
  15940. EXPECT_EQ("/path", uc.path);
  15941. }
  15942. {
  15943. // parse_url accepts any port string; validation is done by parse_port
  15944. detail::UrlComponents uc;
  15945. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15946. EXPECT_EQ("abc", uc.port);
  15947. }
  15948. }
  15949. TEST(ParseUrlTest, WebSocketPatterns) {
  15950. {
  15951. detail::UrlComponents uc;
  15952. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15953. EXPECT_EQ("ws", uc.scheme);
  15954. EXPECT_EQ("echo.example.com", uc.host);
  15955. EXPECT_EQ("8080", uc.port);
  15956. EXPECT_EQ("/ws", uc.path);
  15957. }
  15958. {
  15959. detail::UrlComponents uc;
  15960. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15961. EXPECT_EQ("wss", uc.scheme);
  15962. EXPECT_EQ("echo.example.com", uc.host);
  15963. EXPECT_TRUE(uc.port.empty());
  15964. EXPECT_EQ("/ws", uc.path);
  15965. }
  15966. }
  15967. TEST(ParseUrlTest, QueryOnly) {
  15968. detail::UrlComponents uc;
  15969. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15970. EXPECT_TRUE(uc.host.empty());
  15971. EXPECT_TRUE(uc.path.empty());
  15972. EXPECT_EQ("?q=1&r=2", uc.query);
  15973. }
  15974. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15975. detail::UrlComponents uc;
  15976. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15977. EXPECT_TRUE(uc.scheme.empty());
  15978. EXPECT_EQ("example.com", uc.host);
  15979. EXPECT_EQ("443", uc.port);
  15980. EXPECT_EQ("/path", uc.path);
  15981. }
  15982. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15983. // If ipv6 regex working, regex match codepath is taken.
  15984. // else port will default to 80 in Client impl
  15985. int clientImplMagicPort = 80;
  15986. int port = 4321;
  15987. // above ports must be different to avoid false negative
  15988. EXPECT_NE(clientImplMagicPort, port);
  15989. std::string ipV6TestURL = "http://[ff06::c3]";
  15990. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15991. CLIENT_PRIVATE_KEY_FILE);
  15992. EXPECT_EQ(cli.port(), port);
  15993. }
  15994. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15995. auto file_path = "./www/dir/index.html";
  15996. auto dir_path = "./www/dir";
  15997. detail::FileStat stat_file(file_path);
  15998. EXPECT_TRUE(stat_file.is_file());
  15999. EXPECT_FALSE(stat_file.is_dir());
  16000. detail::FileStat stat_dir(dir_path);
  16001. EXPECT_FALSE(stat_dir.is_file());
  16002. EXPECT_TRUE(stat_dir.is_dir());
  16003. }
  16004. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16005. // IPv4 with default HTTP port (80)
  16006. EXPECT_EQ("example.com",
  16007. detail::make_host_and_port_string("example.com", 80, false));
  16008. // IPv4 with default HTTPS port (443)
  16009. EXPECT_EQ("example.com",
  16010. detail::make_host_and_port_string("example.com", 443, true));
  16011. // IPv4 with non-default HTTP port
  16012. EXPECT_EQ("example.com:8080",
  16013. detail::make_host_and_port_string("example.com", 8080, false));
  16014. // IPv4 with non-default HTTPS port
  16015. EXPECT_EQ("example.com:8443",
  16016. detail::make_host_and_port_string("example.com", 8443, true));
  16017. // IPv6 with default HTTP port (80)
  16018. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16019. // IPv6 with default HTTPS port (443)
  16020. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16021. // IPv6 with non-default HTTP port
  16022. EXPECT_EQ("[::1]:8080",
  16023. detail::make_host_and_port_string("::1", 8080, false));
  16024. // IPv6 with non-default HTTPS port
  16025. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16026. // IPv6 full address with default port
  16027. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16028. detail::make_host_and_port_string(
  16029. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16030. // IPv6 full address with non-default port
  16031. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16032. detail::make_host_and_port_string(
  16033. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16034. // IPv6 localhost with non-default port
  16035. EXPECT_EQ("[::1]:3000",
  16036. detail::make_host_and_port_string("::1", 3000, false));
  16037. // IPv6 with zone ID (link-local address) with default port
  16038. EXPECT_EQ("[fe80::1%eth0]",
  16039. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16040. // IPv6 with zone ID (link-local address) with non-default port
  16041. EXPECT_EQ("[fe80::1%eth0]:8080",
  16042. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16043. // Edge case: Port 443 with is_ssl=false (should add port)
  16044. EXPECT_EQ("example.com:443",
  16045. detail::make_host_and_port_string("example.com", 443, false));
  16046. // Edge case: Port 80 with is_ssl=true (should add port)
  16047. EXPECT_EQ("example.com:80",
  16048. detail::make_host_and_port_string("example.com", 80, true));
  16049. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16050. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16051. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16052. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16053. // Security fix: Already bracketed IPv6 should not get double brackets
  16054. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16055. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16056. EXPECT_EQ("[::1]:8080",
  16057. detail::make_host_and_port_string("[::1]", 8080, false));
  16058. EXPECT_EQ("[2001:db8::1]:8080",
  16059. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16060. EXPECT_EQ("[fe80::1%eth0]",
  16061. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16062. EXPECT_EQ("[fe80::1%eth0]:8080",
  16063. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16064. // Edge case: Empty host (should return as-is)
  16065. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16066. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16067. // This is a known limitation but shouldn't crash
  16068. EXPECT_EQ("[host:name]",
  16069. detail::make_host_and_port_string("host:name", 80, false));
  16070. // Port number edge cases (no validation, but should not crash)
  16071. EXPECT_EQ("example.com:0",
  16072. detail::make_host_and_port_string("example.com", 0, false));
  16073. EXPECT_EQ("example.com:-1",
  16074. detail::make_host_and_port_string("example.com", -1, false));
  16075. EXPECT_EQ("example.com:65535",
  16076. detail::make_host_and_port_string("example.com", 65535, false));
  16077. EXPECT_EQ("example.com:65536",
  16078. detail::make_host_and_port_string("example.com", 65536, false));
  16079. }
  16080. #ifdef CPPHTTPLIB_SSL_ENABLED
  16081. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16082. httplib::SSLClient cli("roblox.com", 443);
  16083. cli.set_follow_location(true);
  16084. auto res = cli.Get("/");
  16085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16086. EXPECT_EQ(StatusCode::OK_200, res->status);
  16087. }
  16088. #endif
  16089. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16090. Server svr;
  16091. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16092. EXPECT_EQ(res.status, 400);
  16093. });
  16094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16095. auto se = detail::scope_exit([&] {
  16096. svr.stop();
  16097. thread.join();
  16098. ASSERT_FALSE(svr.is_running());
  16099. });
  16100. svr.wait_until_ready();
  16101. Client cli(HOST, PORT);
  16102. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16103. }
  16104. TEST(InvalidHeaderCharsTest, is_field_name) {
  16105. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16106. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16107. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16108. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16109. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16110. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16111. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16112. EXPECT_FALSE(detail::fields::is_field_name(""));
  16113. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16114. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16115. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16116. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16117. }
  16118. TEST(InvalidHeaderCharsTest, is_field_value) {
  16119. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16120. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16121. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16122. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16123. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16124. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16125. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16126. EXPECT_TRUE(detail::fields::is_field_value(""));
  16127. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16128. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16129. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16130. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16131. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16132. }
  16133. TEST(InvalidHeaderCharsTest, OnServer) {
  16134. Server svr;
  16135. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16136. std::string header = "Not Set";
  16137. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16138. res.set_header(header, "value");
  16139. res.set_content("Page Content Page Content", "text/plain");
  16140. });
  16141. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16142. std::string header = "Not Set";
  16143. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16144. res.set_header("X-Test", header);
  16145. res.set_content("Page Content Page Content", "text/plain");
  16146. });
  16147. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16148. auto se = detail::scope_exit([&] {
  16149. svr.stop();
  16150. thread.join();
  16151. ASSERT_FALSE(svr.is_running());
  16152. });
  16153. svr.wait_until_ready();
  16154. Client cli(HOST, PORT);
  16155. {
  16156. auto res = cli.Get(
  16157. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16159. EXPECT_EQ("Page Content Page Content", res->body);
  16160. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16161. }
  16162. {
  16163. auto res = cli.Get(
  16164. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ("Page Content Page Content", res->body);
  16167. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16168. }
  16169. }
  16170. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16171. auto handled = false;
  16172. Server svr;
  16173. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16174. thread t = thread([&] { svr.listen(HOST, PORT); });
  16175. auto se = detail::scope_exit([&] {
  16176. svr.stop();
  16177. t.join();
  16178. ASSERT_FALSE(svr.is_running());
  16179. ASSERT_FALSE(handled);
  16180. });
  16181. svr.wait_until_ready();
  16182. auto req = "POST /test HTTP/1.1\r\n"
  16183. "Content-Length: x\r\n"
  16184. "\r\n";
  16185. std::string response;
  16186. ASSERT_TRUE(send_request(1, req, &response));
  16187. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16188. response.substr(0, response.find("\r\n")));
  16189. }
  16190. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16191. // case-insensitive, and a server that receives a 100-continue expectation in
  16192. // an HTTP/1.0 request MUST ignore it.
  16193. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16194. std::string response;
  16195. ASSERT_TRUE(send_request(1, req, &response, port));
  16196. *got_100 = response.find("100 Continue") != std::string::npos;
  16197. }
  16198. class ExpectTokenTest : public ::testing::Test {
  16199. protected:
  16200. void SetUp() override {
  16201. svr_.Post("/p", [](const Request &, Response &res) {
  16202. res.set_content("ok", "text/plain");
  16203. });
  16204. port_ = svr_.bind_to_any_port(HOST);
  16205. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16206. svr_.wait_until_ready();
  16207. }
  16208. void TearDown() override {
  16209. svr_.stop();
  16210. if (thread_.joinable()) { thread_.join(); }
  16211. }
  16212. std::string request(const char *version, const char *expect_value) const {
  16213. return std::string("POST /p ") + version +
  16214. "\r\n"
  16215. "Host: localhost\r\n"
  16216. "Content-Length: 2\r\n"
  16217. "Connection: close\r\n"
  16218. "Expect: " +
  16219. expect_value +
  16220. "\r\n"
  16221. "\r\n"
  16222. "hi";
  16223. }
  16224. Server svr_;
  16225. int port_ = 0;
  16226. thread thread_;
  16227. };
  16228. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16229. bool got_100 = false;
  16230. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16231. EXPECT_TRUE(got_100);
  16232. }
  16233. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16234. bool got_100 = true;
  16235. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16236. EXPECT_FALSE(got_100);
  16237. }
  16238. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16239. bool got_100 = false;
  16240. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16241. EXPECT_TRUE(got_100);
  16242. }
  16243. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16244. bool got_100 = false;
  16245. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16246. EXPECT_TRUE(got_100);
  16247. }
  16248. // `100 Continue` is sent only when the server starts reading the body, so a
  16249. // request rejected before that never invites the client to send it. The
  16250. // requests below carry the expectation but withhold the body, as a client
  16251. // waiting for `100 Continue` would.
  16252. // A POST that expects `100 Continue` and withholds its two-byte body.
  16253. static std::string expect_headers_only(const std::string &path) {
  16254. return "POST " + path +
  16255. " HTTP/1.1\r\n"
  16256. "Host: localhost\r\n"
  16257. "Content-Length: 2\r\n"
  16258. "Expect: 100-continue\r\n"
  16259. "\r\n";
  16260. }
  16261. class ExpectLazyContinueTest : public ::testing::Test {
  16262. protected:
  16263. void SetUp() override {
  16264. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16265. if (req.path == "/pre-routing") {
  16266. res.status = StatusCode::Unauthorized_401;
  16267. return Server::HandlerResponse::Handled;
  16268. }
  16269. return Server::HandlerResponse::Unhandled;
  16270. });
  16271. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16272. if (req.matched_route == "/pre-request") {
  16273. res.status = StatusCode::Forbidden_403;
  16274. return Server::HandlerResponse::Handled;
  16275. }
  16276. return Server::HandlerResponse::Unhandled;
  16277. });
  16278. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16279. res.set_content("ok", "text/plain");
  16280. });
  16281. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16282. res.set_content("ok", "text/plain");
  16283. });
  16284. svr_.Post("/reader-used", [](const Request &, Response &res,
  16285. const ContentReader &content_reader) {
  16286. std::string body;
  16287. content_reader([&](const char *data, size_t len) {
  16288. body.append(data, len);
  16289. return true;
  16290. });
  16291. res.set_content(body, "text/plain");
  16292. });
  16293. svr_.Post("/reader-unused",
  16294. [](const Request &, Response &res, const ContentReader &) {
  16295. res.set_content("ignored", "text/plain");
  16296. });
  16297. port_ = svr_.bind_to_any_port(HOST);
  16298. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16299. svr_.wait_until_ready();
  16300. }
  16301. void TearDown() override {
  16302. svr_.stop();
  16303. if (thread_.joinable()) { thread_.join(); }
  16304. }
  16305. // Sends `req` and reads until the server closes the connection. Returns
  16306. // false if the read had to wait for the client-side timeout instead.
  16307. bool send_until_closed(const std::string &req, std::string *resp) const {
  16308. auto start = std::chrono::steady_clock::now();
  16309. if (!send_request(3, req, resp, port_)) { return false; }
  16310. auto elapsed = std::chrono::steady_clock::now() - start;
  16311. return elapsed < std::chrono::seconds(2);
  16312. }
  16313. // The final response comes without `100 Continue`, and the server closes
  16314. // the connection since the body may or may not follow.
  16315. void expect_final_without_interim(const std::string &path,
  16316. const char *status_line) const {
  16317. std::string resp;
  16318. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16319. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16320. EXPECT_EQ(0u, resp.find(status_line));
  16321. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16322. }
  16323. Server svr_;
  16324. int port_ = 0;
  16325. thread thread_;
  16326. };
  16327. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16328. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16329. }
  16330. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16331. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16332. }
  16333. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16334. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16335. }
  16336. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16337. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16338. }
  16339. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16340. // The body follows once `100 Continue` has had time to arrive.
  16341. auto req = expect_headers_only("/reader-used");
  16342. req.insert(req.size() - 2, "Connection: close\r\n");
  16343. std::string resp;
  16344. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16345. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16346. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16347. EXPECT_NE(std::string::npos, resp.find("hi"));
  16348. }
  16349. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16350. // Large enough for the client to add `Expect: 100-continue` itself.
  16351. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16352. std::atomic<bool> body_sent{false};
  16353. Client cli(HOST, port_);
  16354. auto res = cli.Post(
  16355. "/pre-request", length,
  16356. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16357. body_sent = true;
  16358. std::string chunk(len, 'x');
  16359. sink.write(chunk.data(), chunk.size());
  16360. return true;
  16361. },
  16362. "application/octet-stream");
  16363. ASSERT_TRUE(res);
  16364. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16365. EXPECT_FALSE(body_sent);
  16366. }
  16367. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16368. Server svr;
  16369. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16370. return StatusCode::ExpectationFailed_417;
  16371. });
  16372. svr.Post("/p", [](const Request &, Response &res) {
  16373. res.set_content("ok", "text/plain");
  16374. });
  16375. auto port = svr.bind_to_any_port(HOST);
  16376. thread t = thread([&] { svr.listen_after_bind(); });
  16377. auto se = detail::scope_exit([&] {
  16378. svr.stop();
  16379. t.join();
  16380. });
  16381. svr.wait_until_ready();
  16382. std::string resp;
  16383. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16384. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16385. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16386. // Exactly one response: the route handler must not run after the 417.
  16387. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16388. }
  16389. #ifndef _WIN32
  16390. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16391. static constexpr char reject[] = "Unauthorized";
  16392. static constexpr char accept[] = "Upload accepted";
  16393. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16394. Server svr;
  16395. svr.set_expect_100_continue_handler(
  16396. [](const Request & /*req*/, Response &res) {
  16397. res.status = StatusCode::Unauthorized_401;
  16398. res.set_content(reject, "text/plain");
  16399. return res.status;
  16400. });
  16401. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16402. res.set_content(accept, "text/plain");
  16403. });
  16404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. thread.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. });
  16410. svr.wait_until_ready();
  16411. {
  16412. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16413. curl_easy_init(), &curl_easy_cleanup};
  16414. ASSERT_NE(curl, nullptr);
  16415. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16416. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16417. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16418. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16419. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16420. &curl_slist_free_all};
  16421. ASSERT_NE(list, nullptr);
  16422. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16423. struct read_data {
  16424. size_t read_size;
  16425. size_t total_size;
  16426. } data = {0, total_size};
  16427. using read_callback_t =
  16428. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16429. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16430. void *userdata) -> size_t {
  16431. read_data *d = (read_data *)userdata;
  16432. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16433. std::fill_n(ptr, size * nmemb, 'A');
  16434. d->read_size += size * nmemb;
  16435. return size * nmemb;
  16436. };
  16437. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16438. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16439. std::vector<char> buffer;
  16440. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16441. using write_callback_t =
  16442. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16443. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16444. void *userdata) -> size_t {
  16445. std::vector<char> *buf = (std::vector<char> *)userdata;
  16446. buf->reserve(buf->size() + size * nmemb + 1);
  16447. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16448. return size * nmemb;
  16449. };
  16450. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16451. {
  16452. const auto res = curl_easy_perform(curl.get());
  16453. ASSERT_EQ(res, CURLE_OK);
  16454. }
  16455. {
  16456. auto response_code = long{};
  16457. const auto res =
  16458. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16459. ASSERT_EQ(res, CURLE_OK);
  16460. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16461. }
  16462. {
  16463. auto dl = curl_off_t{};
  16464. const auto res =
  16465. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16466. ASSERT_EQ(res, CURLE_OK);
  16467. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16468. }
  16469. {
  16470. buffer.push_back('\0');
  16471. ASSERT_STRCASEEQ(buffer.data(), reject);
  16472. }
  16473. }
  16474. }
  16475. #endif
  16476. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16477. // Regression test for #2458.
  16478. //
  16479. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16480. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16481. // ticket can make the client socket spuriously readable during the
  16482. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16483. // the client withholds the body and then blocks reading a response that never
  16484. // comes, failing with `Failed to read connection`.
  16485. //
  16486. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16487. // within the timeout. This raw OpenSSL server deliberately never sends
  16488. // `100 Continue`; the client must still deliver the body and receive 200.
  16489. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16490. signal(SIGPIPE, SIG_IGN);
  16491. const auto port = PORT + 4;
  16492. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16493. ASSERT_NE(srv, INVALID_SOCKET);
  16494. int opt = 1;
  16495. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16496. sockaddr_in addr{};
  16497. addr.sin_family = AF_INET;
  16498. addr.sin_port = htons(static_cast<uint16_t>(port));
  16499. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16500. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16501. ASSERT_EQ(0, ::listen(srv, 1));
  16502. std::atomic<size_t> server_body_bytes{0};
  16503. auto server_thread = std::thread([&] {
  16504. sockaddr_in cli_addr{};
  16505. socklen_t cli_len = sizeof(cli_addr);
  16506. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16507. if (cli == INVALID_SOCKET) { return; }
  16508. // Bound the lifetime of the server side so a buggy client (which never
  16509. // sends the body) cannot make this thread block forever on join.
  16510. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16511. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16512. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16513. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16514. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16515. SSL *ssl = SSL_new(ctx);
  16516. SSL_set_fd(ssl, static_cast<int>(cli));
  16517. if (SSL_accept(ssl) > 0) {
  16518. // Read the request headers. Reading here also flushes the TLS 1.3
  16519. // session tickets to the client. Deliberately do NOT send
  16520. // `100 Continue`.
  16521. std::string buf;
  16522. char tmp[1024];
  16523. while (buf.find("\r\n\r\n") == std::string::npos) {
  16524. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16525. if (n <= 0) { break; }
  16526. buf.append(tmp, static_cast<size_t>(n));
  16527. }
  16528. // A correct client sends the body now; count what arrives.
  16529. auto pos = buf.find("\r\n\r\n");
  16530. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16531. while (body < 4096) {
  16532. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16533. if (n <= 0) { break; }
  16534. body += static_cast<size_t>(n);
  16535. }
  16536. server_body_bytes = body;
  16537. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16538. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16539. SSL_shutdown(ssl);
  16540. }
  16541. SSL_free(ssl);
  16542. detail::close_socket(cli);
  16543. SSL_CTX_free(ctx);
  16544. });
  16545. auto se = detail::scope_exit([&] {
  16546. server_thread.join();
  16547. detail::close_socket(srv);
  16548. });
  16549. SSLClient cli("127.0.0.1", port);
  16550. cli.enable_server_certificate_verification(false);
  16551. cli.set_connection_timeout(5, 0);
  16552. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16553. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16554. std::string body(4096, 'A');
  16555. auto res = cli.Put("/api/test", body, "application/json");
  16556. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16557. EXPECT_EQ(StatusCode::OK_200, res->status);
  16558. EXPECT_EQ(body.size(), server_body_bytes.load());
  16559. }
  16560. #endif
  16561. template <typename S, typename C>
  16562. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16563. svr.Get("/stream", [&](const Request &, Response &res) {
  16564. auto data = new std::string("01234567890123456789");
  16565. res.set_content_provider(
  16566. data->size(), "text/plain",
  16567. [&, data](size_t offset, size_t length, DataSink &sink) {
  16568. const size_t DATA_CHUNK_SIZE = 4;
  16569. const auto &d = *data;
  16570. std::this_thread::sleep_for(std::chrono::seconds(1));
  16571. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16572. return true;
  16573. },
  16574. [data](bool success) {
  16575. EXPECT_FALSE(success);
  16576. delete data;
  16577. });
  16578. });
  16579. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16580. auto i = new size_t(0);
  16581. res.set_content_provider(
  16582. "text/plain",
  16583. [i](size_t, DataSink &sink) {
  16584. if (*i < 5) {
  16585. std::this_thread::sleep_for(std::chrono::seconds(1));
  16586. sink.write("abcd", 4);
  16587. (*i)++;
  16588. } else {
  16589. sink.done();
  16590. }
  16591. return true;
  16592. },
  16593. [i](bool success) {
  16594. EXPECT_FALSE(success);
  16595. delete i;
  16596. });
  16597. });
  16598. svr.Get("/chunked", [&](const Request &, Response &res) {
  16599. auto i = new size_t(0);
  16600. res.set_chunked_content_provider(
  16601. "text/plain",
  16602. [i](size_t, DataSink &sink) {
  16603. if (*i < 5) {
  16604. std::this_thread::sleep_for(std::chrono::seconds(1));
  16605. sink.os << "abcd";
  16606. (*i)++;
  16607. } else {
  16608. sink.done();
  16609. }
  16610. return true;
  16611. },
  16612. [i](bool success) {
  16613. EXPECT_FALSE(success);
  16614. delete i;
  16615. });
  16616. });
  16617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16618. auto se = detail::scope_exit([&] {
  16619. svr.stop();
  16620. listen_thread.join();
  16621. ASSERT_FALSE(svr.is_running());
  16622. });
  16623. svr.wait_until_ready();
  16624. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16625. {
  16626. auto start = std::chrono::steady_clock::now();
  16627. auto res = cli.Get("/stream");
  16628. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16629. std::chrono::steady_clock::now() - start)
  16630. .count();
  16631. ASSERT_FALSE(res);
  16632. EXPECT_EQ(Error::Read, res.error());
  16633. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16634. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16635. }
  16636. {
  16637. auto start = std::chrono::steady_clock::now();
  16638. auto res = cli.Get("/stream_without_length");
  16639. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16640. std::chrono::steady_clock::now() - start)
  16641. .count();
  16642. ASSERT_FALSE(res);
  16643. EXPECT_EQ(Error::Read, res.error());
  16644. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16645. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16646. }
  16647. {
  16648. auto start = std::chrono::steady_clock::now();
  16649. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16650. EXPECT_EQ("abcd", string(data, data_length));
  16651. return true;
  16652. });
  16653. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16654. std::chrono::steady_clock::now() - start)
  16655. .count();
  16656. ASSERT_FALSE(res);
  16657. EXPECT_EQ(Error::Read, res.error());
  16658. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16659. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16660. }
  16661. }
  16662. TEST(MaxTimeoutTest, ContentStream) {
  16663. time_t timeout = 2000;
  16664. time_t threshold = 200;
  16665. Server svr;
  16666. Client cli("localhost", PORT);
  16667. max_timeout_test(svr, cli, timeout, threshold);
  16668. }
  16669. #ifdef CPPHTTPLIB_SSL_ENABLED
  16670. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16671. time_t timeout = 2000;
  16672. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16674. SSLClient cli("localhost", PORT);
  16675. cli.enable_server_certificate_verification(false);
  16676. max_timeout_test(svr, cli, timeout, threshold);
  16677. }
  16678. #endif
  16679. class EventDispatcher {
  16680. public:
  16681. EventDispatcher() {}
  16682. bool wait_event(DataSink *sink) {
  16683. unique_lock<mutex> lk(m_);
  16684. int id = id_;
  16685. // Wait with timeout to prevent hanging if client disconnects
  16686. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16687. [&] { return cid_ == id; })) {
  16688. return false; // Timeout occurred
  16689. }
  16690. sink->write(message_.data(), message_.size());
  16691. return true;
  16692. }
  16693. void send_event(const string &message) {
  16694. lock_guard<mutex> lk(m_);
  16695. cid_ = id_++;
  16696. message_ = message;
  16697. cv_.notify_all();
  16698. }
  16699. private:
  16700. mutex m_;
  16701. condition_variable cv_;
  16702. atomic_int id_{0};
  16703. atomic_int cid_{-1};
  16704. string message_;
  16705. };
  16706. TEST(ClientInThreadTest, Issue2068) {
  16707. EventDispatcher ed;
  16708. Server svr;
  16709. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16710. res.set_chunked_content_provider("text/event-stream",
  16711. [&](size_t /*offset*/, DataSink &sink) {
  16712. return ed.wait_event(&sink);
  16713. });
  16714. });
  16715. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16716. svr.wait_until_ready();
  16717. thread event_thread([&] {
  16718. int id = 0;
  16719. while (svr.is_running()) {
  16720. this_thread::sleep_for(chrono::milliseconds(500));
  16721. std::stringstream ss;
  16722. ss << "data: " << id << "\n\n";
  16723. ed.send_event(ss.str());
  16724. id++;
  16725. }
  16726. });
  16727. auto se = detail::scope_exit([&] {
  16728. svr.stop();
  16729. listen_thread.join();
  16730. event_thread.join();
  16731. ASSERT_FALSE(svr.is_running());
  16732. });
  16733. {
  16734. auto client = detail::make_unique<Client>(HOST, PORT);
  16735. client->set_read_timeout(std::chrono::minutes(10));
  16736. std::atomic<bool> stop{false};
  16737. std::thread t([&] {
  16738. client->Get("/event1",
  16739. [&](const char *, size_t) -> bool { return !stop; });
  16740. });
  16741. std::this_thread::sleep_for(std::chrono::seconds(2));
  16742. stop = true;
  16743. client->stop();
  16744. t.join();
  16745. // Reset client after thread has finished
  16746. client.reset();
  16747. }
  16748. }
  16749. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16750. auto handled = false;
  16751. Server svr;
  16752. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16753. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16754. auto se = detail::scope_exit([&] {
  16755. svr.stop();
  16756. t.join();
  16757. ASSERT_FALSE(svr.is_running());
  16758. ASSERT_FALSE(handled);
  16759. });
  16760. svr.wait_until_ready();
  16761. // Two Content-Length headers with different values — must be rejected
  16762. auto req = "POST /test HTTP/1.1\r\n"
  16763. "Content-Length: 5\r\n"
  16764. "Content-Length: 10\r\n"
  16765. "\r\n"
  16766. "hello";
  16767. std::string response;
  16768. ASSERT_TRUE(send_request(1, req, &response));
  16769. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16770. response.substr(0, response.find("\r\n")));
  16771. }
  16772. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16773. auto handled = false;
  16774. Server svr;
  16775. svr.Post("/test", [&](const Request &, Response &res) {
  16776. handled = true;
  16777. res.set_content("ok", "text/plain");
  16778. });
  16779. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16780. auto se = detail::scope_exit([&] {
  16781. svr.stop();
  16782. t.join();
  16783. ASSERT_FALSE(svr.is_running());
  16784. ASSERT_TRUE(handled);
  16785. });
  16786. svr.wait_until_ready();
  16787. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16788. auto req = "POST /test HTTP/1.1\r\n"
  16789. "Content-Length: 5\r\n"
  16790. "Content-Length: 5\r\n"
  16791. "\r\n"
  16792. "hello";
  16793. std::string response;
  16794. ASSERT_TRUE(send_request(1, req, &response));
  16795. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16796. }
  16797. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16798. Server svr;
  16799. svr.Get("/test", [](const Request &, Response &res) {
  16800. res.set_content("ok", "text/plain");
  16801. });
  16802. auto port = svr.bind_to_any_port(HOST);
  16803. thread t = thread([&] { svr.listen_after_bind(); });
  16804. auto se = detail::scope_exit([&] {
  16805. svr.stop();
  16806. t.join();
  16807. ASSERT_FALSE(svr.is_running());
  16808. });
  16809. svr.wait_until_ready();
  16810. auto status_line = [&](const std::string &host_lines) {
  16811. std::string res;
  16812. send_request(
  16813. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16814. &res, port);
  16815. return res.substr(0, res.find("\r\n"));
  16816. };
  16817. const char *accepted[] = {
  16818. "Host: localhost\r\n",
  16819. "Host: a.example:8080\r\n",
  16820. "Host: my_service\r\n",
  16821. "Host: [::1]:8080\r\n",
  16822. "Host: [fe80::1%25eth0]\r\n",
  16823. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16824. };
  16825. for (auto host_lines : accepted) {
  16826. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16827. }
  16828. const char *rejected[] = {
  16829. "Host: a.example\r\nHost: b.example\r\n",
  16830. "Host: a.example\r\nHost: a.example\r\n",
  16831. "Host: a@b.example\r\n",
  16832. "Host: a.example/b\r\n",
  16833. "Host: a.example\\b\r\n",
  16834. "Host: a.example?b\r\n",
  16835. "Host: a.example#b\r\n",
  16836. "Host: a.example b.example\r\n",
  16837. };
  16838. for (auto host_lines : rejected) {
  16839. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16840. << host_lines;
  16841. }
  16842. }
  16843. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16844. Server svr;
  16845. svr.Get("/", [](const Request &req, Response &res) {
  16846. EXPECT_EQ(2U, req.trailers.size());
  16847. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16848. // Denied
  16849. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16850. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16851. // Accepted
  16852. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16853. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16854. EXPECT_TRUE(req.has_trailer("X-World"));
  16855. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16856. res.set_content("ok", "text/plain");
  16857. });
  16858. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16859. auto se = detail::scope_exit([&] {
  16860. svr.stop();
  16861. t.join();
  16862. ASSERT_FALSE(svr.is_running());
  16863. });
  16864. svr.wait_until_ready();
  16865. const std::string req = "GET / HTTP/1.1\r\n"
  16866. "Transfer-Encoding: chunked\r\n"
  16867. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16868. "\r\n"
  16869. "0\r\n"
  16870. "Content-Length: 10\r\n"
  16871. "Host: internal.local\r\n"
  16872. "Content-Type: malicious/content\r\n"
  16873. "Cookie: any\r\n"
  16874. "Set-Cookie: any\r\n"
  16875. "X-Forwarded-For: attacker.com\r\n"
  16876. "X-Real-Ip: 1.1.1.1\r\n"
  16877. "X-Hello: hello\r\n"
  16878. "X-World: world\r\n"
  16879. "\r\n";
  16880. std::string res;
  16881. ASSERT_TRUE(send_request(1, req, &res));
  16882. }
  16883. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16884. // several field lines, and the combined value is what has to be parsed. A
  16885. // Trailer field split across lines therefore declares every name it lists;
  16886. // reading only the first line silently drops the trailers the later lines
  16887. // declare. The prohibited-trailer filter still applies to every line.
  16888. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16889. Server svr;
  16890. size_t observed_trailer_count = 0;
  16891. std::string observed_hello;
  16892. std::string observed_world;
  16893. bool observed_content_length = true;
  16894. svr.Get("/", [&](const Request &req, Response &res) {
  16895. observed_trailer_count = req.trailers.size();
  16896. observed_hello = req.get_trailer_value("X-Hello");
  16897. observed_world = req.get_trailer_value("X-World");
  16898. observed_content_length = req.has_trailer("Content-Length");
  16899. res.set_content("ok", "text/plain");
  16900. });
  16901. auto port = svr.bind_to_any_port(HOST);
  16902. thread t = thread([&]() { svr.listen_after_bind(); });
  16903. auto se = detail::scope_exit([&] {
  16904. svr.stop();
  16905. t.join();
  16906. ASSERT_FALSE(svr.is_running());
  16907. });
  16908. svr.wait_until_ready();
  16909. const std::string req = "GET / HTTP/1.1\r\n"
  16910. "Transfer-Encoding: chunked\r\n"
  16911. "Trailer: X-Hello\r\n"
  16912. "Trailer: X-World, Content-Length\r\n"
  16913. "\r\n"
  16914. "0\r\n"
  16915. "X-Hello: hello\r\n"
  16916. "X-World: world\r\n"
  16917. "Content-Length: 10\r\n"
  16918. "\r\n";
  16919. std::string res;
  16920. ASSERT_TRUE(send_request(1, req, &res, port));
  16921. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16922. // Accepted: both field lines contribute to the declared set
  16923. EXPECT_EQ(2U, observed_trailer_count);
  16924. EXPECT_EQ(observed_hello, "hello");
  16925. EXPECT_EQ(observed_world, "world");
  16926. // Denied: a prohibited name stays prohibited on a later field line
  16927. EXPECT_FALSE(observed_content_length);
  16928. }
  16929. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16930. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16931. // unbounded run of fields that are never declared, because the counter would
  16932. // only advance for declared fields.
  16933. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16934. Server svr;
  16935. bool handler_called = false;
  16936. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16937. handler_called = true;
  16938. res.set_content("ok", "text/plain");
  16939. });
  16940. auto port = svr.bind_to_any_port(HOST);
  16941. thread t = thread([&]() { svr.listen_after_bind(); });
  16942. auto se = detail::scope_exit([&] {
  16943. svr.stop();
  16944. t.join();
  16945. ASSERT_FALSE(svr.is_running());
  16946. });
  16947. svr.wait_until_ready();
  16948. // Declare nothing, then send far more undeclared trailer fields than the
  16949. // header-count limit. Parsing must stop and reject the request rather than
  16950. // read every line.
  16951. std::string req = "GET / HTTP/1.1\r\n"
  16952. "Transfer-Encoding: chunked\r\n"
  16953. "\r\n"
  16954. "0\r\n";
  16955. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16956. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16957. }
  16958. req += "\r\n";
  16959. std::string res;
  16960. ASSERT_TRUE(send_request(1, req, &res, port));
  16961. // The request is rejected before the handler runs.
  16962. EXPECT_FALSE(handler_called);
  16963. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16964. }
  16965. // The set of declared trailer names is capped so a peer cannot grow it without
  16966. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16967. // declared past the cap is not honored, even if the field is actually sent.
  16968. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16969. Server svr;
  16970. // One name inside the cap and one past it, so the test tracks the cap rather
  16971. // than a fixed count.
  16972. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16973. const std::string within_cap_name = "X-T-0";
  16974. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16975. bool observed_within_cap = false;
  16976. bool observed_past_cap = false;
  16977. svr.Get("/", [&](const Request &req, Response &res) {
  16978. observed_within_cap = req.has_trailer(within_cap_name);
  16979. observed_past_cap = req.has_trailer(past_cap_name);
  16980. res.set_content("ok", "text/plain");
  16981. });
  16982. auto port = svr.bind_to_any_port(HOST);
  16983. thread t = thread([&]() { svr.listen_after_bind(); });
  16984. auto se = detail::scope_exit([&] {
  16985. svr.stop();
  16986. t.join();
  16987. ASSERT_FALSE(svr.is_running());
  16988. });
  16989. svr.wait_until_ready();
  16990. // Declare more trailer names than the cap in a single Trailer field, then
  16991. // actually send the first (within the cap) and the last (past it).
  16992. std::string trailer_decl = "Trailer: ";
  16993. for (int i = 0; i < declared_count; i++) {
  16994. if (i != 0) { trailer_decl += ", "; }
  16995. trailer_decl += "X-T-" + std::to_string(i);
  16996. }
  16997. trailer_decl += "\r\n";
  16998. const std::string req = "GET / HTTP/1.1\r\n"
  16999. "Transfer-Encoding: chunked\r\n" +
  17000. trailer_decl +
  17001. "\r\n"
  17002. "0\r\n" +
  17003. within_cap_name + ": a\r\n" + past_cap_name +
  17004. ": b\r\n"
  17005. "\r\n";
  17006. std::string res;
  17007. ASSERT_TRUE(send_request(1, req, &res, port));
  17008. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17009. // A name within the cap is honored; one declared past the cap is dropped.
  17010. EXPECT_TRUE(observed_within_cap);
  17011. EXPECT_FALSE(observed_past_cap);
  17012. }
  17013. // A direct client that is not listed in trusted_proxies must not be able to
  17014. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17015. // the peer address on the actual TCP connection determines whether the
  17016. // header is honored.
  17017. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17018. Server svr;
  17019. // Deliberately does NOT include the loopback address the test client
  17020. // actually connects from, so the direct connection is not a trusted proxy.
  17021. svr.set_trusted_proxies({"203.0.113.66"});
  17022. std::string observed_remote_addr;
  17023. svr.Get("/ip", [&](const Request &req, Response &res) {
  17024. observed_remote_addr = req.remote_addr;
  17025. res.set_content("ok", "text/plain");
  17026. });
  17027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17028. auto se = detail::scope_exit([&] {
  17029. svr.stop();
  17030. t.join();
  17031. ASSERT_FALSE(svr.is_running());
  17032. });
  17033. svr.wait_until_ready();
  17034. Client cli(HOST, PORT);
  17035. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17037. EXPECT_EQ(StatusCode::OK_200, res->status);
  17038. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17039. // ignored entirely and the real connection-level address retained.
  17040. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17041. observed_remote_addr == "127.0.0.1");
  17042. }
  17043. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17044. Server svr;
  17045. std::string observed_remote_addr;
  17046. std::string observed_xff;
  17047. svr.Get("/ip", [&](const Request &req, Response &res) {
  17048. observed_remote_addr = req.remote_addr;
  17049. observed_xff = req.get_header_value("X-Forwarded-For");
  17050. res.set_content("ok", "text/plain");
  17051. });
  17052. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17053. auto se = detail::scope_exit([&] {
  17054. svr.stop();
  17055. t.join();
  17056. ASSERT_FALSE(svr.is_running());
  17057. });
  17058. svr.wait_until_ready();
  17059. Client cli(HOST, PORT);
  17060. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17062. EXPECT_EQ(StatusCode::OK_200, res->status);
  17063. EXPECT_EQ(observed_xff, "203.0.113.66");
  17064. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17065. observed_remote_addr == "127.0.0.1");
  17066. }
  17067. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17068. Server svr;
  17069. svr.set_trusted_proxies({"203.0.113.66"});
  17070. std::string observed_remote_addr;
  17071. std::string observed_xff;
  17072. svr.Get("/ip", [&](const Request &req, Response &res) {
  17073. observed_remote_addr = req.remote_addr;
  17074. observed_xff = req.get_header_value("X-Forwarded-For");
  17075. res.set_content("ok", "text/plain");
  17076. });
  17077. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17078. auto se = detail::scope_exit([&] {
  17079. svr.stop();
  17080. t.join();
  17081. ASSERT_FALSE(svr.is_running());
  17082. });
  17083. svr.wait_until_ready();
  17084. Client cli(HOST, PORT);
  17085. auto res = cli.Get("/ip");
  17086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17087. EXPECT_EQ(StatusCode::OK_200, res->status);
  17088. EXPECT_EQ(observed_xff, "");
  17089. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17090. observed_remote_addr == "127.0.0.1");
  17091. }
  17092. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17093. Server svr;
  17094. // Include the loopback address the test client actually connects from, so
  17095. // the direct connection itself is recognized as the trusted proxy hop.
  17096. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17097. std::string observed_remote_addr;
  17098. std::string observed_xff;
  17099. svr.Get("/ip", [&](const Request &req, Response &res) {
  17100. observed_remote_addr = req.remote_addr;
  17101. observed_xff = req.get_header_value("X-Forwarded-For");
  17102. res.set_content("ok", "text/plain");
  17103. });
  17104. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17105. auto se = detail::scope_exit([&] {
  17106. svr.stop();
  17107. t.join();
  17108. ASSERT_FALSE(svr.is_running());
  17109. });
  17110. svr.wait_until_ready();
  17111. Client cli(HOST, PORT);
  17112. auto res = cli.Get(
  17113. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17115. EXPECT_EQ(StatusCode::OK_200, res->status);
  17116. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17117. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17118. }
  17119. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17120. Server svr;
  17121. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17122. std::string observed_remote_addr;
  17123. std::string observed_xff;
  17124. svr.Get("/ip", [&](const Request &req, Response &res) {
  17125. observed_remote_addr = req.remote_addr;
  17126. observed_xff = req.get_header_value("X-Forwarded-For");
  17127. res.set_content("ok", "text/plain");
  17128. });
  17129. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17130. auto se = detail::scope_exit([&] {
  17131. svr.stop();
  17132. t.join();
  17133. ASSERT_FALSE(svr.is_running());
  17134. });
  17135. svr.wait_until_ready();
  17136. Client cli(HOST, PORT);
  17137. auto res = cli.Get(
  17138. "/ip",
  17139. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17141. EXPECT_EQ(StatusCode::OK_200, res->status);
  17142. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17143. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17144. }
  17145. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17146. Server svr;
  17147. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17148. std::string observed_remote_addr;
  17149. std::string observed_xff;
  17150. svr.Get("/ip", [&](const Request &req, Response &res) {
  17151. observed_remote_addr = req.remote_addr;
  17152. observed_xff = req.get_header_value("X-Forwarded-For");
  17153. res.set_content("ok", "text/plain");
  17154. });
  17155. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17156. auto se = detail::scope_exit([&] {
  17157. svr.stop();
  17158. t.join();
  17159. ASSERT_FALSE(svr.is_running());
  17160. });
  17161. svr.wait_until_ready();
  17162. Client cli(HOST, PORT);
  17163. auto res = cli.Get(
  17164. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17166. EXPECT_EQ(StatusCode::OK_200, res->status);
  17167. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17168. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17169. // and must not be selected.
  17170. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17171. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17172. }
  17173. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17174. Server svr;
  17175. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17176. std::string observed_remote_addr;
  17177. svr.Get("/ip", [&](const Request &req, Response &res) {
  17178. observed_remote_addr = req.remote_addr;
  17179. res.set_content("ok", "text/plain");
  17180. });
  17181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17182. auto se = detail::scope_exit([&] {
  17183. svr.stop();
  17184. t.join();
  17185. ASSERT_FALSE(svr.is_running());
  17186. });
  17187. svr.wait_until_ready();
  17188. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17189. // a forged address and the trusted proxy's own address; the forged value must
  17190. // not win over the address the trusted proxy actually recorded.
  17191. Client cli(HOST, PORT);
  17192. auto res = cli.Get(
  17193. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17195. EXPECT_EQ(StatusCode::OK_200, res->status);
  17196. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17197. }
  17198. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17199. Server svr;
  17200. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17201. std::string observed_remote_addr;
  17202. std::string observed_xff;
  17203. svr.Get("/ip", [&](const Request &req, Response &res) {
  17204. observed_remote_addr = req.remote_addr;
  17205. observed_xff = req.get_header_value("X-Forwarded-For");
  17206. res.set_content("ok", "text/plain");
  17207. });
  17208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17209. auto se = detail::scope_exit([&] {
  17210. svr.stop();
  17211. t.join();
  17212. ASSERT_FALSE(svr.is_running());
  17213. });
  17214. svr.wait_until_ready();
  17215. Client cli(HOST, PORT);
  17216. auto res = cli.Get(
  17217. "/ip",
  17218. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17220. EXPECT_EQ(StatusCode::OK_200, res->status);
  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. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17225. Server svr;
  17226. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17227. std::string observed_remote_addr;
  17228. std::string observed_xff;
  17229. svr.Get("/ip", [&](const Request &req, Response &res) {
  17230. observed_remote_addr = req.remote_addr;
  17231. observed_xff = req.get_header_value("X-Forwarded-For");
  17232. res.set_content("ok", "text/plain");
  17233. });
  17234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17235. auto se = detail::scope_exit([&] {
  17236. svr.stop();
  17237. t.join();
  17238. ASSERT_FALSE(svr.is_running());
  17239. });
  17240. svr.wait_until_ready();
  17241. std::string raw_req =
  17242. "GET /ip HTTP/1.1\r\n"
  17243. "Host: localhost\r\n"
  17244. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17245. "Connection: close\r\n"
  17246. "\r\n";
  17247. std::string out;
  17248. ASSERT_TRUE(send_request(5, raw_req, &out));
  17249. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17250. // Header parser trims surrounding whitespace of the header value
  17251. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17252. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17253. }
  17254. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17255. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17256. // their own X-Forwarded-For as a separate field line rather than extending the
  17257. // one the client sent, so every occurrence has to be taken into account.
  17258. // Reading only the first one hands back the address the client chose.
  17259. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17260. Server svr;
  17261. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17262. std::string observed_remote_addr;
  17263. size_t observed_xff_count = 0;
  17264. svr.Get("/ip", [&](const Request &req, Response &res) {
  17265. observed_remote_addr = req.remote_addr;
  17266. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17267. res.set_content("ok", "text/plain");
  17268. });
  17269. auto port = svr.bind_to_any_port(HOST);
  17270. thread t = thread([&]() { svr.listen_after_bind(); });
  17271. auto se = detail::scope_exit([&] {
  17272. svr.stop();
  17273. t.join();
  17274. ASSERT_FALSE(svr.is_running());
  17275. });
  17276. svr.wait_until_ready();
  17277. // The client supplies the first field line; the trusted proxy appends the
  17278. // address it observed as a second one.
  17279. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17280. "Host: localhost\r\n"
  17281. "X-Forwarded-For: 1.2.3.4\r\n"
  17282. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17283. "Connection: close\r\n"
  17284. "\r\n";
  17285. std::string out;
  17286. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17287. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17288. EXPECT_EQ(observed_xff_count, 2U);
  17289. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17290. // The same chain spread over one field line per hop derives the same client
  17291. // address, i.e. the split and the comma-joined representations agree.
  17292. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17293. "Host: localhost\r\n"
  17294. "X-Forwarded-For: 1.2.3.4\r\n"
  17295. "X-Forwarded-For: 198.51.100.23\r\n"
  17296. "X-Forwarded-For: 192.0.2.45\r\n"
  17297. "Connection: close\r\n"
  17298. "\r\n";
  17299. out.clear();
  17300. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17301. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17302. EXPECT_EQ(observed_xff_count, 3U);
  17303. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17304. }
  17305. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17306. // crash the server (it used to call front() on an empty vector inside
  17307. // get_client_ip). The connection-level remote address must be retained instead.
  17308. static void run_malformed_xff_test(const std::string &xff_value) {
  17309. Server svr;
  17310. svr.set_trusted_proxies({"192.0.2.45"});
  17311. std::string observed_remote_addr;
  17312. svr.Get("/ip", [&](const Request &req, Response &res) {
  17313. observed_remote_addr = req.remote_addr;
  17314. res.set_content("ok", "text/plain");
  17315. });
  17316. int port = 0;
  17317. thread t = thread([&]() {
  17318. port = svr.bind_to_any_port(HOST);
  17319. svr.listen_after_bind();
  17320. });
  17321. auto se = detail::scope_exit([&] {
  17322. svr.stop();
  17323. t.join();
  17324. ASSERT_FALSE(svr.is_running());
  17325. });
  17326. svr.wait_until_ready();
  17327. Client cli(HOST, port);
  17328. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17330. EXPECT_EQ(StatusCode::OK_200, res->status);
  17331. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17332. observed_remote_addr == "127.0.0.1");
  17333. }
  17334. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17335. run_malformed_xff_test("");
  17336. }
  17337. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17338. run_malformed_xff_test(",");
  17339. }
  17340. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17341. run_malformed_xff_test(", , ,");
  17342. }
  17343. // The same rule applies to Accept: a request whose acceptable types are spread
  17344. // over several field lines must be negotiated against all of them.
  17345. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17346. // case-insensitive connection options. Comparing the whole field value against
  17347. // one option misses a client that sends several of them, and misses every
  17348. // casing but the one written in the comparison.
  17349. //
  17350. // Sends req, reads the response, then reuses the same socket for a second
  17351. // request to find out whether the server kept the connection.
  17352. static void probe_connection_reuse(int port, const std::string &req,
  17353. bool *announced_close, bool *reusable) {
  17354. auto error = Error::Success;
  17355. auto sock = detail::create_client_socket(
  17356. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17357. /*connection_timeout_sec=*/5, 0,
  17358. /*read_timeout_sec=*/1, 0,
  17359. /*write_timeout_sec=*/5, 0, std::string(), error);
  17360. ASSERT_NE(sock, INVALID_SOCKET);
  17361. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17362. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17363. "Host: localhost\r\n"
  17364. "Connection: close\r\n"
  17365. "\r\n";
  17366. std::string first_response;
  17367. std::string second_response;
  17368. detail::process_client_socket(
  17369. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17370. [&](Stream &strm) {
  17371. if (strm.write(req.data(), req.size()) !=
  17372. static_cast<ssize_t>(req.size())) {
  17373. return false;
  17374. }
  17375. char buf[512];
  17376. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17377. // Headers plus the two-byte body of the handler below
  17378. while (reader.getline()) {
  17379. first_response += reader.ptr();
  17380. if (first_response.find("ok") != std::string::npos) { break; }
  17381. }
  17382. if (strm.write(second.data(), second.size()) !=
  17383. static_cast<ssize_t>(second.size())) {
  17384. return true;
  17385. }
  17386. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17387. while (reader2.getline()) {
  17388. second_response += reader2.ptr();
  17389. if (second_response.find("ok") != std::string::npos) { break; }
  17390. }
  17391. return true;
  17392. });
  17393. *announced_close =
  17394. first_response.find("Connection: close") != std::string::npos;
  17395. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17396. }
  17397. class ConnectionTokenTest : public ::testing::Test {
  17398. protected:
  17399. void SetUp() override {
  17400. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17401. res.set_content("ok", "text/plain");
  17402. });
  17403. port_ = svr_.bind_to_any_port(HOST);
  17404. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17405. svr_.wait_until_ready();
  17406. }
  17407. void TearDown() override {
  17408. svr_.stop();
  17409. if (thread_.joinable()) { thread_.join(); }
  17410. }
  17411. Server svr_;
  17412. int port_ = 0;
  17413. thread thread_;
  17414. };
  17415. // "close" alongside another option still closes the connection, and the
  17416. // response says so rather than leaving the peer to discover it.
  17417. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17418. bool announced_close = false;
  17419. bool reusable = true;
  17420. probe_connection_reuse(port_,
  17421. "GET /keepalive HTTP/1.1\r\n"
  17422. "Host: localhost\r\n"
  17423. "Connection: keep-alive, close\r\n"
  17424. "\r\n",
  17425. &announced_close, &reusable);
  17426. EXPECT_TRUE(announced_close);
  17427. EXPECT_FALSE(reusable);
  17428. }
  17429. // "close" split over two field lines is the same list, so it is honored too.
  17430. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17431. bool announced_close = false;
  17432. bool reusable = true;
  17433. probe_connection_reuse(port_,
  17434. "GET /keepalive HTTP/1.1\r\n"
  17435. "Host: localhost\r\n"
  17436. "Connection: keep-alive\r\n"
  17437. "Connection: close\r\n"
  17438. "\r\n",
  17439. &announced_close, &reusable);
  17440. EXPECT_TRUE(announced_close);
  17441. EXPECT_FALSE(reusable);
  17442. }
  17443. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17444. // keep-alive in the spelling everyone actually sends keeps its connection.
  17445. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17446. bool announced_close = false;
  17447. bool reusable = false;
  17448. probe_connection_reuse(port_,
  17449. "GET /keepalive HTTP/1.0\r\n"
  17450. "Host: localhost\r\n"
  17451. "Connection: keep-alive\r\n"
  17452. "\r\n",
  17453. &announced_close, &reusable);
  17454. EXPECT_FALSE(announced_close);
  17455. EXPECT_TRUE(reusable);
  17456. }
  17457. // A token the value merely contains is not the token itself.
  17458. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17459. bool announced_close = false;
  17460. bool reusable = false;
  17461. probe_connection_reuse(port_,
  17462. "GET /keepalive HTTP/1.1\r\n"
  17463. "Host: localhost\r\n"
  17464. "Connection: notclose\r\n"
  17465. "\r\n",
  17466. &announced_close, &reusable);
  17467. EXPECT_FALSE(announced_close);
  17468. EXPECT_TRUE(reusable);
  17469. }
  17470. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17471. Server svr;
  17472. std::vector<std::string> observed_types;
  17473. svr.Get("/", [&](const Request &req, Response &res) {
  17474. observed_types = req.accept_content_types;
  17475. res.set_content("ok", "text/plain");
  17476. });
  17477. auto port = svr.bind_to_any_port(HOST);
  17478. thread t = thread([&]() { svr.listen_after_bind(); });
  17479. auto se = detail::scope_exit([&] {
  17480. svr.stop();
  17481. t.join();
  17482. ASSERT_FALSE(svr.is_running());
  17483. });
  17484. svr.wait_until_ready();
  17485. Client cli(HOST, port);
  17486. Headers headers;
  17487. headers.emplace("Accept", "text/plain;q=0.5");
  17488. headers.emplace("Accept", "application/json");
  17489. auto res = cli.Get("/", headers);
  17490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17491. EXPECT_EQ(StatusCode::OK_200, res->status);
  17492. // Sorted by q-value, so the second field line's type comes first
  17493. ASSERT_EQ(2U, observed_types.size());
  17494. EXPECT_EQ("application/json", observed_types[0]);
  17495. EXPECT_EQ("text/plain", observed_types[1]);
  17496. }
  17497. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17498. // empty field line must not contribute a bare comma to the combined value.
  17499. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17500. Server svr;
  17501. std::vector<std::string> observed_types;
  17502. svr.Get("/", [&](const Request &req, Response &res) {
  17503. observed_types = req.accept_content_types;
  17504. res.set_content("ok", "text/plain");
  17505. });
  17506. auto port = svr.bind_to_any_port(HOST);
  17507. thread t = thread([&]() { svr.listen_after_bind(); });
  17508. auto se = detail::scope_exit([&] {
  17509. svr.stop();
  17510. t.join();
  17511. ASSERT_FALSE(svr.is_running());
  17512. });
  17513. svr.wait_until_ready();
  17514. // Empty first field line, then a real one
  17515. std::string raw_req = "GET / HTTP/1.1\r\n"
  17516. "Host: localhost\r\n"
  17517. "Accept:\r\n"
  17518. "Accept: application/json\r\n"
  17519. "Connection: close\r\n"
  17520. "\r\n";
  17521. std::string out;
  17522. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17523. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17524. ASSERT_EQ(1U, observed_types.size());
  17525. EXPECT_EQ("application/json", observed_types[0]);
  17526. }
  17527. // The skip in get_combined_header_value() is what keeps an empty field line
  17528. // from contributing a bare comma. Only a trailing empty field line exercises
  17529. // it: a leading one is already covered by the "combined is still empty" check,
  17530. // and parse_accept_header() now ignores the empty element either way, so the
  17531. // request-level test above can no longer tell the two apart.
  17532. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17533. Headers headers;
  17534. headers.emplace("Accept", "text/html");
  17535. headers.emplace("Accept", "");
  17536. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17537. headers.clear();
  17538. headers.emplace("Accept", "");
  17539. headers.emplace("Accept", "application/json");
  17540. EXPECT_EQ("application/json",
  17541. detail::get_combined_header_value(headers, "Accept"));
  17542. }
  17543. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17544. // An encoding offered on a later Accept-Encoding field line is still offered.
  17545. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17546. Server svr;
  17547. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17548. res.set_content(std::string(1024, 'x'), "text/plain");
  17549. });
  17550. auto port = svr.bind_to_any_port(HOST);
  17551. thread t = thread([&]() { svr.listen_after_bind(); });
  17552. auto se = detail::scope_exit([&] {
  17553. svr.stop();
  17554. t.join();
  17555. ASSERT_FALSE(svr.is_running());
  17556. });
  17557. svr.wait_until_ready();
  17558. Client cli(HOST, port);
  17559. cli.set_decompress(false);
  17560. Headers headers;
  17561. headers.emplace("Accept-Encoding", "identity");
  17562. headers.emplace("Accept-Encoding", "gzip");
  17563. auto res = cli.Get("/", headers);
  17564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17565. EXPECT_EQ(StatusCode::OK_200, res->status);
  17566. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17567. }
  17568. #endif
  17569. #ifndef _WIN32
  17570. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17571. Server svr;
  17572. svr.Post("/post", [&](const Request &req, Response &res) {
  17573. res.set_content(req.body, "text/plain");
  17574. });
  17575. svr.Put("/put", [&](const Request &req, Response &res) {
  17576. res.set_content(req.body, "text/plain");
  17577. });
  17578. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17579. res.set_content(req.body, "text/plain");
  17580. });
  17581. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17582. res.set_content(req.body, "text/plain");
  17583. });
  17584. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17585. auto se = detail::scope_exit([&] {
  17586. svr.stop();
  17587. t.join();
  17588. ASSERT_FALSE(svr.is_running());
  17589. });
  17590. svr.wait_until_ready();
  17591. std::string resp;
  17592. // POST without Content-Length
  17593. ASSERT_TRUE(send_request(5,
  17594. "POST /post HTTP/1.1\r\n"
  17595. "Host: localhost\r\n"
  17596. "Connection: close\r\n"
  17597. "\r\n",
  17598. &resp));
  17599. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17600. // PUT without Content-Length
  17601. resp.clear();
  17602. ASSERT_TRUE(send_request(5,
  17603. "PUT /put HTTP/1.1\r\n"
  17604. "Host: localhost\r\n"
  17605. "Connection: close\r\n"
  17606. "\r\n",
  17607. &resp));
  17608. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17609. // PATCH without Content-Length
  17610. resp.clear();
  17611. ASSERT_TRUE(send_request(5,
  17612. "PATCH /patch HTTP/1.1\r\n"
  17613. "Host: localhost\r\n"
  17614. "Connection: close\r\n"
  17615. "\r\n",
  17616. &resp));
  17617. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17618. // DELETE without Content-Length
  17619. resp.clear();
  17620. ASSERT_TRUE(send_request(5,
  17621. "DELETE /delete HTTP/1.1\r\n"
  17622. "Host: localhost\r\n"
  17623. "Connection: close\r\n"
  17624. "\r\n",
  17625. &resp));
  17626. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17627. }
  17628. #endif
  17629. //==============================================================================
  17630. // open_stream() Tests
  17631. //==============================================================================
  17632. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17633. std::string result;
  17634. char buf[8192];
  17635. ssize_t n;
  17636. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17637. result.append(buf, static_cast<size_t>(n));
  17638. }
  17639. return result;
  17640. }
  17641. // Mock stream for unit tests
  17642. class MockStream : public Stream {
  17643. public:
  17644. std::string data;
  17645. size_t pos = 0;
  17646. ssize_t error_after = -1; // -1 = no error
  17647. explicit MockStream(const std::string &d, ssize_t err = -1)
  17648. : data(d), error_after(err) {}
  17649. bool is_readable() const override { return true; }
  17650. bool wait_readable() const override { return true; }
  17651. bool wait_writable() const override { return true; }
  17652. ssize_t read(char *ptr, size_t size) override {
  17653. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17654. if (pos >= data.size()) return 0;
  17655. size_t limit =
  17656. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17657. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17658. std::memcpy(ptr, data.data() + pos, to_read);
  17659. pos += to_read;
  17660. return static_cast<ssize_t>(to_read);
  17661. }
  17662. ssize_t write(const char *, size_t) override { return -1; }
  17663. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17664. ip = "127.0.0.1";
  17665. port = 0;
  17666. }
  17667. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17668. ip = "127.0.0.1";
  17669. port = 0;
  17670. }
  17671. socket_t socket() const override { return INVALID_SOCKET; }
  17672. time_t duration() const override { return 0; }
  17673. };
  17674. TEST(StreamHandleTest, Basic) {
  17675. ClientImpl::StreamHandle handle;
  17676. EXPECT_FALSE(handle.is_valid());
  17677. handle.response = detail::make_unique<Response>();
  17678. handle.error = Error::Connection;
  17679. EXPECT_FALSE(handle.is_valid());
  17680. handle.error = Error::Success;
  17681. EXPECT_TRUE(handle.is_valid());
  17682. }
  17683. TEST(BodyReaderTest, Basic) {
  17684. MockStream stream("Hello, World!");
  17685. detail::BodyReader reader;
  17686. reader.stream = &stream;
  17687. reader.content_length = 13;
  17688. char buf[32];
  17689. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17690. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17691. EXPECT_TRUE(reader.eof);
  17692. }
  17693. TEST(BodyReaderTest, NoStream) {
  17694. detail::BodyReader reader;
  17695. char buf[32];
  17696. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17697. EXPECT_EQ(Error::Connection, reader.last_error);
  17698. }
  17699. TEST(BodyReaderTest, Error) {
  17700. MockStream stream("Hello, World!", 5);
  17701. detail::BodyReader reader;
  17702. reader.stream = &stream;
  17703. reader.content_length = 13;
  17704. char buf[32];
  17705. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17706. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17707. EXPECT_EQ(Error::Read, reader.last_error);
  17708. }
  17709. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17710. // Mock-based StreamHandle tests relying on private internals are removed.
  17711. class OpenStreamTest : public ::testing::Test {
  17712. protected:
  17713. void SetUp() override {
  17714. svr_.Get("/hello", [](const Request &, Response &res) {
  17715. res.set_content("Hello World!", "text/plain");
  17716. });
  17717. svr_.Get("/large", [](const Request &, Response &res) {
  17718. res.set_content(std::string(10000, 'X'), "text/plain");
  17719. });
  17720. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17721. res.set_content("Hello World!", "image/jpeg");
  17722. res.set_header("Content-Encoding", "UTF-8");
  17723. });
  17724. svr_.Get("/chunked", [](const Request &, Response &res) {
  17725. res.set_chunked_content_provider("text/plain",
  17726. [](size_t offset, DataSink &sink) {
  17727. if (offset < 15) {
  17728. sink.write("chunk", 5);
  17729. return true;
  17730. }
  17731. sink.done();
  17732. return true;
  17733. });
  17734. });
  17735. svr_.Get("/compressible", [](const Request &, Response &res) {
  17736. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17737. DataSink &sink) {
  17738. if (offset < 100 * 1024) {
  17739. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17740. sink.write(chunk.data(), chunk.size());
  17741. return true;
  17742. }
  17743. sink.done();
  17744. return true;
  17745. });
  17746. });
  17747. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17748. [](const Request & /*req*/, Response &res) {
  17749. auto i = new int(0);
  17750. res.set_header("Trailer", "Content-Length, X-Allowed");
  17751. res.set_chunked_content_provider(
  17752. "text/plain",
  17753. [i](size_t /*offset*/, DataSink &sink) {
  17754. switch (*i) {
  17755. case 0: sink.os << "123"; break;
  17756. case 1: sink.os << "456"; break;
  17757. case 2: sink.os << "789"; break;
  17758. case 3: {
  17759. sink.done_with_trailer(
  17760. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17761. } break;
  17762. }
  17763. (*i)++;
  17764. return true;
  17765. },
  17766. [i](bool success) {
  17767. EXPECT_TRUE(success);
  17768. delete i;
  17769. });
  17770. });
  17771. // Echo headers endpoint for header-related tests
  17772. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17773. std::string body;
  17774. for (const auto &h : req.headers) {
  17775. body.append(h.first);
  17776. body.push_back(':');
  17777. body.append(h.second);
  17778. body.push_back('\n');
  17779. }
  17780. res.set_content(body, "text/plain");
  17781. });
  17782. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17783. std::string body;
  17784. for (const auto &h : req.headers) {
  17785. body.append(h.first);
  17786. body.push_back(':');
  17787. body.append(h.second);
  17788. body.push_back('\n');
  17789. }
  17790. res.set_content(body, "text/plain");
  17791. });
  17792. port_ = svr_.bind_to_any_port("127.0.0.1");
  17793. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17794. svr_.wait_until_ready();
  17795. }
  17796. void TearDown() override {
  17797. svr_.stop();
  17798. if (thread_.joinable()) thread_.join();
  17799. }
  17800. Server svr_;
  17801. std::thread thread_;
  17802. int port_ = 0;
  17803. };
  17804. TEST_F(OpenStreamTest, Basic) {
  17805. Client cli("127.0.0.1", port_);
  17806. auto handle = cli.open_stream("GET", "/hello");
  17807. EXPECT_TRUE(handle.is_valid());
  17808. EXPECT_EQ("Hello World!", read_all(handle));
  17809. }
  17810. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17811. Client cli("127.0.0.1", port_);
  17812. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17813. ASSERT_TRUE(handle.is_valid());
  17814. EXPECT_EQ("Hello World!", read_all(handle));
  17815. }
  17816. TEST_F(OpenStreamTest, SmallBuffer) {
  17817. Client cli("127.0.0.1", port_);
  17818. auto handle = cli.open_stream("GET", "/hello");
  17819. std::string result;
  17820. char buf[4];
  17821. ssize_t n;
  17822. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17823. result.append(buf, static_cast<size_t>(n));
  17824. EXPECT_EQ("Hello World!", result);
  17825. }
  17826. TEST_F(OpenStreamTest, DefaultHeaders) {
  17827. Client cli("127.0.0.1", port_);
  17828. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17829. {
  17830. auto handle = cli.open_stream("GET", "/echo-headers");
  17831. ASSERT_TRUE(handle.is_valid());
  17832. auto body = read_all(handle);
  17833. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17834. std::string::npos);
  17835. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17836. std::string::npos);
  17837. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17838. }
  17839. // open_stream POST with body and no explicit content_type should NOT add
  17840. // text/plain Content-Type (behavior differs from non-streaming path), but
  17841. // should include Content-Length
  17842. {
  17843. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17844. ASSERT_TRUE(handle.is_valid());
  17845. auto body = read_all(handle);
  17846. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17847. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17848. }
  17849. // open_stream POST with explicit Content-Type should preserve it
  17850. {
  17851. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17852. {{"Content-Type", "application/custom"}},
  17853. "{}", "application/custom");
  17854. ASSERT_TRUE(handle.is_valid());
  17855. auto body = read_all(handle);
  17856. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17857. }
  17858. // User-specified User-Agent must not be overwritten for stream API
  17859. {
  17860. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17861. {{"User-Agent", "MyAgent/1.2"}});
  17862. ASSERT_TRUE(handle.is_valid());
  17863. auto body = read_all(handle);
  17864. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17865. }
  17866. }
  17867. TEST_F(OpenStreamTest, Large) {
  17868. Client cli("127.0.0.1", port_);
  17869. auto handle = cli.open_stream("GET", "/large");
  17870. EXPECT_EQ(10000u, read_all(handle).size());
  17871. }
  17872. TEST_F(OpenStreamTest, ConnectionError) {
  17873. Client cli("127.0.0.1", 9999);
  17874. auto handle = cli.open_stream("GET", "/hello");
  17875. EXPECT_FALSE(handle.is_valid());
  17876. }
  17877. TEST_F(OpenStreamTest, Chunked) {
  17878. Client cli("127.0.0.1", port_);
  17879. auto handle = cli.open_stream("GET", "/chunked");
  17880. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17881. "Transfer-Encoding") == "chunked");
  17882. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17883. }
  17884. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17885. Client cli("127.0.0.1", port_);
  17886. auto handle =
  17887. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17888. ASSERT_TRUE(handle.is_valid());
  17889. // Consume body to allow trailers to be received/parsed
  17890. auto body = read_all(handle);
  17891. // Explicitly parse trailers (ensure trailers are available for assertion)
  17892. handle.parse_trailers_if_needed();
  17893. EXPECT_EQ(std::string("123456789"), body);
  17894. // The response should include a Trailer header declaring both names
  17895. ASSERT_TRUE(handle.response);
  17896. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17897. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17898. handle.response->get_header_value("Trailer"));
  17899. // Prohibited trailer must not be present
  17900. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17901. // Allowed trailer should be present
  17902. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17903. EXPECT_EQ(std::string("yes"),
  17904. handle.response->get_trailer_value("X-Allowed"));
  17905. // Verify trailers are NOT present as regular headers
  17906. EXPECT_EQ(std::string(""),
  17907. handle.response->get_header_value("Content-Length"));
  17908. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17909. }
  17910. static std::thread serve_single_response(std::promise<int> &port_promise,
  17911. const std::string &response) {
  17912. return std::thread([&port_promise, response] {
  17913. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17914. default_socket_options(srv);
  17915. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17916. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17917. sockaddr_in addr{};
  17918. addr.sin_family = AF_INET;
  17919. addr.sin_port = htons(0); // Let OS assign a free port
  17920. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17921. int opt = 1;
  17922. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17923. #ifdef _WIN32
  17924. reinterpret_cast<const char *>(&opt),
  17925. #else
  17926. &opt,
  17927. #endif
  17928. sizeof(opt));
  17929. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17930. ::listen(srv, 1) != 0) {
  17931. port_promise.set_value(-1);
  17932. detail::close_socket(srv);
  17933. return;
  17934. }
  17935. socklen_t addr_len = sizeof(addr);
  17936. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17937. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17938. sockaddr_in cli_addr{};
  17939. socklen_t cli_len = sizeof(cli_addr);
  17940. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17941. if (cli != INVALID_SOCKET) {
  17942. // Read the complete HTTP request (until the blank line that terminates
  17943. // headers) before sending the response. If the server closes the socket
  17944. // while the client's request data is still unread in the kernel receive
  17945. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17946. // connection on both sides: it discards the client's receive buffer
  17947. // (which already holds our response) and causes any in-progress write on
  17948. // the client to fail with ECONNRESET. Reading all request data first
  17949. // ensures close() emits a graceful FIN.
  17950. {
  17951. char rbuf[256];
  17952. std::string req;
  17953. while (req.find("\r\n\r\n") == std::string::npos) {
  17954. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17955. if (n <= 0) { break; }
  17956. req.append(rbuf, static_cast<size_t>(n));
  17957. }
  17958. }
  17959. ::send(cli,
  17960. #ifdef _WIN32
  17961. static_cast<const char *>(response.c_str()),
  17962. static_cast<int>(response.size()),
  17963. #else
  17964. response.c_str(), response.size(),
  17965. #endif
  17966. 0);
  17967. detail::close_socket(cli);
  17968. }
  17969. detail::close_socket(srv);
  17970. });
  17971. }
  17972. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17973. #ifndef _WIN32
  17974. signal(SIGPIPE, SIG_IGN);
  17975. #endif
  17976. std::promise<int> port_promise;
  17977. auto port_future = port_promise.get_future();
  17978. auto server_thread =
  17979. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17980. "Content-Type: text/plain\r\n"
  17981. "Content-Length: not-a-number\r\n"
  17982. "Connection: close\r\n"
  17983. "\r\n"
  17984. "hello");
  17985. auto port = port_future.get();
  17986. ASSERT_GT(port, 0);
  17987. Client cli("127.0.0.1", port);
  17988. auto handle = cli.open_stream("GET", "/");
  17989. EXPECT_FALSE(handle.is_valid());
  17990. server_thread.join();
  17991. }
  17992. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17993. #ifndef _WIN32
  17994. signal(SIGPIPE, SIG_IGN);
  17995. #endif
  17996. std::promise<int> port_promise;
  17997. auto port_future = port_promise.get_future();
  17998. auto server_thread = serve_single_response(
  17999. port_promise, "HTTP/1.1 200 OK\r\n"
  18000. "Content-Type: text/plain\r\n"
  18001. "Content-Length: 99999999999999999999999999\r\n"
  18002. "Connection: close\r\n"
  18003. "\r\n"
  18004. "hello");
  18005. auto port = port_future.get();
  18006. ASSERT_GT(port, 0);
  18007. // Historically std::stoull would throw std::out_of_range here and crash
  18008. // the process, then parsing silently clamped to a bogus framing length and
  18009. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18010. // so the stream fails to open, matching the not-a-number case above. The
  18011. // process still must NOT terminate.
  18012. Client cli("127.0.0.1", port);
  18013. auto handle = cli.open_stream("GET", "/");
  18014. EXPECT_FALSE(handle.is_valid());
  18015. server_thread.join();
  18016. }
  18017. // Serves `response` to the single request `fn` makes with a fresh client.
  18018. template <typename Fn>
  18019. static void with_single_response(const std::string &response, Fn fn) {
  18020. #ifndef _WIN32
  18021. signal(SIGPIPE, SIG_IGN);
  18022. #endif
  18023. std::promise<int> port_promise;
  18024. auto port_future = port_promise.get_future();
  18025. auto server_thread = serve_single_response(port_promise, response);
  18026. auto se = detail::scope_exit([&] { server_thread.join(); });
  18027. auto port = port_future.get();
  18028. ASSERT_GT(port, 0);
  18029. Client cli("127.0.0.1", port);
  18030. fn(cli);
  18031. }
  18032. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18033. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18034. // the chunked coding and drop Content-Length, so a front-end that trusts
  18035. // Content-Length would disagree about where the body ends (response
  18036. // smuggling). The client must reject such a response.
  18037. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18038. for (const char *te : {"chunked", "gzip, chunked"}) {
  18039. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18040. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18041. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18042. "5\r\nhello\r\n0\r\n\r\n";
  18043. with_single_response(response, [&](Client &cli) {
  18044. auto res = cli.Get("/");
  18045. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18046. EXPECT_EQ(Error::Read, res.error()) << te;
  18047. });
  18048. with_single_response(response, [&](Client &cli) {
  18049. auto handle = cli.open_stream("GET", "/");
  18050. EXPECT_FALSE(handle.is_valid()) << te;
  18051. EXPECT_EQ(Error::Read, handle.error) << te;
  18052. });
  18053. }
  18054. }
  18055. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18056. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18057. // closing the connection (unlike a request, which must be rejected).
  18058. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18059. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18060. "Transfer-Encoding: chunked\r\n"
  18061. "Connection: close\r\n"
  18062. "\r\n"
  18063. "5\r\nhello\r\n0\r\n\r\n",
  18064. "HTTP/1.1 200 OK\r\n"
  18065. "Transfer-Encoding: gzip\r\n"
  18066. "Connection: close\r\n"
  18067. "\r\n"
  18068. "hello"}) {
  18069. with_single_response(response, [&](Client &cli) {
  18070. auto res = cli.Get("/");
  18071. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18072. EXPECT_EQ("hello", res->body);
  18073. });
  18074. with_single_response(response, [&](Client &cli) {
  18075. auto handle = cli.open_stream("GET", "/");
  18076. ASSERT_TRUE(handle.is_valid()) << response;
  18077. EXPECT_EQ("hello", read_all(handle));
  18078. });
  18079. }
  18080. }
  18081. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18082. // framing headers describe nothing to read and must not be rejected.
  18083. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18084. const std::string framing = "Content-Length: 5\r\n"
  18085. "Transfer-Encoding: chunked\r\n"
  18086. "Connection: close\r\n"
  18087. "\r\n";
  18088. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18089. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18090. });
  18091. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18092. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18093. });
  18094. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18095. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18096. with_single_response(response, [&](Client &cli) {
  18097. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18098. });
  18099. with_single_response(response, [&](Client &cli) {
  18100. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18101. });
  18102. }
  18103. }
  18104. // A payload max length of 0 means no limit, however the body is framed.
  18105. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18106. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18107. "Transfer-Encoding: chunked\r\n"
  18108. "\r\n"
  18109. "5\r\nhello\r\n0\r\n\r\n",
  18110. "HTTP/1.1 200 OK\r\n"
  18111. "Connection: close\r\n"
  18112. "\r\n"
  18113. "hello"}) {
  18114. with_single_response(response, [&](Client &cli) {
  18115. cli.set_payload_max_length(0);
  18116. auto res = cli.Get("/");
  18117. ASSERT_TRUE(res) << response;
  18118. EXPECT_EQ("hello", res->body) << response;
  18119. });
  18120. }
  18121. }
  18122. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18123. Server svr;
  18124. svr.set_payload_max_length(0);
  18125. svr.Post("/echo", [](const Request &req, Response &res) {
  18126. res.set_content(req.body, "text/plain");
  18127. });
  18128. auto port = svr.bind_to_any_port(HOST);
  18129. thread t = thread([&] { svr.listen_after_bind(); });
  18130. auto se = detail::scope_exit([&] {
  18131. svr.stop();
  18132. t.join();
  18133. ASSERT_FALSE(svr.is_running());
  18134. });
  18135. svr.wait_until_ready();
  18136. Client cli(HOST, port);
  18137. auto res = cli.Post(
  18138. "/echo",
  18139. [](size_t /*offset*/, DataSink &sink) {
  18140. sink.write("hello", 5);
  18141. sink.done();
  18142. return true;
  18143. },
  18144. "text/plain");
  18145. ASSERT_TRUE(res);
  18146. EXPECT_EQ(StatusCode::OK_200, res->status);
  18147. EXPECT_EQ("hello", res->body);
  18148. }
  18149. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18150. TEST_F(OpenStreamTest, Gzip) {
  18151. Client cli("127.0.0.1", port_);
  18152. auto handle = cli.open_stream("GET", "/compressible", {},
  18153. {{"Accept-Encoding", "gzip"}});
  18154. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18155. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18156. }
  18157. #endif
  18158. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18159. TEST_F(OpenStreamTest, Brotli) {
  18160. Client cli("127.0.0.1", port_);
  18161. auto handle =
  18162. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18163. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18164. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18165. }
  18166. #endif
  18167. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18168. TEST_F(OpenStreamTest, Zstd) {
  18169. Client cli("127.0.0.1", port_);
  18170. auto handle = cli.open_stream("GET", "/compressible", {},
  18171. {{"Accept-Encoding", "zstd"}});
  18172. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18173. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18174. }
  18175. #endif
  18176. #ifdef CPPHTTPLIB_SSL_ENABLED
  18177. class SSLOpenStreamTest : public ::testing::Test {
  18178. protected:
  18179. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18180. void SetUp() override {
  18181. svr_.Get("/hello", [](const Request &, Response &res) {
  18182. res.set_content("Hello SSL World!", "text/plain");
  18183. });
  18184. svr_.Get("/chunked", [](const Request &, Response &res) {
  18185. res.set_chunked_content_provider("text/plain",
  18186. [](size_t offset, DataSink &sink) {
  18187. if (offset < 15) {
  18188. sink.write("chunk", 5);
  18189. return true;
  18190. }
  18191. sink.done();
  18192. return true;
  18193. });
  18194. });
  18195. svr_.Post("/echo", [](const Request &req, Response &res) {
  18196. res.set_content(req.body, req.get_header_value("Content-Type"));
  18197. });
  18198. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18199. std::string body = req.body;
  18200. res.set_chunked_content_provider(
  18201. "text/plain", [body](size_t offset, DataSink &sink) {
  18202. if (offset < body.size()) {
  18203. sink.write(body.data() + offset, body.size() - offset);
  18204. }
  18205. sink.done();
  18206. return true;
  18207. });
  18208. });
  18209. port_ = svr_.bind_to_any_port("127.0.0.1");
  18210. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18211. svr_.wait_until_ready();
  18212. }
  18213. void TearDown() override {
  18214. svr_.stop();
  18215. if (thread_.joinable()) thread_.join();
  18216. }
  18217. SSLServer svr_;
  18218. std::thread thread_;
  18219. int port_ = 0;
  18220. };
  18221. TEST_F(SSLOpenStreamTest, Basic) {
  18222. SSLClient cli("127.0.0.1", port_);
  18223. cli.enable_server_certificate_verification(false);
  18224. auto handle = cli.open_stream("GET", "/hello");
  18225. ASSERT_TRUE(handle.is_valid());
  18226. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18227. }
  18228. TEST_F(SSLOpenStreamTest, Chunked) {
  18229. SSLClient cli("127.0.0.1", port_);
  18230. cli.enable_server_certificate_verification(false);
  18231. auto handle = cli.open_stream("GET", "/chunked");
  18232. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18233. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18234. "Transfer-Encoding") == "chunked");
  18235. auto body = read_all(handle);
  18236. EXPECT_EQ("chunkchunkchunk", body);
  18237. }
  18238. TEST_F(SSLOpenStreamTest, Post) {
  18239. SSLClient cli("127.0.0.1", port_);
  18240. cli.enable_server_certificate_verification(false);
  18241. auto handle =
  18242. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18243. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18244. EXPECT_EQ(200, handle.response->status);
  18245. auto body = read_all(handle);
  18246. EXPECT_EQ("Hello SSL POST", body);
  18247. }
  18248. TEST_F(SSLOpenStreamTest, PostChunked) {
  18249. SSLClient cli("127.0.0.1", port_);
  18250. cli.enable_server_certificate_verification(false);
  18251. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18252. "Chunked SSL Data", "text/plain");
  18253. ASSERT_TRUE(handle.is_valid());
  18254. EXPECT_EQ(200, handle.response->status);
  18255. auto body = read_all(handle);
  18256. EXPECT_EQ("Chunked SSL Data", body);
  18257. }
  18258. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18259. // Content-Length is terminated by the server closing the connection. When the
  18260. // SSL peer sends a close_notify after the body, the client must treat it as a
  18261. // clean EOF and return a successful response rather than an error.
  18262. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18264. ASSERT_TRUE(svr.is_valid());
  18265. svr.set_keep_alive_max_count(1);
  18266. const std::string expected_body = "Hello from connection-close response!";
  18267. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18268. res.set_content_provider("text/plain",
  18269. [&](size_t offset, DataSink &sink) -> bool {
  18270. if (offset < expected_body.size()) {
  18271. sink.write(expected_body.data() + offset,
  18272. expected_body.size() - offset);
  18273. }
  18274. sink.done();
  18275. return true;
  18276. });
  18277. });
  18278. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18279. auto se = detail::scope_exit([&] {
  18280. svr.stop();
  18281. listen_thread.join();
  18282. ASSERT_FALSE(svr.is_running());
  18283. });
  18284. svr.wait_until_ready();
  18285. SSLClient cli(HOST, PORT);
  18286. cli.enable_server_certificate_verification(false);
  18287. auto res = cli.Get("/no-content-length");
  18288. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18289. EXPECT_EQ(StatusCode::OK_200, res->status);
  18290. EXPECT_EQ(expected_body, res->body);
  18291. }
  18292. #endif // CPPHTTPLIB_SSL_ENABLED
  18293. //==============================================================================
  18294. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18295. // results for various scenarios.
  18296. //==============================================================================
  18297. TEST(ParityTest, GetVsOpenStream) {
  18298. Server svr;
  18299. const std::string path = "/parity";
  18300. const std::string content = "Parity test content: hello world";
  18301. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18302. res.set_content(content, "text/plain");
  18303. });
  18304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18305. auto se = detail::scope_exit([&] {
  18306. svr.stop();
  18307. t.join();
  18308. ASSERT_FALSE(svr.is_running());
  18309. });
  18310. svr.wait_until_ready();
  18311. Client cli(HOST, PORT);
  18312. // Non-stream path
  18313. auto r1 = cli.Get(path);
  18314. ASSERT_TRUE(r1);
  18315. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18316. // Stream path
  18317. auto h = cli.open_stream("GET", path);
  18318. ASSERT_TRUE(h.is_valid());
  18319. EXPECT_EQ(r1->body, read_all(h));
  18320. }
  18321. // Helper to compress data with provided compressor type T
  18322. template <typename Compressor>
  18323. static std::string compress_payload_for_parity(const std::string &in) {
  18324. std::string out;
  18325. Compressor compressor;
  18326. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18327. [&](const char *data, size_t n) {
  18328. out.append(data, n);
  18329. return true;
  18330. });
  18331. EXPECT_TRUE(ok);
  18332. return out;
  18333. }
  18334. // Helper function for compression parity tests
  18335. template <typename Compressor>
  18336. static void test_compression_parity(const std::string &original,
  18337. const std::string &path,
  18338. const std::string &encoding) {
  18339. const std::string compressed =
  18340. compress_payload_for_parity<Compressor>(original);
  18341. Server svr;
  18342. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18343. res.set_content(compressed, "application/octet-stream");
  18344. res.set_header("Content-Encoding", encoding);
  18345. });
  18346. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18347. auto se = detail::scope_exit([&] {
  18348. svr.stop();
  18349. t.join();
  18350. ASSERT_FALSE(svr.is_running());
  18351. });
  18352. svr.wait_until_ready();
  18353. Client cli(HOST, PORT);
  18354. // Non-streaming
  18355. {
  18356. auto res = cli.Get(path);
  18357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18358. EXPECT_EQ(StatusCode::OK_200, res->status);
  18359. EXPECT_EQ(original, res->body);
  18360. }
  18361. // Streaming
  18362. {
  18363. auto h = cli.open_stream("GET", path);
  18364. ASSERT_TRUE(h.is_valid());
  18365. EXPECT_EQ(original, read_all(h));
  18366. }
  18367. }
  18368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18369. TEST(ParityTest, Gzip) {
  18370. test_compression_parity<detail::gzip_compressor>(
  18371. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18372. }
  18373. #endif
  18374. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18375. TEST(ParityTest, Brotli) {
  18376. test_compression_parity<detail::brotli_compressor>(
  18377. "Hello, brotli parity test payload", "/parity-br", "br");
  18378. }
  18379. #endif
  18380. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18381. TEST(ParityTest, Zstd) {
  18382. test_compression_parity<detail::zstd_compressor>(
  18383. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18384. }
  18385. #endif
  18386. //==============================================================================
  18387. // New Stream API Tests
  18388. //==============================================================================
  18389. inline std::string read_body(httplib::stream::Result &result) {
  18390. std::string body;
  18391. while (result.next()) {
  18392. body.append(result.data(), result.size());
  18393. }
  18394. return body;
  18395. }
  18396. TEST(ClientConnectionTest, Basic) {
  18397. httplib::ClientConnection conn;
  18398. EXPECT_FALSE(conn.is_open());
  18399. conn.sock = 1;
  18400. EXPECT_TRUE(conn.is_open());
  18401. httplib::ClientConnection conn2(std::move(conn));
  18402. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18403. conn2.sock = INVALID_SOCKET;
  18404. }
  18405. // Unified test server for all stream::* tests
  18406. class StreamApiTest : public ::testing::Test {
  18407. protected:
  18408. void SetUp() override {
  18409. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18410. res.set_content("Hello World!", "text/plain");
  18411. });
  18412. svr_.Get("/echo-params",
  18413. [](const httplib::Request &req, httplib::Response &res) {
  18414. std::string r;
  18415. for (const auto &p : req.params) {
  18416. if (!r.empty()) r += "&";
  18417. r += p.first + "=" + p.second;
  18418. }
  18419. res.set_content(r, "text/plain");
  18420. });
  18421. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18422. res.set_content(req.body, req.get_header_value("Content-Type"));
  18423. });
  18424. svr_.Post("/echo-headers",
  18425. [](const httplib::Request &req, httplib::Response &res) {
  18426. std::string r;
  18427. for (const auto &h : req.headers)
  18428. r += h.first + ": " + h.second + "\n";
  18429. res.set_content(r, "text/plain");
  18430. });
  18431. svr_.Post("/echo-params",
  18432. [](const httplib::Request &req, httplib::Response &res) {
  18433. std::string r = "params:";
  18434. for (const auto &p : req.params)
  18435. r += p.first + "=" + p.second + ";";
  18436. res.set_content(r + " body:" + req.body, "text/plain");
  18437. });
  18438. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18439. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18440. });
  18441. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18442. res.set_content("PUT:" + req.body, "text/plain");
  18443. });
  18444. svr_.Patch("/echo",
  18445. [](const httplib::Request &req, httplib::Response &res) {
  18446. res.set_content("PATCH:" + req.body, "text/plain");
  18447. });
  18448. svr_.Delete(
  18449. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18450. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18451. "text/plain");
  18452. });
  18453. svr_.Get("/head-test",
  18454. [](const httplib::Request &, httplib::Response &res) {
  18455. res.set_content("body for HEAD", "text/plain");
  18456. });
  18457. svr_.Options("/options",
  18458. [](const httplib::Request &, httplib::Response &res) {
  18459. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18460. });
  18461. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18462. svr_.wait_until_ready();
  18463. }
  18464. void TearDown() override {
  18465. svr_.stop();
  18466. if (thread_.joinable()) thread_.join();
  18467. }
  18468. httplib::Server svr_;
  18469. std::thread thread_;
  18470. };
  18471. // stream::Get tests
  18472. TEST_F(StreamApiTest, GetBasic) {
  18473. httplib::Client cli(HOST, PORT);
  18474. auto result = httplib::stream::Get(cli, "/hello");
  18475. ASSERT_TRUE(result.is_valid());
  18476. EXPECT_EQ(200, result.status());
  18477. EXPECT_EQ("Hello World!", read_body(result));
  18478. }
  18479. TEST_F(StreamApiTest, GetWithParams) {
  18480. httplib::Client cli(HOST, PORT);
  18481. httplib::Params params{{"foo", "bar"}};
  18482. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18483. ASSERT_TRUE(result.is_valid());
  18484. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18485. }
  18486. TEST_F(StreamApiTest, GetConnectionError) {
  18487. httplib::Client cli(HOST, 9999);
  18488. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18489. }
  18490. TEST_F(StreamApiTest, Get404) {
  18491. httplib::Client cli(HOST, PORT);
  18492. auto result = httplib::stream::Get(cli, "/nonexistent");
  18493. EXPECT_TRUE(result.is_valid());
  18494. EXPECT_EQ(404, result.status());
  18495. }
  18496. // stream::Post tests
  18497. TEST_F(StreamApiTest, PostBasic) {
  18498. httplib::Client cli(HOST, PORT);
  18499. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18500. "application/json");
  18501. ASSERT_TRUE(result.is_valid());
  18502. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18503. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18504. }
  18505. TEST_F(StreamApiTest, PostWithHeaders) {
  18506. httplib::Client cli(HOST, PORT);
  18507. httplib::Headers headers{{"X-Custom", "value"}};
  18508. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18509. "text/plain");
  18510. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18511. }
  18512. TEST_F(StreamApiTest, PostWithParams) {
  18513. httplib::Client cli(HOST, PORT);
  18514. httplib::Params params{{"k", "v"}};
  18515. auto result =
  18516. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18517. auto body = read_body(result);
  18518. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18519. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18520. }
  18521. TEST_F(StreamApiTest, PostLarge) {
  18522. httplib::Client cli(HOST, PORT);
  18523. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18524. size_t total = 0;
  18525. while (result.next()) {
  18526. total += result.size();
  18527. }
  18528. EXPECT_EQ(100u * 1024u, total);
  18529. }
  18530. // stream::Put/Patch tests
  18531. TEST_F(StreamApiTest, PutAndPatch) {
  18532. httplib::Client cli(HOST, PORT);
  18533. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18534. EXPECT_EQ("PUT:test", read_body(put));
  18535. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18536. EXPECT_EQ("PATCH:test", read_body(patch));
  18537. }
  18538. // stream::Delete tests
  18539. TEST_F(StreamApiTest, Delete) {
  18540. httplib::Client cli(HOST, PORT);
  18541. auto del1 = httplib::stream::Delete(cli, "/resource");
  18542. EXPECT_EQ("Deleted", read_body(del1));
  18543. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18544. EXPECT_EQ("Deleted:data", read_body(del2));
  18545. }
  18546. // stream::Head/Options tests
  18547. TEST_F(StreamApiTest, HeadAndOptions) {
  18548. httplib::Client cli(HOST, PORT);
  18549. auto head = httplib::stream::Head(cli, "/head-test");
  18550. EXPECT_TRUE(head.is_valid());
  18551. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18552. auto opts = httplib::stream::Options(cli, "/options");
  18553. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18554. }
  18555. // SSL stream::* tests
  18556. #ifdef CPPHTTPLIB_SSL_ENABLED
  18557. class SSLStreamApiTest : public ::testing::Test {
  18558. protected:
  18559. void SetUp() override {
  18560. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18561. res.set_content("Hello SSL!", "text/plain");
  18562. });
  18563. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18564. res.set_content(req.body, "text/plain");
  18565. });
  18566. port_ = svr_.bind_to_any_port("127.0.0.1");
  18567. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18568. svr_.wait_until_ready();
  18569. }
  18570. void TearDown() override {
  18571. svr_.stop();
  18572. if (thread_.joinable()) thread_.join();
  18573. }
  18574. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18575. std::thread thread_;
  18576. int port_ = 0;
  18577. };
  18578. TEST_F(SSLStreamApiTest, GetAndPost) {
  18579. httplib::SSLClient cli("127.0.0.1", port_);
  18580. cli.enable_server_certificate_verification(false);
  18581. auto get = httplib::stream::Get(cli, "/hello");
  18582. EXPECT_EQ("Hello SSL!", read_body(get));
  18583. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18584. EXPECT_EQ("test", read_body(post));
  18585. }
  18586. #endif
  18587. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18588. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18589. // BodyReader
  18590. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18591. // Test that read timeout during streaming is detected
  18592. // Use a large content-length response where server delays mid-stream
  18593. Server svr;
  18594. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18595. // Send a large response with delay in the middle
  18596. res.set_content_provider(
  18597. 1000, // content_length
  18598. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18599. if (offset < 100) {
  18600. // Send first 100 bytes immediately
  18601. std::string data(100, 'A');
  18602. sink.write(data.c_str(), data.size());
  18603. return true;
  18604. }
  18605. // Then delay longer than client timeout
  18606. std::this_thread::sleep_for(std::chrono::seconds(3));
  18607. std::string data(900, 'B');
  18608. sink.write(data.c_str(), data.size());
  18609. return true;
  18610. });
  18611. });
  18612. auto port = 8091;
  18613. std::thread t([&]() { svr.listen("localhost", port); });
  18614. svr.wait_until_ready();
  18615. Client cli("localhost", port);
  18616. cli.set_read_timeout(1, 0); // 1 second timeout
  18617. auto handle = cli.open_stream("GET", "/slow-stream");
  18618. ASSERT_TRUE(handle.is_valid());
  18619. char buf[256];
  18620. ssize_t total = 0;
  18621. ssize_t n;
  18622. bool got_error = false;
  18623. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18624. total += n;
  18625. }
  18626. if (n < 0) {
  18627. got_error = true;
  18628. // Should be timeout or read error
  18629. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18630. handle.get_read_error() == Error::Read)
  18631. << "Actual error: " << to_string(handle.get_read_error());
  18632. }
  18633. // Either we got an error, or we got less data than expected
  18634. EXPECT_TRUE(got_error || total < 1000)
  18635. << "Expected timeout but got all " << total << " bytes";
  18636. svr.stop();
  18637. t.join();
  18638. }
  18639. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18640. // Test connection closed detection via BodyReader
  18641. Server svr;
  18642. std::atomic<bool> close_now{false};
  18643. svr.Get("/will-close", [&](const Request &, Response &res) {
  18644. res.set_content_provider(
  18645. 10000, // Large content_length that we won't fully send
  18646. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18647. if (offset < 100) {
  18648. std::string data(100, 'X');
  18649. sink.write(data.c_str(), data.size());
  18650. return true;
  18651. }
  18652. // Wait for signal then abort
  18653. while (!close_now) {
  18654. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18655. }
  18656. return false; // Abort - server will close connection
  18657. });
  18658. });
  18659. auto port = 8092;
  18660. std::thread t([&]() { svr.listen("localhost", port); });
  18661. svr.wait_until_ready();
  18662. Client cli("localhost", port);
  18663. auto handle = cli.open_stream("GET", "/will-close");
  18664. ASSERT_TRUE(handle.is_valid());
  18665. char buf[256];
  18666. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18667. EXPECT_GT(n, 0) << "First read should succeed";
  18668. // Signal server to close
  18669. close_now = true;
  18670. // Keep reading until error or EOF
  18671. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18672. // Keep reading
  18673. }
  18674. // Should get an error since content_length wasn't satisfied
  18675. if (n < 0) {
  18676. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18677. handle.get_read_error() == Error::Read)
  18678. << "Actual error: " << to_string(handle.get_read_error());
  18679. }
  18680. svr.stop();
  18681. t.join();
  18682. }
  18683. #ifdef CPPHTTPLIB_SSL_ENABLED
  18684. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18685. // Test that read timeout during SSL streaming is detected
  18686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18687. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18688. res.set_content_provider(
  18689. 1000, "text/plain",
  18690. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18691. if (offset < 100) {
  18692. std::string data(100, 'A');
  18693. sink.write(data.c_str(), data.size());
  18694. return true;
  18695. }
  18696. std::this_thread::sleep_for(std::chrono::seconds(3));
  18697. std::string data(900, 'B');
  18698. sink.write(data.c_str(), data.size());
  18699. return true;
  18700. });
  18701. });
  18702. auto port = 8093;
  18703. std::thread t([&]() { svr.listen("localhost", port); });
  18704. svr.wait_until_ready();
  18705. SSLClient cli("localhost", port);
  18706. cli.enable_server_certificate_verification(false);
  18707. cli.set_read_timeout(1, 0); // 1 second timeout
  18708. auto handle = cli.open_stream("GET", "/slow-stream");
  18709. ASSERT_TRUE(handle.is_valid());
  18710. char buf[256];
  18711. ssize_t total = 0;
  18712. ssize_t n;
  18713. bool got_error = false;
  18714. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18715. total += n;
  18716. }
  18717. if (n < 0) {
  18718. got_error = true;
  18719. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18720. handle.get_read_error() == Error::Read)
  18721. << "Actual error: " << to_string(handle.get_read_error());
  18722. }
  18723. EXPECT_TRUE(got_error || total < 1000)
  18724. << "Expected timeout but got all " << total << " bytes";
  18725. svr.stop();
  18726. t.join();
  18727. }
  18728. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18729. // Test SSL connection closed detection
  18730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18731. std::atomic<bool> close_now{false};
  18732. svr.Get("/will-close", [&](const Request &, Response &res) {
  18733. res.set_content_provider(
  18734. 10000, "text/plain",
  18735. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18736. if (offset < 100) {
  18737. std::string data(100, 'X');
  18738. sink.write(data.c_str(), data.size());
  18739. return true;
  18740. }
  18741. while (!close_now) {
  18742. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18743. }
  18744. return false;
  18745. });
  18746. });
  18747. auto port = 8094;
  18748. std::thread t([&]() { svr.listen("localhost", port); });
  18749. svr.wait_until_ready();
  18750. SSLClient cli("localhost", port);
  18751. cli.enable_server_certificate_verification(false);
  18752. auto handle = cli.open_stream("GET", "/will-close");
  18753. ASSERT_TRUE(handle.is_valid());
  18754. char buf[256];
  18755. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18756. EXPECT_GT(n, 0);
  18757. // Signal server to close
  18758. close_now = true;
  18759. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18760. // Keep reading
  18761. }
  18762. if (n < 0) {
  18763. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18764. handle.get_read_error() == Error::Read)
  18765. << "Actual error: " << to_string(handle.get_read_error());
  18766. }
  18767. svr.stop();
  18768. t.join();
  18769. }
  18770. #endif
  18771. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18772. using namespace httplib;
  18773. // Create a test file
  18774. const char *fname = "etag_testfile.txt";
  18775. const char *content = "etag-content";
  18776. {
  18777. std::ofstream ofs(fname);
  18778. ofs << content;
  18779. ASSERT_TRUE(ofs.good());
  18780. }
  18781. Server svr;
  18782. svr.set_mount_point("/static", ".");
  18783. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18784. svr.wait_until_ready();
  18785. Client cli(HOST, PORT);
  18786. // First request: should get 200 with ETag header
  18787. auto res1 = cli.Get("/static/etag_testfile.txt");
  18788. ASSERT_TRUE(res1);
  18789. ASSERT_EQ(200, res1->status);
  18790. ASSERT_TRUE(res1->has_header("ETag"));
  18791. std::string etag = res1->get_header_value("ETag");
  18792. EXPECT_FALSE(etag.empty());
  18793. // Verify ETag format: W/"hex-hex"
  18794. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18795. EXPECT_EQ('W', etag[0]);
  18796. EXPECT_EQ('/', etag[1]);
  18797. EXPECT_EQ('"', etag[2]);
  18798. EXPECT_EQ('"', etag.back());
  18799. // Exact match: expect 304 Not Modified
  18800. Headers h2 = {{"If-None-Match", etag}};
  18801. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18802. ASSERT_TRUE(res2);
  18803. EXPECT_EQ(304, res2->status);
  18804. // Wildcard match: expect 304 Not Modified
  18805. Headers h3 = {{"If-None-Match", "*"}};
  18806. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18807. ASSERT_TRUE(res3);
  18808. EXPECT_EQ(304, res3->status);
  18809. // Non-matching ETag: expect 200
  18810. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18811. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18812. ASSERT_TRUE(res4);
  18813. EXPECT_EQ(200, res4->status);
  18814. // Multiple ETags with one matching: expect 304
  18815. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18816. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18817. ASSERT_TRUE(res5);
  18818. EXPECT_EQ(304, res5->status);
  18819. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18820. // that equivalent to the single comma-separated list above, so the match on
  18821. // the second line must still be found.
  18822. Headers h6;
  18823. h6.emplace("If-None-Match", "W/\"other\"");
  18824. h6.emplace("If-None-Match", etag);
  18825. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18826. ASSERT_TRUE(res6);
  18827. EXPECT_EQ(304, res6->status);
  18828. svr.stop();
  18829. t.join();
  18830. std::remove(fname);
  18831. }
  18832. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18833. using namespace httplib;
  18834. Server svr;
  18835. svr.set_mount_point("/static", ".");
  18836. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18837. svr.wait_until_ready();
  18838. Client cli(HOST, PORT);
  18839. // Send If-None-Match: * to a non-existent file
  18840. Headers h = {{"If-None-Match", "*"}};
  18841. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18843. EXPECT_EQ(404, res->status);
  18844. svr.stop();
  18845. t.join();
  18846. }
  18847. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18848. using namespace httplib;
  18849. // Create a test file
  18850. const char *fname = "etag_boundary_testfile.txt";
  18851. const char *content = "boundary-test";
  18852. {
  18853. std::ofstream ofs(fname);
  18854. ofs << content;
  18855. ASSERT_TRUE(ofs.good());
  18856. }
  18857. Server svr;
  18858. svr.set_mount_point("/static", ".");
  18859. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18860. svr.wait_until_ready();
  18861. Client cli(HOST, PORT);
  18862. // Get the actual ETag
  18863. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18864. ASSERT_TRUE(res1);
  18865. ASSERT_EQ(200, res1->status);
  18866. ASSERT_TRUE(res1->has_header("ETag"));
  18867. std::string etag = res1->get_header_value("ETag");
  18868. // Test 1: Very long ETag value (longer than actual ETag)
  18869. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18870. Headers h1 = {{"If-None-Match", "W/"
  18871. "\"very-long-etag-value-that-is-much-longer-"
  18872. "than-the-actual-etag-value\""}};
  18873. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18874. ASSERT_TRUE(res2);
  18875. EXPECT_EQ(200, res2->status); // Should not match
  18876. // Test 2: Long string followed by wildcard
  18877. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18878. // string)
  18879. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18880. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18881. ASSERT_TRUE(res3);
  18882. EXPECT_EQ(304, res3->status); // Should match on "*"
  18883. // Test 3: Wildcard followed by long string
  18884. // Should match on "*" immediately and return 304
  18885. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18886. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18887. ASSERT_TRUE(res4);
  18888. EXPECT_EQ(304, res4->status); // Should match on "*"
  18889. // Test 4: Multiple long non-matching values
  18890. // Should NOT match and return 200 (test that all comparisons are safe)
  18891. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18892. "W/\"second-long-non-matching-value\", "
  18893. "W/\"third-long-non-matching-value\""}};
  18894. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18895. ASSERT_TRUE(res5);
  18896. EXPECT_EQ(200, res5->status); // Should not match
  18897. // Test 5: Single character that is not "*" (edge case)
  18898. Headers h5 = {{"If-None-Match", "X"}};
  18899. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18900. ASSERT_TRUE(res6);
  18901. EXPECT_EQ(200, res6->status); // Should not match
  18902. svr.stop();
  18903. t.join();
  18904. std::remove(fname);
  18905. }
  18906. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18907. using namespace httplib;
  18908. // Create a test file
  18909. const char *fname = "ims_testfile.txt";
  18910. const char *content = "if-modified-since-test";
  18911. {
  18912. std::ofstream ofs(fname);
  18913. ofs << content;
  18914. ASSERT_TRUE(ofs.good());
  18915. }
  18916. Server svr;
  18917. svr.set_mount_point("/static", ".");
  18918. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18919. svr.wait_until_ready();
  18920. Client cli(HOST, PORT);
  18921. // First request: should get 200 with Last-Modified header
  18922. auto res1 = cli.Get("/static/ims_testfile.txt");
  18923. ASSERT_TRUE(res1);
  18924. ASSERT_EQ(200, res1->status);
  18925. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18926. std::string last_modified = res1->get_header_value("Last-Modified");
  18927. EXPECT_FALSE(last_modified.empty());
  18928. // If-Modified-Since with same time: expect 304
  18929. Headers h2 = {{"If-Modified-Since", last_modified}};
  18930. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18931. ASSERT_TRUE(res2);
  18932. EXPECT_EQ(304, res2->status);
  18933. // If-Modified-Since with future time: expect 304
  18934. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18935. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18936. ASSERT_TRUE(res3);
  18937. EXPECT_EQ(304, res3->status);
  18938. // If-Modified-Since with past time: expect 200
  18939. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18940. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18941. ASSERT_TRUE(res4);
  18942. EXPECT_EQ(200, res4->status);
  18943. // If-None-Match takes precedence over If-Modified-Since
  18944. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18945. ASSERT_TRUE(res1->has_header("ETag"));
  18946. std::string etag = res1->get_header_value("ETag");
  18947. Headers h5 = {{"If-None-Match", etag},
  18948. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18949. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18950. ASSERT_TRUE(res5);
  18951. EXPECT_EQ(304, res5->status);
  18952. svr.stop();
  18953. t.join();
  18954. std::remove(fname);
  18955. }
  18956. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18957. using namespace httplib;
  18958. Server svr;
  18959. // Endpoint that returns compressible content
  18960. svr.Get("/compressible", [](const Request &, Response &res) {
  18961. // Return a large enough body to trigger compression
  18962. std::string body(1000, 'a');
  18963. res.set_content(body, "text/plain");
  18964. });
  18965. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18966. svr.wait_until_ready();
  18967. Client cli(HOST, PORT);
  18968. // Request with gzip support: should get Vary header when compressed
  18969. cli.set_compress(true);
  18970. auto res1 = cli.Get("/compressible");
  18971. ASSERT_TRUE(res1);
  18972. EXPECT_EQ(200, res1->status);
  18973. // If Content-Encoding is set, Vary should also be set
  18974. if (res1->has_header("Content-Encoding")) {
  18975. EXPECT_TRUE(res1->has_header("Vary"));
  18976. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18977. }
  18978. // Request without Accept-Encoding header: should not have compression
  18979. Headers h_no_compress;
  18980. auto res2 = cli.Get("/compressible", h_no_compress);
  18981. ASSERT_TRUE(res2);
  18982. EXPECT_EQ(200, res2->status);
  18983. // Verify Vary header is present when compression is applied
  18984. // (the exact behavior depends on server configuration)
  18985. svr.stop();
  18986. t.join();
  18987. }
  18988. TEST(ETagTest, IfRangeWithETag) {
  18989. using namespace httplib;
  18990. // Create a test file with known content
  18991. const char *fname = "if_range_testfile.txt";
  18992. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18993. {
  18994. std::ofstream ofs(fname);
  18995. ofs << content;
  18996. ASSERT_TRUE(ofs.good());
  18997. }
  18998. Server svr;
  18999. svr.set_mount_point("/static", ".");
  19000. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19001. svr.wait_until_ready();
  19002. Client cli(HOST, PORT);
  19003. // First request: get ETag
  19004. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19005. ASSERT_TRUE(res1);
  19006. ASSERT_EQ(200, res1->status);
  19007. ASSERT_TRUE(res1->has_header("ETag"));
  19008. std::string etag = res1->get_header_value("ETag");
  19009. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19010. // Since our server generates weak ETags (W/"..."), If-Range with our
  19011. // ETag should NOT result in partial content - it should return full content.
  19012. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19013. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19014. ASSERT_TRUE(res2);
  19015. // Weak ETag in If-Range -> full content (200), not partial (206)
  19016. EXPECT_EQ(200, res2->status);
  19017. EXPECT_EQ(content, res2->body);
  19018. EXPECT_FALSE(res2->has_header("Content-Range"));
  19019. // Range request with non-matching If-Range (ETag): should get 200 (full
  19020. // content)
  19021. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19022. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19023. ASSERT_TRUE(res3);
  19024. EXPECT_EQ(200, res3->status);
  19025. EXPECT_EQ(content, res3->body);
  19026. EXPECT_FALSE(res3->has_header("Content-Range"));
  19027. // Range request with strong ETag (hypothetical - our server doesn't generate
  19028. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19029. // should return full content)
  19030. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19031. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19032. ASSERT_TRUE(res4);
  19033. EXPECT_EQ(200, res4->status);
  19034. EXPECT_EQ(content, res4->body);
  19035. EXPECT_FALSE(res4->has_header("Content-Range"));
  19036. svr.stop();
  19037. t.join();
  19038. std::remove(fname);
  19039. }
  19040. TEST(ETagTest, IfRangeWithDate) {
  19041. using namespace httplib;
  19042. // Create a test file
  19043. const char *fname = "if_range_date_testfile.txt";
  19044. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19045. {
  19046. std::ofstream ofs(fname);
  19047. ofs << content;
  19048. ASSERT_TRUE(ofs.good());
  19049. }
  19050. Server svr;
  19051. svr.set_mount_point("/static", ".");
  19052. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19053. svr.wait_until_ready();
  19054. Client cli(HOST, PORT);
  19055. // First request: get Last-Modified
  19056. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19057. ASSERT_TRUE(res1);
  19058. ASSERT_EQ(200, res1->status);
  19059. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19060. std::string last_modified = res1->get_header_value("Last-Modified");
  19061. // Range request with matching If-Range (date): should get 206
  19062. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19063. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19064. ASSERT_TRUE(res2);
  19065. EXPECT_EQ(206, res2->status);
  19066. EXPECT_EQ("FGHIJ", res2->body);
  19067. // Range request with old If-Range date: should get 200 (full content)
  19068. Headers h3 = {{"Range", "bytes=5-9"},
  19069. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19070. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19071. ASSERT_TRUE(res3);
  19072. EXPECT_EQ(200, res3->status);
  19073. EXPECT_EQ(content, res3->body);
  19074. // Range request with future If-Range date: should get 206
  19075. Headers h4 = {{"Range", "bytes=0-4"},
  19076. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19077. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19078. ASSERT_TRUE(res4);
  19079. EXPECT_EQ(206, res4->status);
  19080. EXPECT_EQ("ABCDE", res4->body);
  19081. svr.stop();
  19082. t.join();
  19083. std::remove(fname);
  19084. }
  19085. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19086. using namespace httplib;
  19087. const char *fname = "etag_malformed.txt";
  19088. const char *content = "malformed-etag";
  19089. {
  19090. std::ofstream ofs(fname);
  19091. ofs << content;
  19092. ASSERT_TRUE(ofs.good());
  19093. }
  19094. Server svr;
  19095. svr.set_mount_point("/static", ".");
  19096. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19097. svr.wait_until_ready();
  19098. Client cli(HOST, PORT);
  19099. // baseline: should get 200 and an ETag
  19100. auto res1 = cli.Get("/static/etag_malformed.txt");
  19101. ASSERT_TRUE(res1);
  19102. ASSERT_EQ(200, res1->status);
  19103. ASSERT_TRUE(res1->has_header("ETag"));
  19104. // Malformed ETag value (missing quotes) should be treated as non-matching
  19105. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19106. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19107. ASSERT_TRUE(res_bad);
  19108. EXPECT_EQ(200, res_bad->status);
  19109. // Whitespace-only header value should be considered invalid / non-matching
  19110. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19111. "Host: localhost\r\n"
  19112. "If-None-Match: \r\n"
  19113. "Connection: close\r\n"
  19114. "\r\n";
  19115. std::string out;
  19116. ASSERT_TRUE(send_request(5, raw_req, &out));
  19117. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19118. svr.stop();
  19119. t.join();
  19120. std::remove(fname);
  19121. }
  19122. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19123. using namespace httplib;
  19124. const char *fname = "ims_invalid_format.txt";
  19125. const char *content = "ims-bad-format";
  19126. {
  19127. std::ofstream ofs(fname);
  19128. ofs << content;
  19129. ASSERT_TRUE(ofs.good());
  19130. }
  19131. Server svr;
  19132. svr.set_mount_point("/static", ".");
  19133. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19134. svr.wait_until_ready();
  19135. Client cli(HOST, PORT);
  19136. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19137. ASSERT_TRUE(res1);
  19138. ASSERT_EQ(200, res1->status);
  19139. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19140. // If-Modified-Since with invalid format should not result in 304
  19141. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19142. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19143. ASSERT_TRUE(res_bad);
  19144. EXPECT_EQ(200, res_bad->status);
  19145. // If-Range with invalid date format should be treated as mismatch -> full
  19146. // content (200)
  19147. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19148. {"If-Range", "invalid-date"}};
  19149. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19150. ASSERT_TRUE(res_ifrange);
  19151. EXPECT_EQ(200, res_ifrange->status);
  19152. svr.stop();
  19153. t.join();
  19154. std::remove(fname);
  19155. }
  19156. TEST(ETagTest, IfRangeWithMalformedETag) {
  19157. using namespace httplib;
  19158. const char *fname = "ifrange_malformed.txt";
  19159. const std::string content = "0123456789";
  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. // First request: get ETag
  19171. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19172. ASSERT_TRUE(res1);
  19173. ASSERT_EQ(200, res1->status);
  19174. ASSERT_TRUE(res1->has_header("ETag"));
  19175. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19176. // full content (200)
  19177. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19178. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19179. ASSERT_TRUE(res2);
  19180. EXPECT_EQ(200, res2->status);
  19181. EXPECT_EQ(content, res2->body);
  19182. svr.stop();
  19183. t.join();
  19184. std::remove(fname);
  19185. }
  19186. TEST(ETagTest, ExtremeLargeDateValues) {
  19187. using namespace httplib;
  19188. const char *fname = "ims_extreme_date.txt";
  19189. const char *content = "ims-extreme-date";
  19190. {
  19191. std::ofstream ofs(fname);
  19192. ofs << content;
  19193. ASSERT_TRUE(ofs.good());
  19194. }
  19195. Server svr;
  19196. svr.set_mount_point("/static", ".");
  19197. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19198. svr.wait_until_ready();
  19199. Client cli(HOST, PORT);
  19200. auto res1 = cli.Get(std::string("/static/") + fname);
  19201. ASSERT_TRUE(res1);
  19202. ASSERT_EQ(200, res1->status);
  19203. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19204. // Extremely large year that may overflow date parsing routines.
  19205. Headers h_large_date = {
  19206. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19207. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19208. ASSERT_TRUE(res_bad);
  19209. // Expect server to treat this as invalid/mismatch and return full content
  19210. EXPECT_EQ(200, res_bad->status);
  19211. // If-Range with extremely large date should be treated as mismatch -> full
  19212. // content (200)
  19213. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19214. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19215. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19216. ASSERT_TRUE(res_ifrange);
  19217. EXPECT_EQ(200, res_ifrange->status);
  19218. svr.stop();
  19219. t.join();
  19220. std::remove(fname);
  19221. }
  19222. TEST(ETagTest, NegativeFileModificationTime) {
  19223. using namespace httplib;
  19224. const char *fname = "ims_negative_mtime.txt";
  19225. const std::string content = "negative-mtime";
  19226. {
  19227. std::ofstream ofs(fname);
  19228. ofs << content;
  19229. ASSERT_TRUE(ofs.good());
  19230. }
  19231. // Try to set file mtime to a negative value. This may fail on some
  19232. // platforms/filesystems; if it fails, the test will still verify server
  19233. // behaves safely by performing a regular conditional request.
  19234. #if defined(__APPLE__) || defined(__linux__)
  19235. bool set_negative = false;
  19236. do {
  19237. struct timeval times[2];
  19238. // access time: now
  19239. times[0].tv_sec = time(nullptr);
  19240. times[0].tv_usec = 0;
  19241. // modification time: negative (e.g., -1)
  19242. times[1].tv_sec = -1;
  19243. times[1].tv_usec = 0;
  19244. if (utimes(fname, times) == 0) { set_negative = true; }
  19245. } while (0);
  19246. #else
  19247. bool set_negative = false;
  19248. #endif
  19249. Server svr;
  19250. svr.set_mount_point("/static", ".");
  19251. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19252. svr.wait_until_ready();
  19253. Client cli(HOST, PORT);
  19254. auto res1 = cli.Get(std::string("/static/") + fname);
  19255. ASSERT_TRUE(res1);
  19256. ASSERT_EQ(200, res1->status);
  19257. bool has_last_modified = res1->has_header("Last-Modified");
  19258. std::string last_modified;
  19259. if (has_last_modified) {
  19260. last_modified = res1->get_header_value("Last-Modified");
  19261. }
  19262. if (set_negative) {
  19263. // If we successfully set a negative mtime, ensure server returns a
  19264. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19265. // with an old date and ensure server handles it without crash.
  19266. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19267. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19268. ASSERT_TRUE(res2);
  19269. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19270. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19271. } else {
  19272. // Could not set negative mtime on this platform; fall back to verifying
  19273. // that normal invalid/malformed dates are treated safely (non-304).
  19274. Headers h_bad_date = {
  19275. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19276. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19277. ASSERT_TRUE(res_bad);
  19278. EXPECT_EQ(200, res_bad->status);
  19279. }
  19280. svr.stop();
  19281. t.join();
  19282. std::remove(fname);
  19283. }
  19284. //==============================================================================
  19285. // Integration Tests with Server
  19286. //==============================================================================
  19287. class SSEIntegrationTest : public ::testing::Test {
  19288. protected:
  19289. void SetUp() override {
  19290. stop_server_.store(false);
  19291. events_.clear();
  19292. server_ = httplib::detail::make_unique<Server>();
  19293. setup_server();
  19294. start_server();
  19295. }
  19296. void TearDown() override {
  19297. stop_server_.store(true);
  19298. event_cv_.notify_all();
  19299. server_->stop();
  19300. if (server_thread_.joinable()) { server_thread_.join(); }
  19301. }
  19302. void setup_server() {
  19303. // Simple SSE endpoint
  19304. server_->Get("/events", [this](const Request &req, Response &res) {
  19305. auto last_id = req.get_header_value("Last-Event-ID");
  19306. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19307. res.set_chunked_content_provider(
  19308. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19309. std::unique_lock<std::mutex> lock(event_mutex_);
  19310. if (event_cv_.wait_for(
  19311. lock, std::chrono::milliseconds(200), [this] {
  19312. return !events_.empty() || stop_server_.load();
  19313. })) {
  19314. if (stop_server_.load()) { return false; }
  19315. if (!events_.empty()) {
  19316. std::string event = events_.front();
  19317. events_.erase(events_.begin());
  19318. sink.write(event.data(), event.size());
  19319. return true;
  19320. }
  19321. }
  19322. return !stop_server_.load();
  19323. });
  19324. });
  19325. // Endpoint that returns error
  19326. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19327. res.status = 500;
  19328. res.set_content("Internal Server Error", "text/plain");
  19329. });
  19330. // Endpoint for custom event types
  19331. server_->Get("/custom-events", [](const Request &, Response &res) {
  19332. res.set_chunked_content_provider(
  19333. "text/event-stream", [](size_t offset, DataSink &sink) {
  19334. if (offset == 0) {
  19335. std::string event = "event: update\ndata: updated\n\n"
  19336. "event: delete\ndata: deleted\n\n";
  19337. sink.write(event.data(), event.size());
  19338. }
  19339. return false; // End stream after sending
  19340. });
  19341. });
  19342. }
  19343. void start_server() {
  19344. port_ = server_->bind_to_any_port(HOST);
  19345. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19346. // Wait for server to start
  19347. while (!server_->is_running()) {
  19348. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19349. }
  19350. }
  19351. int get_port() const { return port_; }
  19352. void send_event(const std::string &event) {
  19353. std::lock_guard<std::mutex> lock(event_mutex_);
  19354. events_.push_back(event);
  19355. event_cv_.notify_all();
  19356. }
  19357. std::unique_ptr<Server> server_;
  19358. std::thread server_thread_;
  19359. std::mutex event_mutex_;
  19360. std::condition_variable event_cv_;
  19361. std::vector<std::string> events_;
  19362. std::atomic<bool> stop_server_{false};
  19363. std::string last_received_event_id_;
  19364. int port_ = 0;
  19365. };
  19366. //==============================================================================
  19367. // SSE Parsing Tests
  19368. //==============================================================================
  19369. class SSEParsingTest : public SSEIntegrationTest {
  19370. protected:
  19371. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19372. // A trailing sentinel event tells when the whole stream has been parsed.
  19373. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19374. auto body = stream + "event: end\ndata: end\n\n";
  19375. server_->Get("/parse", [body](const Request &, Response &res) {
  19376. res.set_content(body, "text/event-stream");
  19377. });
  19378. return collect("/parse");
  19379. }
  19380. // Runs SSEClient against path until an "end" event arrives and returns the
  19381. // messages dispatched before it
  19382. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19383. Client client(HOST, get_port());
  19384. sse::SSEClient sse(client, path);
  19385. std::mutex mutex;
  19386. std::condition_variable cv;
  19387. std::vector<sse::SSEMessage> messages;
  19388. auto done = false;
  19389. sse.on_message([&](const sse::SSEMessage &msg) {
  19390. std::lock_guard<std::mutex> lock(mutex);
  19391. // Ignore a replay from a reconnect that races with stop()
  19392. if (!done) { messages.push_back(msg); }
  19393. });
  19394. sse.on_event("end", [&](const sse::SSEMessage &) {
  19395. std::lock_guard<std::mutex> lock(mutex);
  19396. done = true;
  19397. cv.notify_all();
  19398. });
  19399. sse.set_reconnect_interval(100);
  19400. sse.start_async();
  19401. {
  19402. std::unique_lock<std::mutex> lock(mutex);
  19403. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19404. }
  19405. sse.stop();
  19406. EXPECT_TRUE(done);
  19407. return messages;
  19408. }
  19409. };
  19410. TEST_F(SSEParsingTest, SingleLineData) {
  19411. auto msgs = parse("data: hello\n\n");
  19412. ASSERT_EQ(msgs.size(), 1u);
  19413. EXPECT_EQ(msgs[0].data, "hello");
  19414. EXPECT_EQ(msgs[0].event, "message");
  19415. }
  19416. TEST_F(SSEParsingTest, MultiLineData) {
  19417. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19418. ASSERT_EQ(msgs.size(), 1u);
  19419. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19420. }
  19421. TEST_F(SSEParsingTest, CustomEventType) {
  19422. auto msgs = parse("event: update\ndata: payload\n\n");
  19423. ASSERT_EQ(msgs.size(), 1u);
  19424. EXPECT_EQ(msgs[0].event, "update");
  19425. EXPECT_EQ(msgs[0].data, "payload");
  19426. }
  19427. TEST_F(SSEParsingTest, EventIdHandling) {
  19428. auto msgs = parse("id: 12345\ndata: test\n\n");
  19429. ASSERT_EQ(msgs.size(), 1u);
  19430. EXPECT_EQ(msgs[0].id, "12345");
  19431. }
  19432. TEST_F(SSEParsingTest, EmptyEventId) {
  19433. auto msgs = parse("id:\ndata: test\n\n");
  19434. ASSERT_EQ(msgs.size(), 1u);
  19435. EXPECT_EQ(msgs[0].id, "");
  19436. }
  19437. TEST_F(SSEParsingTest, CommentsIgnored) {
  19438. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19439. ASSERT_EQ(msgs.size(), 1u);
  19440. EXPECT_EQ(msgs[0].data, "hello");
  19441. EXPECT_EQ(msgs[0].event, "message");
  19442. }
  19443. TEST_F(SSEParsingTest, ColonInValue) {
  19444. auto msgs = parse("data: hello:world:test\n\n");
  19445. ASSERT_EQ(msgs.size(), 1u);
  19446. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19447. }
  19448. TEST_F(SSEParsingTest, FieldNameOnly) {
  19449. // A line without a colon is a field name with an empty value
  19450. auto msgs = parse("data\n\n");
  19451. ASSERT_EQ(msgs.size(), 1u);
  19452. EXPECT_EQ(msgs[0].data, "");
  19453. }
  19454. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19455. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19456. ASSERT_EQ(msgs.size(), 1u);
  19457. EXPECT_EQ(msgs[0].event, "update");
  19458. EXPECT_EQ(msgs[0].data, "hello");
  19459. }
  19460. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19461. auto msgs = parse("data\r\n\r\n");
  19462. ASSERT_EQ(msgs.size(), 1u);
  19463. EXPECT_EQ(msgs[0].data, "");
  19464. }
  19465. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19466. auto msgs = parse("event: update\rdata: hello\r\r");
  19467. ASSERT_EQ(msgs.size(), 1u);
  19468. EXPECT_EQ(msgs[0].event, "update");
  19469. EXPECT_EQ(msgs[0].data, "hello");
  19470. }
  19471. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19472. // Chunk boundaries fall inside every \r\n and right before the first one
  19473. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19474. "\n\r", "\nevent: end\ndata: end\n\n"};
  19475. server_->Get("/split", [chunks](const Request &, Response &res) {
  19476. auto i = std::make_shared<size_t>(0);
  19477. res.set_chunked_content_provider(
  19478. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19479. if (*i == chunks.size()) {
  19480. sink.done();
  19481. } else {
  19482. sink.write(chunks[*i].data(), chunks[*i].size());
  19483. (*i)++;
  19484. }
  19485. return true;
  19486. });
  19487. });
  19488. auto msgs = collect("/split");
  19489. ASSERT_EQ(msgs.size(), 1u);
  19490. EXPECT_EQ(msgs[0].event, "update");
  19491. EXPECT_EQ(msgs[0].data, "hello");
  19492. }
  19493. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19494. // Only a BOM at the start of the stream is ignored
  19495. auto msgs = parse("\xEF\xBB\xBF"
  19496. "data: first\n\n"
  19497. "\xEF\xBB\xBF"
  19498. "data: second\n\n");
  19499. ASSERT_EQ(msgs.size(), 1u);
  19500. EXPECT_EQ(msgs[0].data, "first");
  19501. }
  19502. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19503. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19504. ASSERT_EQ(msgs.size(), 1u);
  19505. EXPECT_EQ(msgs[0].data, "hello");
  19506. EXPECT_EQ(msgs[0].event, "message");
  19507. }
  19508. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19509. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19510. ASSERT_EQ(msgs.size(), 2u);
  19511. EXPECT_EQ(msgs[0].data, "hello");
  19512. EXPECT_EQ(msgs[1].data, "hello");
  19513. }
  19514. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19515. // An event without data is not dispatched, and its type must not leak
  19516. // into the next event
  19517. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19518. ASSERT_EQ(msgs.size(), 1u);
  19519. EXPECT_EQ(msgs[0].event, "message");
  19520. EXPECT_EQ(msgs[0].data, "hello");
  19521. }
  19522. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19523. // The first connection sends only an id; the second echoes back the
  19524. // Last-Event-ID it was reconnected with
  19525. std::atomic<int> connection_count{0};
  19526. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19527. if (connection_count++ == 0) {
  19528. res.set_content("id: 42\n\n", "text/event-stream");
  19529. } else {
  19530. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19531. "\n\nevent: end\ndata: end\n\n",
  19532. "text/event-stream");
  19533. }
  19534. });
  19535. auto msgs = collect("/id-only");
  19536. ASSERT_EQ(msgs.size(), 1u);
  19537. EXPECT_EQ(msgs[0].data, "42");
  19538. }
  19539. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19540. // The first connection sets an id and then clears it with an empty one; the
  19541. // second reports whether it was reconnected with a Last-Event-ID
  19542. std::atomic<int> connection_count{0};
  19543. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19544. if (connection_count++ == 0) {
  19545. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19546. "text/event-stream");
  19547. } else {
  19548. res.set_content(
  19549. std::string("data: ") +
  19550. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19551. "\n\nevent: end\ndata: end\n\n",
  19552. "text/event-stream");
  19553. }
  19554. });
  19555. auto msgs = collect("/id-clear");
  19556. ASSERT_EQ(msgs.size(), 3u);
  19557. EXPECT_EQ(msgs[0].id, "1");
  19558. EXPECT_EQ(msgs[1].id, "");
  19559. EXPECT_EQ(msgs[2].data, "not sent");
  19560. }
  19561. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19562. // The first connection sets an id and then sends ids that cannot be carried
  19563. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19564. // with
  19565. std::atomic<int> connection_count{0};
  19566. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19567. if (connection_count++ == 0) {
  19568. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19569. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19570. "text/event-stream");
  19571. } else {
  19572. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19573. "\n\nevent: end\ndata: end\n\n",
  19574. "text/event-stream");
  19575. }
  19576. });
  19577. auto msgs = collect("/id-unsendable");
  19578. ASSERT_EQ(msgs.size(), 1u);
  19579. EXPECT_EQ(msgs[0].data, "42");
  19580. }
  19581. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19582. auto msgs = parse("event: notification\nid: evt-42\n"
  19583. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19584. ASSERT_EQ(msgs.size(), 1u);
  19585. EXPECT_EQ(msgs[0].event, "notification");
  19586. EXPECT_EQ(msgs[0].id, "evt-42");
  19587. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19588. }
  19589. TEST(SSEMessageTest, Clear) {
  19590. sse::SSEMessage msg;
  19591. msg.event = "custom";
  19592. msg.data = "some data";
  19593. msg.id = "123";
  19594. msg.clear();
  19595. EXPECT_EQ(msg.event, "message");
  19596. EXPECT_EQ(msg.data, "");
  19597. EXPECT_EQ(msg.id, "");
  19598. }
  19599. //==============================================================================
  19600. // SSE Integration Tests
  19601. //==============================================================================
  19602. // Test: Successful connection and on_open callback
  19603. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19604. // Add a simple endpoint that sends one event and closes
  19605. server_->Get("/simple-event", [](const Request &, Response &res) {
  19606. res.set_chunked_content_provider(
  19607. "text/event-stream", [](size_t offset, DataSink &sink) {
  19608. if (offset == 0) {
  19609. std::string event = "data: hello\n\n";
  19610. sink.write(event.data(), event.size());
  19611. }
  19612. return false; // Close stream after sending
  19613. });
  19614. });
  19615. Client client("localhost", get_port());
  19616. sse::SSEClient sse(client, "/simple-event");
  19617. std::atomic<bool> open_called{false};
  19618. std::atomic<bool> message_received{false};
  19619. sse.on_open([&open_called]() { open_called.store(true); });
  19620. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19621. if (msg.data == "hello") { message_received.store(true); }
  19622. });
  19623. sse.set_reconnect_interval(100);
  19624. sse.set_max_reconnect_attempts(1);
  19625. // Start async
  19626. sse.start_async();
  19627. // Wait for message to be processed
  19628. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19629. sse.stop();
  19630. EXPECT_TRUE(open_called.load());
  19631. EXPECT_TRUE(message_received.load());
  19632. }
  19633. // Test: on_message callback
  19634. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19635. // Endpoint that sends multiple events then closes
  19636. server_->Get("/multi-event", [](const Request &, Response &res) {
  19637. res.set_chunked_content_provider(
  19638. "text/event-stream", [](size_t offset, DataSink &sink) {
  19639. if (offset == 0) {
  19640. std::string events = "data: message1\n\ndata: message2\n\n";
  19641. sink.write(events.data(), events.size());
  19642. }
  19643. return false;
  19644. });
  19645. });
  19646. Client client("localhost", get_port());
  19647. sse::SSEClient sse(client, "/multi-event");
  19648. std::vector<std::string> received_messages;
  19649. std::mutex messages_mutex;
  19650. sse.on_message([&](const sse::SSEMessage &msg) {
  19651. std::lock_guard<std::mutex> lock(messages_mutex);
  19652. received_messages.push_back(msg.data);
  19653. });
  19654. sse.set_reconnect_interval(100);
  19655. sse.set_max_reconnect_attempts(1);
  19656. sse.start_async();
  19657. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19658. sse.stop();
  19659. std::lock_guard<std::mutex> lock(messages_mutex);
  19660. EXPECT_GE(received_messages.size(), 2u);
  19661. if (received_messages.size() >= 2) {
  19662. EXPECT_EQ(received_messages[0], "message1");
  19663. EXPECT_EQ(received_messages[1], "message2");
  19664. }
  19665. }
  19666. // Test: on_event for specific types
  19667. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19668. Client client("localhost", get_port());
  19669. sse::SSEClient sse(client, "/custom-events");
  19670. std::atomic<bool> update_received{false};
  19671. std::atomic<bool> delete_received{false};
  19672. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19673. if (msg.data == "updated") { update_received.store(true); }
  19674. });
  19675. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19676. if (msg.data == "deleted") { delete_received.store(true); }
  19677. });
  19678. sse.set_max_reconnect_attempts(1);
  19679. sse.start_async();
  19680. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19681. sse.stop();
  19682. EXPECT_TRUE(update_received.load());
  19683. EXPECT_TRUE(delete_received.load());
  19684. }
  19685. // Test: on_error callback on connection failure
  19686. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19687. // Connect to a non-existent port
  19688. Client client("localhost", 59999);
  19689. sse::SSEClient sse(client, "/events");
  19690. std::atomic<bool> error_called{false};
  19691. Error received_error = Error::Success;
  19692. sse.on_error([&](Error err) {
  19693. error_called.store(true);
  19694. received_error = err;
  19695. });
  19696. sse.set_reconnect_interval(50);
  19697. sse.set_max_reconnect_attempts(1);
  19698. sse.start_async();
  19699. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19700. sse.stop();
  19701. EXPECT_TRUE(error_called.load());
  19702. EXPECT_NE(received_error, Error::Success);
  19703. }
  19704. // Test: Last-Event-ID header sent on reconnect
  19705. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19706. // Endpoint that sends event with ID
  19707. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19708. res.set_chunked_content_provider(
  19709. "text/event-stream", [](size_t offset, DataSink &sink) {
  19710. if (offset == 0) {
  19711. std::string event = "id: evt-123\ndata: test\n\n";
  19712. sink.write(event.data(), event.size());
  19713. }
  19714. return false;
  19715. });
  19716. });
  19717. Client client("localhost", get_port());
  19718. sse::SSEClient sse(client, "/event-with-id");
  19719. std::atomic<bool> id_received{false};
  19720. sse.on_message([&](const sse::SSEMessage &msg) {
  19721. if (!msg.id.empty()) { id_received.store(true); }
  19722. });
  19723. sse.set_reconnect_interval(100);
  19724. sse.set_max_reconnect_attempts(1);
  19725. sse.start_async();
  19726. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19727. sse.stop();
  19728. EXPECT_TRUE(id_received.load());
  19729. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19730. }
  19731. // Test: Manual stop
  19732. TEST_F(SSEIntegrationTest, ManualStop) {
  19733. // Endpoint that sends one event and stays open briefly
  19734. std::atomic<bool> handler_running{true};
  19735. server_->Get("/stay-open", [&handler_running](const Request &,
  19736. Response &res) {
  19737. res.set_chunked_content_provider(
  19738. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19739. if (offset == 0) {
  19740. std::string event = "data: connected\n\n";
  19741. sink.write(event.data(), event.size());
  19742. }
  19743. // Keep connection open while handler_running is true
  19744. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19745. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19746. }
  19747. return false;
  19748. });
  19749. });
  19750. Client client("localhost", get_port());
  19751. sse::SSEClient sse(client, "/stay-open");
  19752. std::atomic<bool> connected{false};
  19753. sse.on_open([&connected]() { connected.store(true); });
  19754. sse.set_reconnect_interval(100);
  19755. sse.set_max_reconnect_attempts(1);
  19756. sse.start_async();
  19757. // Wait for connection to establish
  19758. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19759. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19760. }
  19761. EXPECT_TRUE(connected.load());
  19762. EXPECT_TRUE(sse.is_connected());
  19763. // Signal handler to stop
  19764. handler_running.store(false);
  19765. // Stop SSE client
  19766. sse.stop();
  19767. EXPECT_FALSE(sse.is_connected());
  19768. }
  19769. // Test: SSEClient with custom headers
  19770. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19771. // Setup a server endpoint that checks for custom header
  19772. std::atomic<bool> header_received{false};
  19773. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19774. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19775. header_received.store(true);
  19776. }
  19777. res.set_chunked_content_provider("text/event-stream",
  19778. [](size_t, DataSink &) { return false; });
  19779. });
  19780. Client client("localhost", get_port());
  19781. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19782. sse::SSEClient sse(client, "/header-check", headers);
  19783. sse.set_max_reconnect_attempts(1);
  19784. sse.start_async();
  19785. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19786. sse.stop();
  19787. EXPECT_TRUE(header_received.load());
  19788. }
  19789. // Test: Reconnect interval configuration
  19790. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19791. Client client("localhost", get_port());
  19792. sse::SSEClient sse(client, "/events");
  19793. auto &result = sse.set_reconnect_interval(500);
  19794. // Builder pattern should return reference to self
  19795. EXPECT_EQ(&result, &sse);
  19796. }
  19797. // Test: Max reconnect attempts
  19798. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19799. // Connect to non-existent port to force reconnects
  19800. Client client("localhost", 59998);
  19801. sse::SSEClient sse(client, "/events");
  19802. std::atomic<int> error_count{0};
  19803. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19804. sse.set_reconnect_interval(50);
  19805. sse.set_max_reconnect_attempts(2);
  19806. auto start = std::chrono::steady_clock::now();
  19807. sse.start(); // Blocking call
  19808. auto end = std::chrono::steady_clock::now();
  19809. // Should have stopped after 2 failed attempts
  19810. EXPECT_GE(error_count.load(), 2);
  19811. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19812. auto duration =
  19813. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19814. #ifdef _WIN32
  19815. // Windows is much slower for socket connection failures
  19816. EXPECT_LT(duration.count(), 7000);
  19817. #else
  19818. EXPECT_LT(duration.count(), 1000);
  19819. #endif
  19820. }
  19821. // Test: Multi-line data in integration
  19822. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19823. // Endpoint with multi-line data
  19824. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19825. res.set_chunked_content_provider(
  19826. "text/event-stream", [](size_t offset, DataSink &sink) {
  19827. if (offset == 0) {
  19828. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19829. sink.write(event.data(), event.size());
  19830. }
  19831. return false;
  19832. });
  19833. });
  19834. Client client("localhost", get_port());
  19835. sse::SSEClient sse(client, "/multiline-data");
  19836. std::string received_data;
  19837. std::mutex data_mutex;
  19838. sse.on_message([&](const sse::SSEMessage &msg) {
  19839. std::lock_guard<std::mutex> lock(data_mutex);
  19840. received_data = msg.data;
  19841. });
  19842. sse.set_reconnect_interval(100);
  19843. sse.set_max_reconnect_attempts(1);
  19844. sse.start_async();
  19845. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19846. sse.stop();
  19847. std::lock_guard<std::mutex> lock(data_mutex);
  19848. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19849. }
  19850. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19851. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19852. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19853. DataSink &sink) {
  19854. if (offset == 0) {
  19855. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19856. sink.write(events.data(), events.size());
  19857. }
  19858. return false;
  19859. });
  19860. });
  19861. Client client("localhost", get_port());
  19862. sse::SSEClient sse(client, "/empty-data-lines");
  19863. std::mutex mutex;
  19864. std::condition_variable cv;
  19865. std::vector<std::string> received;
  19866. sse.on_message([&](const sse::SSEMessage &msg) {
  19867. std::lock_guard<std::mutex> lock(mutex);
  19868. received.push_back(msg.data);
  19869. cv.notify_all();
  19870. });
  19871. sse.set_max_reconnect_attempts(1);
  19872. sse.start_async();
  19873. {
  19874. std::unique_lock<std::mutex> lock(mutex);
  19875. cv.wait_for(lock, std::chrono::seconds(2),
  19876. [&] { return received.size() >= 3; });
  19877. }
  19878. sse.stop();
  19879. ASSERT_GE(received.size(), 3u);
  19880. EXPECT_EQ(received[0], "");
  19881. EXPECT_EQ(received[1], "\nhello");
  19882. EXPECT_EQ(received[2], "");
  19883. }
  19884. // Test: Auto-reconnect after server disconnection
  19885. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19886. std::atomic<int> connection_count{0};
  19887. std::atomic<int> message_count{0};
  19888. // Endpoint that sends one event and closes, forcing reconnect
  19889. server_->Get("/reconnect-test",
  19890. [&connection_count](const Request &, Response &res) {
  19891. connection_count.fetch_add(1);
  19892. res.set_chunked_content_provider(
  19893. "text/event-stream", [](size_t offset, DataSink &sink) {
  19894. if (offset == 0) {
  19895. std::string event = "data: hello\n\n";
  19896. sink.write(event.data(), event.size());
  19897. }
  19898. return false; // Close connection after sending
  19899. });
  19900. });
  19901. Client client("localhost", get_port());
  19902. sse::SSEClient sse(client, "/reconnect-test");
  19903. sse.on_message([&message_count](const sse::SSEMessage &) {
  19904. message_count.fetch_add(1);
  19905. });
  19906. sse.set_reconnect_interval(100);
  19907. sse.set_max_reconnect_attempts(3);
  19908. sse.start_async();
  19909. // Wait long enough for multiple reconnects
  19910. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19911. sse.stop();
  19912. // Should have connected multiple times (initial + reconnects)
  19913. EXPECT_GE(connection_count.load(), 2);
  19914. // Should have received messages from multiple connections
  19915. EXPECT_GE(message_count.load(), 2);
  19916. }
  19917. // Test: A retry field that is not all ASCII digits is ignored
  19918. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19919. std::atomic<int> connection_count{0};
  19920. server_->Get("/bad-retry",
  19921. [&connection_count](const Request &, Response &res) {
  19922. connection_count.fetch_add(1);
  19923. res.set_chunked_content_provider(
  19924. "text/event-stream", [](size_t offset, DataSink &sink) {
  19925. if (offset == 0) {
  19926. std::string event = "retry: -1\ndata: hello\n\n";
  19927. sink.write(event.data(), event.size());
  19928. }
  19929. return false;
  19930. });
  19931. });
  19932. Client client("localhost", get_port());
  19933. sse::SSEClient sse(client, "/bad-retry");
  19934. sse.set_reconnect_interval(10000);
  19935. sse.start_async();
  19936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19937. sse.stop();
  19938. EXPECT_EQ(connection_count.load(), 1);
  19939. }
  19940. // Test: A retry field of all ASCII digits sets the reconnection time
  19941. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19942. std::mutex mutex;
  19943. std::condition_variable cv;
  19944. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19945. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19946. {
  19947. std::lock_guard<std::mutex> lock(mutex);
  19948. connected_at.push_back(std::chrono::steady_clock::now());
  19949. cv.notify_all();
  19950. }
  19951. res.set_chunked_content_provider(
  19952. "text/event-stream", [](size_t offset, DataSink &sink) {
  19953. if (offset == 0) {
  19954. std::string event = "retry: 0\ndata: hello\n\n";
  19955. sink.write(event.data(), event.size());
  19956. }
  19957. return false;
  19958. });
  19959. });
  19960. Client client("localhost", get_port());
  19961. sse::SSEClient sse(client, "/zero-retry");
  19962. sse.set_reconnect_interval(10000);
  19963. sse.start_async();
  19964. {
  19965. std::unique_lock<std::mutex> lock(mutex);
  19966. cv.wait_for(lock, std::chrono::seconds(5),
  19967. [&] { return connected_at.size() >= 2; });
  19968. }
  19969. sse.stop();
  19970. // The server-supplied interval is applied, but never below 100ms, so
  19971. // "retry: 0" does not cause a busy reconnect loop
  19972. std::lock_guard<std::mutex> lock(mutex);
  19973. ASSERT_GE(connected_at.size(), 2u);
  19974. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  19975. connected_at[1] - connected_at[0])
  19976. .count();
  19977. EXPECT_GE(interval_ms, 100);
  19978. }
  19979. // Test: Last-Event-ID sent on reconnect
  19980. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19981. std::atomic<int> connection_count{0};
  19982. std::vector<std::string> received_last_event_ids;
  19983. std::mutex id_mutex;
  19984. // Endpoint that checks Last-Event-ID header and sends event with ID
  19985. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19986. int conn = connection_count.fetch_add(1);
  19987. // Capture the Last-Event-ID header from each connection
  19988. {
  19989. std::lock_guard<std::mutex> lock(id_mutex);
  19990. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19991. }
  19992. res.set_chunked_content_provider(
  19993. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19994. if (offset == 0) {
  19995. std::string event =
  19996. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19997. sink.write(event.data(), event.size());
  19998. }
  19999. return false;
  20000. });
  20001. });
  20002. Client client("localhost", get_port());
  20003. sse::SSEClient sse(client, "/reconnect-with-id");
  20004. sse.set_reconnect_interval(100);
  20005. sse.set_max_reconnect_attempts(3);
  20006. sse.start_async();
  20007. // Wait for at least 2 connections
  20008. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20009. sse.stop();
  20010. // Verify behavior
  20011. std::lock_guard<std::mutex> lock(id_mutex);
  20012. EXPECT_GE(received_last_event_ids.size(), 2u);
  20013. // First connection should have no Last-Event-ID
  20014. if (!received_last_event_ids.empty()) {
  20015. EXPECT_EQ(received_last_event_ids[0], "");
  20016. }
  20017. // Second connection should have Last-Event-ID from first connection
  20018. if (received_last_event_ids.size() >= 2) {
  20019. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20020. }
  20021. }
  20022. // Test: set_headers updates headers used on reconnect
  20023. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20024. std::vector<std::string> received_tokens;
  20025. std::mutex token_mutex;
  20026. // Endpoint that captures Authorization header
  20027. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20028. {
  20029. std::lock_guard<std::mutex> lock(token_mutex);
  20030. received_tokens.push_back(req.get_header_value("Authorization"));
  20031. }
  20032. res.set_chunked_content_provider(
  20033. "text/event-stream", [](size_t offset, DataSink &sink) {
  20034. if (offset == 0) {
  20035. std::string event = "data: hello\n\n";
  20036. sink.write(event.data(), event.size());
  20037. }
  20038. return false; // Close connection to trigger reconnect
  20039. });
  20040. });
  20041. Client client("localhost", get_port());
  20042. Headers headers = {{"Authorization", "Bearer old-token"}};
  20043. sse::SSEClient sse(client, "/auth-check", headers);
  20044. // Update headers on each successful connection
  20045. sse.on_open(
  20046. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20047. sse.set_reconnect_interval(100);
  20048. sse.set_max_reconnect_attempts(3);
  20049. sse.start_async();
  20050. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20051. sse.stop();
  20052. std::lock_guard<std::mutex> lock(token_mutex);
  20053. ASSERT_GE(received_tokens.size(), 2u);
  20054. // First connection uses original header
  20055. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20056. // Second connection uses updated header from set_headers
  20057. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20058. }
  20059. // Test: 401 allows reconnection (so on_error can refresh headers)
  20060. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20061. std::atomic<int> connection_count{0};
  20062. // Endpoint: returns 401 on first attempt, 200 on second
  20063. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20064. int conn = connection_count.fetch_add(1);
  20065. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20066. res.status = StatusCode::Unauthorized_401;
  20067. res.set_content("Unauthorized", "text/plain");
  20068. return;
  20069. }
  20070. res.set_chunked_content_provider(
  20071. "text/event-stream", [](size_t offset, DataSink &sink) {
  20072. if (offset == 0) {
  20073. std::string event = "data: authenticated\n\n";
  20074. sink.write(event.data(), event.size());
  20075. }
  20076. return false;
  20077. });
  20078. });
  20079. Client client("localhost", get_port());
  20080. Headers headers = {{"Authorization", "Bearer expired"}};
  20081. sse::SSEClient sse(client, "/auth-retry", headers);
  20082. std::atomic<bool> message_received{false};
  20083. // Refresh token on error
  20084. sse.on_error(
  20085. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20086. sse.on_message([&](const sse::SSEMessage &msg) {
  20087. if (msg.data == "authenticated") { message_received.store(true); }
  20088. });
  20089. sse.set_reconnect_interval(100);
  20090. sse.set_max_reconnect_attempts(3);
  20091. sse.start_async();
  20092. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20093. sse.stop();
  20094. // Should have reconnected after 401 and succeeded with new token
  20095. EXPECT_GE(connection_count.load(), 2);
  20096. EXPECT_TRUE(message_received.load());
  20097. }
  20098. TEST(Issue2318Test, EmptyHostString) {
  20099. {
  20100. httplib::Client cli_empty("", PORT);
  20101. auto res = cli_empty.Get("/");
  20102. ASSERT_FALSE(res);
  20103. EXPECT_EQ(httplib::Error::Connection, res.error());
  20104. }
  20105. {
  20106. httplib::Client cli(" ", PORT);
  20107. auto res = cli.Get("/");
  20108. ASSERT_FALSE(res);
  20109. EXPECT_EQ(httplib::Error::Connection, res.error());
  20110. }
  20111. }
  20112. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20113. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20114. Server svr;
  20115. // Set a small payload limit (1KB)
  20116. svr.set_payload_max_length(1024);
  20117. svr.Post("/test", [&](const Request &req, Response &res) {
  20118. res.set_content("Body size: " + std::to_string(req.body.size()),
  20119. "text/plain");
  20120. });
  20121. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20122. auto se = detail::scope_exit([&] {
  20123. svr.stop();
  20124. listen_thread.join();
  20125. });
  20126. svr.wait_until_ready();
  20127. // Create data that compresses well but exceeds limit when decompressed
  20128. // 8KB of repeated null bytes compresses to a very small size
  20129. std::string original_data(8 * 1024, '\0');
  20130. // Compress the data using gzip
  20131. std::string compressed_data;
  20132. detail::gzip_compressor compressor;
  20133. compressor.compress(original_data.data(), original_data.size(), true,
  20134. [&](const char *data, size_t size) {
  20135. compressed_data.append(data, size);
  20136. return true;
  20137. });
  20138. // Verify compression worked (compressed should be much smaller)
  20139. ASSERT_LT(compressed_data.size(), original_data.size());
  20140. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20141. // Send compressed data with Content-Encoding: gzip
  20142. Client cli(HOST, PORT);
  20143. Headers headers = {{"Content-Encoding", "gzip"}};
  20144. auto res =
  20145. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20146. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20148. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20149. }
  20150. #endif
  20151. // ============================================================================
  20152. // OpenSSL-Specific Tests
  20153. // ============================================================================
  20154. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20155. X509 *readCertificate(const std::string &strFileName) {
  20156. std::ifstream inStream(strFileName);
  20157. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20158. std::istreambuf_iterator<char>());
  20159. if (strCertPEM.empty()) return (nullptr);
  20160. BIO *pbCert = BIO_new(BIO_s_mem());
  20161. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20162. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20163. BIO_free(pbCert);
  20164. return (pCert);
  20165. }
  20166. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20167. std::ifstream inStream(strFileName);
  20168. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20169. std::istreambuf_iterator<char>());
  20170. if (strPrivateKeyPEM.empty()) return (nullptr);
  20171. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20172. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20173. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20174. BIO_free(pbPrivKey);
  20175. return (pPrivateKey);
  20176. }
  20177. TEST(BindServerTest, UpdateCerts) {
  20178. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20179. int port = svr.bind_to_any_port("0.0.0.0");
  20180. ASSERT_TRUE(svr.is_valid());
  20181. ASSERT_TRUE(port > 0);
  20182. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20183. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20184. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20185. ASSERT_TRUE(cert != nullptr);
  20186. ASSERT_TRUE(ca_cert != nullptr);
  20187. ASSERT_TRUE(key != nullptr);
  20188. X509_STORE *cert_store = X509_STORE_new();
  20189. X509_STORE_add_cert(cert_store, ca_cert);
  20190. // svr.update_certs(cert, key, cert_store); // deprecated
  20191. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20192. CLIENT_CA_CERT_FILE);
  20193. ASSERT_TRUE(svr.is_valid());
  20194. svr.stop();
  20195. X509_STORE_free(cert_store);
  20196. X509_free(cert);
  20197. X509_free(ca_cert);
  20198. EVP_PKEY_free(key);
  20199. }
  20200. // Test that update_certs() updates client CA list correctly
  20201. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20202. // Start with file-based constructor
  20203. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20204. ASSERT_TRUE(svr.is_valid());
  20205. // Initially no client CA list should be set
  20206. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20207. ASSERT_TRUE(ssl_ctx != nullptr);
  20208. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20209. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20210. EXPECT_EQ(0, count_before);
  20211. // Now update with client CA (PEM string)
  20212. std::string cert_pem, key_pem, ca_pem;
  20213. read_file(SERVER_CERT_FILE, cert_pem);
  20214. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20215. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20216. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20217. ASSERT_TRUE(svr.is_valid());
  20218. // Now client CA list should be set
  20219. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20220. ASSERT_TRUE(ca_list_after != nullptr);
  20221. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20222. }
  20223. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20224. // Test that the file-path SSLServer constructor properly sets the client CA
  20225. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20227. ASSERT_TRUE(svr.is_valid());
  20228. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20229. ASSERT_TRUE(ssl_ctx != nullptr);
  20230. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20231. ASSERT_TRUE(ca_list != nullptr);
  20232. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20233. }
  20234. #endif
  20235. // ============================================================================
  20236. // MbedTLS-Specific Tests
  20237. // ============================================================================
  20238. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20239. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20240. using namespace httplib::tls;
  20241. // Track if callback was invoked
  20242. bool callback_invoked = false;
  20243. // The callback receives void* ctx which is actually MbedTlsContext*
  20244. // We can access the mbedtls_ssl_config via the context
  20245. auto setup_callback = [&callback_invoked](void *ctx) {
  20246. callback_invoked = true;
  20247. // Cast to MbedTlsContext* to access the ssl config
  20248. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20249. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20250. // Use static variables to hold certificate data (simplified for test)
  20251. static mbedtls_x509_crt own_cert;
  20252. static mbedtls_pk_context own_key;
  20253. static mbedtls_x509_crt ca_chain;
  20254. static bool initialized = false;
  20255. if (!initialized) {
  20256. mbedtls_x509_crt_init(&own_cert);
  20257. mbedtls_pk_init(&own_key);
  20258. mbedtls_x509_crt_init(&ca_chain);
  20259. // Load server certificate
  20260. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20261. return false;
  20262. }
  20263. // Load server private key.
  20264. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20265. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20266. #if MBEDTLS_VERSION_MAJOR == 3
  20267. ,
  20268. mbedtls_ctr_drbg_random, nullptr
  20269. #endif
  20270. ) != 0) {
  20271. return false;
  20272. }
  20273. // Load CA chain for client verification
  20274. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20275. return false;
  20276. }
  20277. initialized = true;
  20278. }
  20279. // Configure the SSL config
  20280. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20281. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20282. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20283. // Set minimum TLS version using mbedTLS native API
  20284. #if MBEDTLS_VERSION_MAJOR >= 3
  20285. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20286. #else
  20287. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20288. MBEDTLS_SSL_MINOR_VERSION_3);
  20289. #endif
  20290. return true;
  20291. };
  20292. SSLServer svr(setup_callback);
  20293. ASSERT_TRUE(svr.is_valid());
  20294. ASSERT_TRUE(callback_invoked);
  20295. svr.Get("/test", [&](const Request &req, Response &res) {
  20296. res.set_content("test", "text/plain");
  20297. auto cert = req.peer_cert();
  20298. ASSERT_TRUE(static_cast<bool>(cert));
  20299. auto common_name = cert.subject_cn();
  20300. EXPECT_EQ("Common Name", common_name);
  20301. });
  20302. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20303. auto se = detail::scope_exit([&] {
  20304. svr.stop();
  20305. t.join();
  20306. ASSERT_FALSE(svr.is_running());
  20307. });
  20308. svr.wait_until_ready();
  20309. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20310. cli.enable_server_certificate_verification(false);
  20311. cli.set_connection_timeout(30);
  20312. auto res = cli.Get("/test");
  20313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20314. ASSERT_EQ(StatusCode::OK_200, res->status);
  20315. }
  20316. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20317. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20318. // keep-alive SSL session, which reads through that config in
  20319. // mbedtls_ssl_close_notify.
  20320. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20321. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20322. ASSERT_TRUE(svr.is_valid());
  20323. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20324. res.set_content("test", "text/plain");
  20325. });
  20326. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20327. auto se = detail::scope_exit([&] {
  20328. svr.stop();
  20329. t.join();
  20330. ASSERT_FALSE(svr.is_running());
  20331. });
  20332. svr.wait_until_ready();
  20333. {
  20334. SSLClient cli(HOST, PORT);
  20335. cli.enable_server_certificate_verification(false);
  20336. cli.set_keep_alive(true);
  20337. auto res = cli.Get("/test");
  20338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20339. ASSERT_EQ(StatusCode::OK_200, res->status);
  20340. // cli is destructed here with the keep-alive SSL session still open.
  20341. }
  20342. }
  20343. #endif
  20344. // WebSocket Tests
  20345. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20346. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20347. // defining the meaning of these bits has been negotiated.
  20348. auto make_frame = [](uint8_t first_byte) {
  20349. std::string frame;
  20350. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20351. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20352. frame += "Hello";
  20353. return frame;
  20354. };
  20355. // RSV1 set (0x40)
  20356. {
  20357. detail::BufferStream strm;
  20358. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20359. ws::Opcode opcode;
  20360. std::string payload;
  20361. bool fin;
  20362. EXPECT_EQ(
  20363. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20364. ws::impl::FrameRead::Fail);
  20365. }
  20366. // RSV2 set (0x20)
  20367. {
  20368. detail::BufferStream strm;
  20369. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20370. ws::Opcode opcode;
  20371. std::string payload;
  20372. bool fin;
  20373. EXPECT_EQ(
  20374. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20375. ws::impl::FrameRead::Fail);
  20376. }
  20377. // RSV3 set (0x10)
  20378. {
  20379. detail::BufferStream strm;
  20380. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20381. ws::Opcode opcode;
  20382. std::string payload;
  20383. bool fin;
  20384. EXPECT_EQ(
  20385. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20386. ws::impl::FrameRead::Fail);
  20387. }
  20388. // No RSV bits set - should succeed
  20389. {
  20390. detail::BufferStream strm;
  20391. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20392. ws::Opcode opcode;
  20393. std::string payload;
  20394. bool fin;
  20395. EXPECT_EQ(
  20396. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20397. ws::impl::FrameRead::Ok);
  20398. EXPECT_EQ(ws::Opcode::Text, opcode);
  20399. EXPECT_EQ("Hello", payload);
  20400. EXPECT_TRUE(fin);
  20401. }
  20402. }
  20403. TEST(WebSocketTest, ControlFrameValidation) {
  20404. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20405. // payload length <= 125.
  20406. // Ping with FIN=0 - must be rejected
  20407. {
  20408. detail::BufferStream strm;
  20409. std::string frame;
  20410. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20411. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20412. strm.write(frame.data(), frame.size());
  20413. ws::Opcode opcode;
  20414. std::string payload;
  20415. bool fin;
  20416. EXPECT_EQ(
  20417. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20418. ws::impl::FrameRead::Fail);
  20419. }
  20420. // Close with FIN=0 - must be rejected
  20421. {
  20422. detail::BufferStream strm;
  20423. std::string frame;
  20424. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20425. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20426. strm.write(frame.data(), frame.size());
  20427. ws::Opcode opcode;
  20428. std::string payload;
  20429. bool fin;
  20430. EXPECT_EQ(
  20431. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20432. ws::impl::FrameRead::Fail);
  20433. }
  20434. // Ping with payload_len=126 (extended length) - must be rejected
  20435. {
  20436. detail::BufferStream strm;
  20437. std::string frame;
  20438. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20439. frame += static_cast<char>(126); // payload_len=126 (>125)
  20440. frame += static_cast<char>(0x00); // extended length high byte
  20441. frame += static_cast<char>(126); // extended length low byte
  20442. frame += std::string(126, 'x');
  20443. strm.write(frame.data(), frame.size());
  20444. ws::Opcode opcode;
  20445. std::string payload;
  20446. bool fin;
  20447. EXPECT_EQ(
  20448. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20449. ws::impl::FrameRead::Fail);
  20450. }
  20451. // Ping with FIN=1 and payload_len=125 - should succeed
  20452. {
  20453. detail::BufferStream strm;
  20454. std::string frame;
  20455. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20456. frame += static_cast<char>(125); // payload_len=125
  20457. frame += std::string(125, 'x');
  20458. strm.write(frame.data(), frame.size());
  20459. ws::Opcode opcode;
  20460. std::string payload;
  20461. bool fin;
  20462. EXPECT_EQ(
  20463. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20464. ws::impl::FrameRead::Ok);
  20465. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20466. EXPECT_EQ(125u, payload.size());
  20467. EXPECT_TRUE(fin);
  20468. }
  20469. }
  20470. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20471. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20472. // length MUST be 0.
  20473. // MSB set - must be rejected
  20474. {
  20475. detail::BufferStream strm;
  20476. std::string frame;
  20477. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20478. frame += static_cast<char>(127); // 64-bit extended length
  20479. frame += static_cast<char>(0x80); // MSB set (invalid)
  20480. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20481. strm.write(frame.data(), frame.size());
  20482. ws::Opcode opcode;
  20483. std::string payload;
  20484. bool fin;
  20485. EXPECT_EQ(
  20486. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20487. ws::impl::FrameRead::Fail);
  20488. }
  20489. // MSB clear - should pass length parsing (will be rejected by max_len,
  20490. // but that's a different check; use a small length to verify)
  20491. {
  20492. detail::BufferStream strm;
  20493. std::string frame;
  20494. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20495. frame += static_cast<char>(127); // 64-bit extended length
  20496. frame += std::string(7, '\0'); // high bytes = 0
  20497. frame += static_cast<char>(0x03); // length = 3
  20498. frame += "abc";
  20499. strm.write(frame.data(), frame.size());
  20500. ws::Opcode opcode;
  20501. std::string payload;
  20502. bool fin;
  20503. EXPECT_EQ(
  20504. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20505. ws::impl::FrameRead::Ok);
  20506. EXPECT_EQ(ws::Opcode::Text, opcode);
  20507. EXPECT_EQ("abc", payload);
  20508. }
  20509. }
  20510. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20511. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20512. // Valid UTF-8
  20513. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20514. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20515. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20516. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20517. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20518. // Invalid UTF-8
  20519. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20520. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20521. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20522. EXPECT_FALSE(
  20523. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20524. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20525. }
  20526. TEST(WebSocketTest, ConnectAndDisconnect) {
  20527. Server svr;
  20528. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20529. std::string msg;
  20530. while (ws.read(msg)) {}
  20531. });
  20532. auto port = svr.bind_to_any_port(HOST);
  20533. std::thread t([&]() { svr.listen_after_bind(); });
  20534. svr.wait_until_ready();
  20535. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20536. auto res = client.connect();
  20537. ASSERT_TRUE(res);
  20538. EXPECT_EQ(Error::Success, res.error());
  20539. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20540. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20541. EXPECT_TRUE(client.is_open());
  20542. client.close();
  20543. EXPECT_FALSE(client.is_open());
  20544. svr.stop();
  20545. t.join();
  20546. }
  20547. TEST(WebSocketTest, ValidURL) {
  20548. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20549. EXPECT_TRUE(ws1.is_valid());
  20550. ws::WebSocketClient ws2("ws://example.com/path");
  20551. EXPECT_TRUE(ws2.is_valid());
  20552. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20553. EXPECT_TRUE(ws3.is_valid());
  20554. #ifdef CPPHTTPLIB_SSL_ENABLED
  20555. ws::WebSocketClient wss1("wss://example.com/path");
  20556. EXPECT_TRUE(wss1.is_valid());
  20557. ws::WebSocketClient wss2("wss://example.com:443/path");
  20558. EXPECT_TRUE(wss2.is_valid());
  20559. #endif
  20560. }
  20561. TEST(WebSocketTest, InvalidURL) {
  20562. // No scheme
  20563. ws::WebSocketClient ws1("localhost:8080/path");
  20564. EXPECT_FALSE(ws1.is_valid());
  20565. // No path
  20566. ws::WebSocketClient ws2("ws://localhost:8080");
  20567. EXPECT_FALSE(ws2.is_valid());
  20568. // Empty string
  20569. ws::WebSocketClient ws3("");
  20570. EXPECT_FALSE(ws3.is_valid());
  20571. // Missing host
  20572. ws::WebSocketClient ws4("ws://:8080/path");
  20573. EXPECT_FALSE(ws4.is_valid());
  20574. // Port number overflow — should not crash
  20575. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20576. EXPECT_FALSE(ws5.is_valid());
  20577. // Port out of range
  20578. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20579. EXPECT_FALSE(ws6.is_valid());
  20580. }
  20581. TEST(WebSocketTest, UnsupportedScheme) {
  20582. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20583. ws::WebSocketClient ws1("http://localhost:8080/path");
  20584. EXPECT_FALSE(ws1.is_valid());
  20585. ws::WebSocketClient ws2("https://localhost:8080/path");
  20586. EXPECT_FALSE(ws2.is_valid());
  20587. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20588. EXPECT_FALSE(ws3.is_valid());
  20589. #else
  20590. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20591. std::invalid_argument);
  20592. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20593. std::invalid_argument);
  20594. #endif
  20595. }
  20596. TEST(WebSocketTest, ConnectWhenInvalid) {
  20597. ws::WebSocketClient ws("not a valid url");
  20598. EXPECT_FALSE(ws.is_valid());
  20599. auto res = ws.connect();
  20600. EXPECT_FALSE(res);
  20601. EXPECT_EQ(Error::Connection, res.error());
  20602. EXPECT_EQ(-1, res.status());
  20603. }
  20604. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20605. // Grab a port that is free, then close it again so nothing listens there
  20606. Server svr;
  20607. auto port = svr.bind_to_any_port(HOST);
  20608. svr.stop();
  20609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20610. auto res = client.connect();
  20611. ASSERT_FALSE(res);
  20612. EXPECT_EQ(Error::Connection, res.error());
  20613. EXPECT_EQ(-1, res.status());
  20614. }
  20615. TEST(WebSocketTest, DefaultPort) {
  20616. ws::WebSocketClient ws1("ws://example.com/path");
  20617. EXPECT_TRUE(ws1.is_valid());
  20618. // ws:// defaults to port 80 (verified by successful parse)
  20619. #ifdef CPPHTTPLIB_SSL_ENABLED
  20620. ws::WebSocketClient ws2("wss://example.com/path");
  20621. EXPECT_TRUE(ws2.is_valid());
  20622. // wss:// defaults to port 443 (verified by successful parse)
  20623. #endif
  20624. }
  20625. TEST(WebSocketTest, IPv6LiteralAddress) {
  20626. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20627. EXPECT_TRUE(ws1.is_valid());
  20628. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20629. EXPECT_TRUE(ws2.is_valid());
  20630. }
  20631. TEST(WebSocketTest, ComplexPath) {
  20632. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20633. EXPECT_TRUE(ws1.is_valid());
  20634. ws::WebSocketClient ws2("ws://localhost:8080/");
  20635. EXPECT_TRUE(ws2.is_valid());
  20636. }
  20637. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20638. Server svr;
  20639. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20640. std::string msg;
  20641. while (ws.read(msg)) {}
  20642. });
  20643. auto port = svr.bind_to_any_port(HOST);
  20644. std::thread t([&]() { svr.listen_after_bind(); });
  20645. svr.wait_until_ready();
  20646. auto another_host = "example.com";
  20647. auto wrong_ip = "192.0.2.1";
  20648. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20649. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20650. ASSERT_TRUE(client.connect());
  20651. EXPECT_TRUE(client.is_open());
  20652. client.close();
  20653. svr.stop();
  20654. t.join();
  20655. }
  20656. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20657. Server svr;
  20658. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20659. std::string msg;
  20660. while (ws.read(msg)) {}
  20661. });
  20662. auto port = svr.bind_to_any_port(HOST);
  20663. std::thread t([&]() { svr.listen_after_bind(); });
  20664. svr.wait_until_ready();
  20665. auto wrong_ip = "192.0.2.1";
  20666. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20667. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20668. client.set_connection_timeout(1);
  20669. client.set_read_timeout(1);
  20670. client.set_write_timeout(1);
  20671. EXPECT_FALSE(client.connect());
  20672. EXPECT_FALSE(client.is_open());
  20673. svr.stop();
  20674. t.join();
  20675. }
  20676. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20677. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20678. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20679. // (RFC 6761) is only a map key and the Host header value.
  20680. auto host = "target.invalid";
  20681. Server svr;
  20682. std::string received_host;
  20683. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20684. received_host = req.get_header_value("Host");
  20685. std::string msg;
  20686. while (ws.read(msg)) {}
  20687. });
  20688. auto port = svr.bind_to_any_port(HOST);
  20689. std::thread t([&]() { svr.listen_after_bind(); });
  20690. // ASSERT_* below returns from the test body, which would leave t joinable
  20691. // and make ~thread call std::terminate.
  20692. auto se = detail::scope_exit([&] {
  20693. svr.stop();
  20694. if (t.joinable()) { t.join(); }
  20695. });
  20696. svr.wait_until_ready();
  20697. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20698. std::to_string(port) + "/ws");
  20699. client.set_hostname_addr_map({{host, HOST}});
  20700. ASSERT_TRUE(client.connect());
  20701. EXPECT_TRUE(client.is_open());
  20702. client.close();
  20703. svr.stop();
  20704. t.join();
  20705. // The mapping only redirects the connection; the identity stays host_.
  20706. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20707. }
  20708. class WebSocketIntegrationTest : public ::testing::Test {
  20709. protected:
  20710. void SetUp() override {
  20711. server_ = httplib::detail::make_unique<Server>();
  20712. setup_server();
  20713. start_server();
  20714. }
  20715. void TearDown() override {
  20716. server_->stop();
  20717. if (server_thread_.joinable()) { server_thread_.join(); }
  20718. }
  20719. void setup_server() {
  20720. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20721. std::string msg;
  20722. ws::ReadResult ret;
  20723. while ((ret = ws.read(msg))) {
  20724. if (ret == ws::Binary) {
  20725. ws.send(msg.data(), msg.size());
  20726. } else {
  20727. ws.send(msg);
  20728. }
  20729. }
  20730. });
  20731. server_->WebSocket("/ws-echo-string",
  20732. [](const Request &, ws::WebSocket &ws) {
  20733. std::string msg;
  20734. while (ws.read(msg)) {
  20735. ws.send("echo: " + msg);
  20736. }
  20737. });
  20738. server_->WebSocket(
  20739. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20740. // Echo back request metadata
  20741. ws.send("path:" + req.path);
  20742. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20743. std::string msg;
  20744. while (ws.read(msg)) {}
  20745. });
  20746. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20747. std::string msg;
  20748. ws.read(msg); // wait for a message
  20749. ws.close();
  20750. });
  20751. server_->WebSocket("/ws-close-status",
  20752. [](const Request &, ws::WebSocket &ws) {
  20753. std::string msg;
  20754. ws.read(msg); // wait for a message
  20755. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20756. });
  20757. server_->WebSocket(
  20758. "/ws-subprotocol",
  20759. [](const Request &, ws::WebSocket &ws) {
  20760. std::string msg;
  20761. while (ws.read(msg)) {
  20762. ws.send(msg);
  20763. }
  20764. },
  20765. [](const std::vector<std::string> &protocols) -> std::string {
  20766. for (const auto &p : protocols) {
  20767. if (p == "graphql-ws") { return p; }
  20768. }
  20769. return "";
  20770. });
  20771. server_->WebSocket(
  20772. "/ws-subprotocol-unoffered",
  20773. [](const Request &, ws::WebSocket &ws) {
  20774. std::string msg;
  20775. while (ws.read(msg)) {
  20776. ws.send(msg);
  20777. }
  20778. },
  20779. [](const std::vector<std::string> &) -> std::string {
  20780. return "admin";
  20781. });
  20782. }
  20783. void start_server() {
  20784. port_ = server_->bind_to_any_port(HOST);
  20785. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20786. server_->wait_until_ready();
  20787. }
  20788. std::unique_ptr<Server> server_;
  20789. std::thread server_thread_;
  20790. int port_ = 0;
  20791. };
  20792. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20793. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20794. "/ws-echo");
  20795. ASSERT_TRUE(client.connect());
  20796. ASSERT_TRUE(client.is_open());
  20797. ASSERT_TRUE(client.send("Hello WebSocket"));
  20798. std::string msg;
  20799. EXPECT_EQ(ws::Text, client.read(msg));
  20800. EXPECT_EQ("Hello WebSocket", msg);
  20801. client.close();
  20802. }
  20803. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20804. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20805. "/ws-echo");
  20806. ASSERT_TRUE(client.connect());
  20807. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20808. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20809. std::string msg;
  20810. EXPECT_EQ(ws::Binary, client.read(msg));
  20811. EXPECT_EQ(binary_data, msg);
  20812. client.close();
  20813. }
  20814. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20815. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20816. "/ws-echo");
  20817. ASSERT_TRUE(client.connect());
  20818. for (int i = 0; i < 10; i++) {
  20819. auto text = "message " + std::to_string(i);
  20820. ASSERT_TRUE(client.send(text));
  20821. std::string msg;
  20822. ASSERT_TRUE(client.read(msg));
  20823. EXPECT_EQ(text, msg);
  20824. }
  20825. client.close();
  20826. }
  20827. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20829. "/ws-close");
  20830. ASSERT_TRUE(client.connect());
  20831. // Send a message to trigger the server to close
  20832. ASSERT_TRUE(client.send("trigger close"));
  20833. // The server will close, so read should return false
  20834. std::string msg;
  20835. EXPECT_FALSE(client.read(msg));
  20836. EXPECT_FALSE(client.is_open());
  20837. }
  20838. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20839. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20840. "/ws-echo");
  20841. ASSERT_TRUE(client.connect());
  20842. // 128KB message
  20843. std::string large_data(128 * 1024, 'X');
  20844. ASSERT_TRUE(client.send(large_data));
  20845. std::string msg;
  20846. ASSERT_TRUE(client.read(msg));
  20847. EXPECT_EQ(large_data, msg);
  20848. client.close();
  20849. }
  20850. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20852. "/ws-echo");
  20853. ASSERT_TRUE(client.connect());
  20854. const int num_threads = 4;
  20855. std::vector<std::thread> threads;
  20856. std::atomic<int> send_count{0};
  20857. for (int t = 0; t < num_threads; t++) {
  20858. threads.emplace_back([&client, &send_count, t]() {
  20859. for (int i = 0; i < 5; i++) {
  20860. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20861. if (client.send(text)) { send_count++; }
  20862. }
  20863. });
  20864. }
  20865. for (auto &th : threads) {
  20866. th.join();
  20867. }
  20868. int received = 0;
  20869. std::string msg;
  20870. while (received < send_count.load()) {
  20871. if (!client.read(msg)) { break; }
  20872. received++;
  20873. }
  20874. EXPECT_EQ(send_count.load(), received);
  20875. client.close();
  20876. }
  20877. TEST_F(WebSocketIntegrationTest, ReadString) {
  20878. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20879. "/ws-echo-string");
  20880. ASSERT_TRUE(client.connect());
  20881. ASSERT_TRUE(client.send("hello"));
  20882. std::string msg;
  20883. ASSERT_TRUE(client.read(msg));
  20884. EXPECT_EQ("echo: hello", msg);
  20885. ASSERT_TRUE(client.send("world"));
  20886. ASSERT_TRUE(client.read(msg));
  20887. EXPECT_EQ("echo: world", msg);
  20888. client.close();
  20889. }
  20890. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20891. Headers headers = {{"X-Test-Header", "test-value"}};
  20892. ws::WebSocketClient client(
  20893. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20894. ASSERT_TRUE(client.connect());
  20895. std::string msg;
  20896. ASSERT_TRUE(client.read(msg));
  20897. EXPECT_EQ("path:/ws-request-info", msg);
  20898. ASSERT_TRUE(client.read(msg));
  20899. EXPECT_EQ("header:test-value", msg);
  20900. client.close();
  20901. }
  20902. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20904. "/ws-echo");
  20905. client.set_read_timeout(1, 0); // 1 second
  20906. ASSERT_TRUE(client.connect());
  20907. // Don't send anything — server echo handler waits for a message, so read()
  20908. // should time out. The connection survives it: nothing was consumed.
  20909. std::string msg;
  20910. EXPECT_EQ(client.read(msg), ws::Timeout);
  20911. EXPECT_TRUE(client.is_open());
  20912. // And it is still usable afterwards.
  20913. EXPECT_TRUE(client.send("after timeout"));
  20914. EXPECT_EQ(client.read(msg), ws::Text);
  20915. EXPECT_EQ(msg, "after timeout");
  20916. }
  20917. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20918. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20919. "/ws-echo");
  20920. client.set_read_timeout(1, 0);
  20921. ASSERT_TRUE(client.connect());
  20922. ASSERT_TRUE(client.send("first"));
  20923. std::string msg;
  20924. ASSERT_EQ(client.read(msg), ws::Text);
  20925. ASSERT_EQ(msg, "first");
  20926. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20927. // not be used with a read timeout: it would reprocess the previous message.
  20928. EXPECT_EQ(client.read(msg), ws::Timeout);
  20929. EXPECT_EQ(msg, "first");
  20930. }
  20931. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20933. "/ws-echo");
  20934. ASSERT_TRUE(client.connect());
  20935. // Setting it once the connection is open reaches the live stream, not just
  20936. // the seed for the next connect().
  20937. client.set_read_timeout(1, 0);
  20938. std::string msg;
  20939. EXPECT_EQ(client.read(msg), ws::Timeout);
  20940. EXPECT_TRUE(client.is_open());
  20941. }
  20942. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20943. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20944. "/ws-echo");
  20945. client.set_read_timeout(5, 0);
  20946. ASSERT_TRUE(client.connect());
  20947. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20948. // The server should reject it and close the connection.
  20949. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20950. client.send(oversized);
  20951. // The server's read() should have failed due to payload limit,
  20952. // so our read() should return false (connection closed).
  20953. std::string msg;
  20954. EXPECT_FALSE(client.read(msg));
  20955. }
  20956. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20958. "/ws-echo");
  20959. client.set_read_timeout(10, 0);
  20960. ASSERT_TRUE(client.connect());
  20961. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20962. // This should succeed.
  20963. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20964. ASSERT_TRUE(client.send(at_limit));
  20965. std::string msg;
  20966. ASSERT_TRUE(client.read(msg));
  20967. EXPECT_EQ(at_limit.size(), msg.size());
  20968. client.close();
  20969. }
  20970. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20972. "/nonexistent");
  20973. auto res = client.connect();
  20974. EXPECT_FALSE(res);
  20975. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20976. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20977. EXPECT_FALSE(client.is_open());
  20978. }
  20979. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20981. "/ws-echo");
  20982. ASSERT_TRUE(client.connect());
  20983. ASSERT_TRUE(client.send(""));
  20984. std::string msg;
  20985. EXPECT_EQ(ws::Text, client.read(msg));
  20986. EXPECT_EQ("", msg);
  20987. client.close();
  20988. }
  20989. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20990. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20991. "/ws-echo");
  20992. // First connection
  20993. ASSERT_TRUE(client.connect());
  20994. ASSERT_TRUE(client.send("first"));
  20995. std::string msg;
  20996. ASSERT_TRUE(client.read(msg));
  20997. EXPECT_EQ("first", msg);
  20998. client.close();
  20999. EXPECT_FALSE(client.is_open());
  21000. // Reconnect using the same client object
  21001. ASSERT_TRUE(client.connect());
  21002. ASSERT_TRUE(client.is_open());
  21003. ASSERT_TRUE(client.send("second"));
  21004. ASSERT_TRUE(client.read(msg));
  21005. EXPECT_EQ("second", msg);
  21006. client.close();
  21007. }
  21008. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21009. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21010. "/ws-close-status");
  21011. ASSERT_TRUE(client.connect());
  21012. // Trigger the server to close with GoingAway status
  21013. ASSERT_TRUE(client.send("trigger"));
  21014. // read() should return false after receiving the close frame
  21015. std::string msg;
  21016. EXPECT_FALSE(client.read(msg));
  21017. EXPECT_FALSE(client.is_open());
  21018. }
  21019. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21020. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21021. "/ws-echo");
  21022. ASSERT_TRUE(client.connect());
  21023. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21024. EXPECT_FALSE(client.is_open());
  21025. }
  21026. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21027. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21028. ws::WebSocketClient client(
  21029. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21030. ASSERT_TRUE(client.connect());
  21031. // Server should have selected graphql-ws
  21032. EXPECT_EQ("graphql-ws", client.subprotocol());
  21033. client.close();
  21034. }
  21035. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21036. Headers headers;
  21037. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21038. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21039. ws::WebSocketClient client(
  21040. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21041. ASSERT_TRUE(client.connect());
  21042. // The offer on the second field line counts too, so graphql-ws is selected
  21043. EXPECT_EQ("graphql-ws", client.subprotocol());
  21044. client.close();
  21045. }
  21046. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21047. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21048. ws::WebSocketClient client(
  21049. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21050. ASSERT_TRUE(client.connect());
  21051. // Server should not have selected any subprotocol
  21052. EXPECT_TRUE(client.subprotocol().empty());
  21053. client.close();
  21054. }
  21055. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21056. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21057. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21058. "/ws-subprotocol-unoffered",
  21059. headers);
  21060. ASSERT_TRUE(client.connect());
  21061. EXPECT_TRUE(client.subprotocol().empty());
  21062. client.close();
  21063. }
  21064. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21065. // Connect without requesting any subprotocol
  21066. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21067. "/ws-subprotocol");
  21068. ASSERT_TRUE(client.connect());
  21069. EXPECT_TRUE(client.subprotocol().empty());
  21070. client.close();
  21071. }
  21072. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21073. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21074. "/ws-echo");
  21075. client.set_tcp_nodelay(true);
  21076. client.set_connection_timeout(3, 0);
  21077. bool socket_options_called = false;
  21078. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21079. ASSERT_TRUE(client.connect());
  21080. ASSERT_TRUE(client.is_open());
  21081. EXPECT_TRUE(socket_options_called);
  21082. ASSERT_TRUE(client.send("hello"));
  21083. std::string msg;
  21084. auto result = client.read(msg);
  21085. EXPECT_EQ(result, ws::ReadResult::Text);
  21086. EXPECT_EQ(msg, "hello");
  21087. client.close();
  21088. }
  21089. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21090. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21091. "/ws-echo");
  21092. client.set_connection_timeout(std::chrono::seconds(3));
  21093. client.set_write_timeout(std::chrono::seconds(3));
  21094. // A sub-second remainder exercises the seconds/microseconds split.
  21095. client.set_read_timeout(std::chrono::milliseconds(1500));
  21096. ASSERT_TRUE(client.connect());
  21097. auto start = std::chrono::steady_clock::now();
  21098. std::string msg;
  21099. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21100. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21101. std::chrono::steady_clock::now() - start)
  21102. .count();
  21103. // Above 1s so that dropping the microseconds half of the split fails here.
  21104. // Ignoring the setter altogether would not reach this line at all: a client
  21105. // waits forever by default.
  21106. EXPECT_GE(elapsed, 1400);
  21107. EXPECT_LT(elapsed, 30000);
  21108. }
  21109. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21110. Server svr;
  21111. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21112. if (!req.has_header("Authorization")) {
  21113. res.status = StatusCode::Unauthorized_401;
  21114. res.set_content("Unauthorized", "text/plain");
  21115. return Server::HandlerResponse::Handled;
  21116. }
  21117. return Server::HandlerResponse::Unhandled;
  21118. });
  21119. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21120. std::string msg;
  21121. while (ws.read(msg)) {
  21122. ws.send(msg);
  21123. }
  21124. });
  21125. auto port = svr.bind_to_any_port("localhost");
  21126. std::thread t([&]() { svr.listen_after_bind(); });
  21127. svr.wait_until_ready();
  21128. // Without Authorization header - should be rejected before upgrade
  21129. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21130. EXPECT_FALSE(client1.connect());
  21131. // The rejection is framed like any other HTTP response
  21132. {
  21133. Client cli("localhost", port);
  21134. Headers headers = {{"Upgrade", "websocket"},
  21135. {"Connection", "Upgrade"},
  21136. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21137. {"Sec-WebSocket-Version", "13"}};
  21138. auto res = cli.Get("/ws", headers);
  21139. ASSERT_TRUE(res);
  21140. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21141. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21142. EXPECT_EQ("Unauthorized", res->body);
  21143. }
  21144. // With Authorization header - should succeed
  21145. Headers headers = {{"Authorization", "Bearer token123"}};
  21146. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21147. headers);
  21148. ASSERT_TRUE(client2.connect());
  21149. ASSERT_TRUE(client2.send("hello"));
  21150. std::string msg;
  21151. ASSERT_TRUE(client2.read(msg));
  21152. EXPECT_EQ("hello", msg);
  21153. client2.close();
  21154. svr.stop();
  21155. t.join();
  21156. }
  21157. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21158. Server svr;
  21159. std::atomic<int> pre_request_calls{0};
  21160. std::atomic<bool> route_matched{false};
  21161. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21162. pre_request_calls++;
  21163. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21164. if (req.get_header_value("Authorization") != "Bearer token123") {
  21165. res.status = StatusCode::Unauthorized_401;
  21166. res.set_content("Unauthorized", "text/plain");
  21167. return Server::HandlerResponse::Handled;
  21168. }
  21169. return Server::HandlerResponse::Unhandled;
  21170. });
  21171. std::atomic<bool> handler_called{false};
  21172. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21173. handler_called = true;
  21174. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21175. });
  21176. auto port = svr.bind_to_any_port("localhost");
  21177. std::thread t([&]() { svr.listen_after_bind(); });
  21178. svr.wait_until_ready();
  21179. // Without Authorization header - should be rejected before upgrade
  21180. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21181. "/ws/1");
  21182. EXPECT_FALSE(client1.connect());
  21183. EXPECT_FALSE(handler_called);
  21184. EXPECT_EQ(1, pre_request_calls);
  21185. EXPECT_TRUE(route_matched);
  21186. // The rejection is an ordinary HTTP response, not a protocol switch
  21187. {
  21188. Client cli("localhost", port);
  21189. Headers headers = {{"Upgrade", "websocket"},
  21190. {"Connection", "Upgrade"},
  21191. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21192. {"Sec-WebSocket-Version", "13"}};
  21193. auto res = cli.Get("/ws/1", headers);
  21194. ASSERT_TRUE(res);
  21195. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21196. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21197. EXPECT_EQ("Unauthorized", res->body);
  21198. }
  21199. EXPECT_FALSE(handler_called);
  21200. // With Authorization header - should succeed
  21201. Headers headers = {{"Authorization", "Bearer token123"}};
  21202. ws::WebSocketClient client2(
  21203. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21204. ASSERT_TRUE(client2.connect());
  21205. std::string msg;
  21206. ASSERT_TRUE(client2.read(msg));
  21207. EXPECT_EQ("/ws/:id 2", msg);
  21208. EXPECT_TRUE(handler_called);
  21209. client2.close();
  21210. svr.stop();
  21211. t.join();
  21212. }
  21213. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21214. Server svr;
  21215. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21216. // A read timeout is how a handler gets control back. Without it, a handler
  21217. // parked in read() can never write on the connection it is reading.
  21218. ws.set_read_timeout(std::chrono::milliseconds(100));
  21219. std::string msg;
  21220. while (ws.is_open()) {
  21221. auto r = ws.read(msg);
  21222. if (r == httplib::ws::Timeout) {
  21223. ws.send("tick");
  21224. continue;
  21225. }
  21226. if (r == httplib::ws::Fail) { break; }
  21227. ws.send(msg);
  21228. }
  21229. });
  21230. auto port = svr.bind_to_any_port("localhost");
  21231. std::thread t([&]() { svr.listen_after_bind(); });
  21232. svr.wait_until_ready();
  21233. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21234. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21235. ASSERT_TRUE(client.connect());
  21236. // The client sends nothing, so anything it receives came out of the
  21237. // handler's timeout path.
  21238. std::string msg;
  21239. ASSERT_EQ(client.read(msg), ws::Text);
  21240. EXPECT_EQ("tick", msg);
  21241. client.close();
  21242. svr.stop();
  21243. t.join();
  21244. }
  21245. // Stream::read may return fewer bytes than asked for. This is that contract at
  21246. // its worst -- one byte per call -- which is what a frame header straddling a
  21247. // read buffer's boundary looks like to the frame parser.
  21248. class WsByteAtATimeStream : public Stream {
  21249. public:
  21250. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21251. bool is_readable() const override { return true; }
  21252. bool wait_readable() const override { return true; }
  21253. bool wait_writable() const override { return true; }
  21254. ssize_t read(char *ptr, size_t size) override {
  21255. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21256. *ptr = data_[pos_++];
  21257. return 1;
  21258. }
  21259. ssize_t write(const char *, size_t size) override {
  21260. return static_cast<ssize_t>(size);
  21261. }
  21262. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21263. ip = "127.0.0.1";
  21264. port = 0;
  21265. }
  21266. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21267. ip = "127.0.0.1";
  21268. port = 0;
  21269. }
  21270. socket_t socket() const override { return INVALID_SOCKET; }
  21271. time_t duration() const override { return 0; }
  21272. private:
  21273. std::string data_;
  21274. size_t pos_ = 0;
  21275. };
  21276. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21277. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21278. // length and the mask key are all multi-byte fields here. Each used to be
  21279. // read with a single read() call, which fails as soon as one is split.
  21280. std::string body(200, 'x');
  21281. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21282. std::string frame;
  21283. frame += static_cast<char>(0x81); // FIN + Text
  21284. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21285. frame += static_cast<char>(body.size() >> 8);
  21286. frame += static_cast<char>(body.size() & 0xff);
  21287. for (size_t i = 0; i < 4; i++) {
  21288. frame += static_cast<char>(mask[i]);
  21289. }
  21290. for (size_t i = 0; i < body.size(); i++) {
  21291. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21292. }
  21293. WsByteAtATimeStream strm(frame);
  21294. ws::Opcode opcode;
  21295. std::string payload;
  21296. bool fin = false;
  21297. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21298. /*expect_masked=*/true, 1024),
  21299. ws::impl::FrameRead::Ok);
  21300. EXPECT_TRUE(fin);
  21301. EXPECT_EQ(opcode, ws::Opcode::Text);
  21302. EXPECT_EQ(payload, body);
  21303. }
  21304. TEST(WebSocketTest, QueryStringInHandshake) {
  21305. Server svr;
  21306. std::mutex mtx;
  21307. std::string received_target;
  21308. std::string received_token;
  21309. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21310. {
  21311. std::lock_guard<std::mutex> lock(mtx);
  21312. received_target = req.target;
  21313. if (req.has_param("token")) {
  21314. received_token = req.get_param_value("token");
  21315. }
  21316. }
  21317. std::string msg;
  21318. while (ws.read(msg)) {
  21319. ws.send(msg);
  21320. }
  21321. });
  21322. auto port = svr.bind_to_any_port("localhost");
  21323. std::thread t([&]() { svr.listen_after_bind(); });
  21324. svr.wait_until_ready();
  21325. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21326. "/ws?token=ABC&session=123");
  21327. ASSERT_TRUE(client.connect());
  21328. // Round-trip ensures the handler has run and captured the request.
  21329. ASSERT_TRUE(client.send("hello"));
  21330. std::string msg;
  21331. ASSERT_TRUE(client.read(msg));
  21332. EXPECT_EQ("hello", msg);
  21333. client.close();
  21334. {
  21335. std::lock_guard<std::mutex> lock(mtx);
  21336. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21337. EXPECT_EQ("ABC", received_token);
  21338. }
  21339. svr.stop();
  21340. t.join();
  21341. }
  21342. // Run a handshake against a throwaway server and hand the request the server
  21343. // received back to the caller, so tests can assert on the headers the client
  21344. // actually put on the wire.
  21345. static void capture_websocket_handshake_request(
  21346. const Headers &client_headers,
  21347. std::function<void(const Request &, int port)> verify) {
  21348. Server svr;
  21349. std::mutex mtx;
  21350. Request received;
  21351. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21352. {
  21353. std::lock_guard<std::mutex> lock(mtx);
  21354. received = req;
  21355. }
  21356. std::string msg;
  21357. while (ws.read(msg)) {
  21358. ws.send(msg);
  21359. }
  21360. });
  21361. auto port = svr.bind_to_any_port("localhost");
  21362. std::thread t([&]() { svr.listen_after_bind(); });
  21363. auto se = detail::scope_exit([&] {
  21364. svr.stop();
  21365. t.join();
  21366. });
  21367. svr.wait_until_ready();
  21368. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21369. client_headers);
  21370. ASSERT_TRUE(client.connect());
  21371. ASSERT_TRUE(client.send("hello"));
  21372. std::string msg;
  21373. ASSERT_TRUE(client.read(msg));
  21374. client.close();
  21375. {
  21376. std::lock_guard<std::mutex> lock(mtx);
  21377. verify(received, port);
  21378. }
  21379. }
  21380. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21381. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21382. // Non-default port must be present in the Host header. Default ports
  21383. // (80/443) are omitted; that logic is covered by
  21384. // MakeHostAndPortStringTest.
  21385. EXPECT_EQ("localhost:" + std::to_string(port),
  21386. req.get_header_value("Host"));
  21387. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21388. req.get_header_value("User-Agent"));
  21389. EXPECT_FALSE(req.has_header("Accept"));
  21390. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21391. EXPECT_FALSE(req.has_header("Content-Length"));
  21392. });
  21393. }
  21394. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21395. capture_websocket_handshake_request(
  21396. {{"Host", "example.com"},
  21397. {"User-Agent", "custom-agent"},
  21398. {"X-Custom", "value"}},
  21399. [](const Request &req, int) {
  21400. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21401. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21402. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21403. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21404. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21405. });
  21406. }
  21407. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21408. capture_websocket_handshake_request(
  21409. {{"Upgrade", "bogus"},
  21410. {"Connection", "close"},
  21411. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21412. {"Sec-WebSocket-Version", "8"}},
  21413. [](const Request &req, int) {
  21414. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21415. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21416. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21417. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21418. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21419. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21420. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21421. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21422. req.get_header_value("Sec-WebSocket-Key"));
  21423. });
  21424. }
  21425. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21426. // A header the client refuses to send must abort the handshake before any
  21427. // part of it reaches the wire; a lone request line would otherwise sit in
  21428. // the peer's buffer as a truncated request.
  21429. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21430. ASSERT_NE(INVALID_SOCKET, srv);
  21431. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21432. sockaddr_in addr{};
  21433. addr.sin_family = AF_INET;
  21434. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21435. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21436. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21437. ASSERT_EQ(0, ::listen(srv, 1));
  21438. sockaddr_in bound{};
  21439. socklen_t bound_len = sizeof(bound);
  21440. ASSERT_EQ(
  21441. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21442. auto port = ntohs(bound.sin_port);
  21443. ssize_t received = -1;
  21444. std::thread t([&] {
  21445. // Bound every blocking call so a regression fails the test with a bad
  21446. // value instead of hanging the suite.
  21447. fd_set rfds;
  21448. FD_ZERO(&rfds);
  21449. FD_SET(srv, &rfds);
  21450. timeval tv{5, 0};
  21451. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21452. 0) {
  21453. return;
  21454. }
  21455. sockaddr_in cli_addr{};
  21456. socklen_t cli_len = sizeof(cli_addr);
  21457. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21458. if (cli == INVALID_SOCKET) { return; }
  21459. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21460. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21461. char buf[4096];
  21462. received = ::recv(cli, buf, sizeof(buf), 0);
  21463. });
  21464. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21465. // connect() has already shut the socket down by the time it returns false,
  21466. // so the peer sees EOF without waiting for the client to be destroyed.
  21467. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21468. {{"X-Bad", "a\r\nInjected: 1"}});
  21469. EXPECT_FALSE(client.connect());
  21470. t.join();
  21471. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21472. EXPECT_EQ(0, received);
  21473. }
  21474. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21475. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21476. // contains "upgrade" as a substring is a different token and must not
  21477. // start a WebSocket handshake.
  21478. auto make_request = [](const std::vector<std::string> &connection_values) {
  21479. Request req;
  21480. req.method = "GET";
  21481. req.headers.emplace("Upgrade", "websocket");
  21482. for (const auto &value : connection_values) {
  21483. req.headers.emplace("Connection", value);
  21484. }
  21485. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21486. req.headers.emplace("Sec-WebSocket-Version", "13");
  21487. return req;
  21488. };
  21489. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21490. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21491. EXPECT_TRUE(
  21492. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21493. EXPECT_TRUE(
  21494. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21495. EXPECT_TRUE(
  21496. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21497. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21498. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21499. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21500. EXPECT_FALSE(
  21501. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21502. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21503. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21504. }
  21505. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21506. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21507. // asks recipients to match each protocol-name case-insensitively, and RFC
  21508. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21509. // client naming websocket alongside another protocol, or on a second field
  21510. // line, is offering websocket; a value that merely contains "websocket" as a
  21511. // substring is a different protocol name and is not.
  21512. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21513. Request req;
  21514. req.method = "GET";
  21515. for (const auto &value : upgrade_values) {
  21516. req.headers.emplace("Upgrade", value);
  21517. }
  21518. req.headers.emplace("Connection", "Upgrade");
  21519. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21520. req.headers.emplace("Sec-WebSocket-Version", "13");
  21521. return req;
  21522. };
  21523. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21524. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21525. EXPECT_TRUE(
  21526. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21527. EXPECT_TRUE(
  21528. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21529. EXPECT_TRUE(
  21530. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21531. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21532. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21533. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21534. EXPECT_FALSE(
  21535. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21536. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21537. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21538. }
  21539. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21540. Server svr;
  21541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  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. Headers headers = {{"Upgrade", "websocket"},
  21550. {"Connection", "notupgrade"},
  21551. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21552. {"Sec-WebSocket-Version", "13"}};
  21553. Client cli("localhost", port);
  21554. auto res = cli.Get("/ws", headers);
  21555. // The route exists only as a WebSocket route, so a request that fails the
  21556. // handshake check falls through to ordinary routing.
  21557. ASSERT_TRUE(res);
  21558. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21559. }
  21560. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21561. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21562. // Connection value is the only thing left for the client to reject.
  21563. Server svr;
  21564. svr.Get("/ws", [](const Request &req, Response &res) {
  21565. res.status = StatusCode::SwitchingProtocol_101;
  21566. res.set_header("Upgrade", "websocket");
  21567. res.set_header("Connection", "notupgrade");
  21568. res.set_header("Sec-WebSocket-Accept",
  21569. detail::websocket_accept_key(
  21570. req.get_header_value("Sec-WebSocket-Key")));
  21571. });
  21572. auto port = svr.bind_to_any_port("localhost");
  21573. std::thread t([&]() { svr.listen_after_bind(); });
  21574. auto se = detail::scope_exit([&] {
  21575. svr.stop();
  21576. t.join();
  21577. });
  21578. svr.wait_until_ready();
  21579. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21580. auto res = client.connect();
  21581. EXPECT_FALSE(res);
  21582. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21583. EXPECT_FALSE(client.is_open());
  21584. }
  21585. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21586. Server svr;
  21587. svr.Get("/ws", [](const Request &req, Response &res) {
  21588. res.status = StatusCode::SwitchingProtocol_101;
  21589. res.set_header("Upgrade", "websocket");
  21590. res.set_header("Connection", "Upgrade");
  21591. res.set_header("Sec-WebSocket-Accept",
  21592. detail::websocket_accept_key(
  21593. req.get_header_value("Sec-WebSocket-Key")));
  21594. res.set_header("Sec-WebSocket-Protocol", "admin");
  21595. });
  21596. auto port = svr.bind_to_any_port("localhost");
  21597. std::thread t([&]() { svr.listen_after_bind(); });
  21598. auto se = detail::scope_exit([&] {
  21599. svr.stop();
  21600. t.join();
  21601. });
  21602. svr.wait_until_ready();
  21603. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21604. // Server selects a subprotocol the client never offered
  21605. {
  21606. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21607. ws::WebSocketClient client(url, headers);
  21608. auto res = client.connect();
  21609. EXPECT_FALSE(res);
  21610. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21611. EXPECT_FALSE(client.is_open());
  21612. EXPECT_TRUE(client.subprotocol().empty());
  21613. }
  21614. // Client offered none but the server named one anyway
  21615. {
  21616. ws::WebSocketClient client(url);
  21617. auto res = client.connect();
  21618. EXPECT_FALSE(res);
  21619. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21620. EXPECT_FALSE(client.is_open());
  21621. EXPECT_TRUE(client.subprotocol().empty());
  21622. }
  21623. }
  21624. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21625. // The socket path doubles as the URL host, so it must not contain '/'.
  21626. const char *shard = getenv("GTEST_SHARD_INDEX");
  21627. const std::string sock_path =
  21628. shard ? std::string("httplib-ws-") + shard + ".sock"
  21629. : std::string("httplib-ws.sock");
  21630. std::remove(sock_path.c_str());
  21631. Server svr;
  21632. std::mutex mtx;
  21633. std::string received_host;
  21634. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21635. {
  21636. std::lock_guard<std::mutex> lock(mtx);
  21637. received_host = req.get_header_value("Host");
  21638. }
  21639. std::string msg;
  21640. while (ws.read(msg)) {
  21641. ws.send(msg);
  21642. }
  21643. });
  21644. svr.set_address_family(AF_UNIX);
  21645. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21646. auto se = detail::scope_exit([&] {
  21647. svr.stop();
  21648. t.join();
  21649. std::remove(sock_path.c_str());
  21650. });
  21651. svr.wait_until_ready();
  21652. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21653. client.set_address_family(AF_UNIX);
  21654. ASSERT_TRUE(client.connect());
  21655. ASSERT_TRUE(client.send("hello"));
  21656. std::string msg;
  21657. ASSERT_TRUE(client.read(msg));
  21658. client.close();
  21659. {
  21660. std::lock_guard<std::mutex> lock(mtx);
  21661. // There is no host:port for a Unix socket, so the same "localhost"
  21662. // placeholder the HTTP client uses is expected.
  21663. EXPECT_EQ("localhost", received_host);
  21664. }
  21665. }
  21666. // Two threads must never parse WebSocket frames from the same stream.
  21667. // close() used to read the peer's Close reply with its own frame read, so it
  21668. // raced a reader thread that was in the middle of a payload: the payload loop
  21669. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21670. // so bytes taken by close() were replaced with bytes from further along the
  21671. // stream. The message kept its length and silently changed content.
  21672. //
  21673. // The raw peer below sends a frame header plus part of the payload, waits for
  21674. // the handler to call close(), and only then sends the rest. Whichever thread
  21675. // would win the race for those bytes, the message must arrive intact, because
  21676. // close() must not touch the stream while read() owns it.
  21677. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21678. #ifndef _WIN32
  21679. signal(SIGPIPE, SIG_IGN);
  21680. #endif
  21681. const size_t payload_len = 120; // fits the 7-bit length field
  21682. const size_t prefix_len = 8;
  21683. const int attempts = 8;
  21684. std::string expected(payload_len, '\0');
  21685. for (size_t i = 0; i < payload_len; i++) {
  21686. expected[i] = static_cast<char>('a' + i % 26);
  21687. }
  21688. std::atomic<bool> peer_stalled{false};
  21689. std::atomic<bool> handler_done{false};
  21690. std::mutex received_mutex;
  21691. std::vector<std::string> received;
  21692. // Bound every wait, so a regression fails the test instead of hanging the
  21693. // suite.
  21694. auto wait_for = [](const std::atomic<bool> &flag) {
  21695. for (int i = 0; i < 500 && !flag; i++) {
  21696. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21697. }
  21698. };
  21699. Server svr;
  21700. svr.set_websocket_ping_interval(0);
  21701. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21702. std::thread reader([&]() {
  21703. std::string msg;
  21704. while (ws.read(msg)) {
  21705. std::lock_guard<std::mutex> guard(received_mutex);
  21706. received.push_back(msg);
  21707. }
  21708. });
  21709. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21710. // inside read_websocket_frame() when close() runs.
  21711. wait_for(peer_stalled);
  21712. ws.close();
  21713. reader.join();
  21714. handler_done = true;
  21715. });
  21716. auto port = svr.bind_to_any_port("127.0.0.1");
  21717. std::thread t([&]() { svr.listen_after_bind(); });
  21718. auto se = detail::scope_exit([&] {
  21719. svr.stop();
  21720. t.join();
  21721. });
  21722. svr.wait_until_ready();
  21723. auto send_bytes = [](socket_t s, const std::string &data) {
  21724. #ifdef _WIN32
  21725. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21726. #else
  21727. auto n = ::send(s, data.data(), data.size(), 0);
  21728. #endif
  21729. return n == static_cast<decltype(n)>(data.size());
  21730. };
  21731. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21732. // Every length used here fits the 7-bit length field.
  21733. auto masked_header = [](uint8_t first_byte, size_t len) {
  21734. std::string h;
  21735. h += static_cast<char>(first_byte);
  21736. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21737. h.append(4, '\0'); // mask key
  21738. return h;
  21739. };
  21740. for (int attempt = 0; attempt < attempts; attempt++) {
  21741. peer_stalled = false;
  21742. handler_done = false;
  21743. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21744. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21745. auto se_sock = detail::scope_exit([&] {
  21746. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21747. });
  21748. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21749. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21750. sockaddr_in addr{};
  21751. addr.sin_family = AF_INET;
  21752. addr.sin_port = htons(static_cast<uint16_t>(port));
  21753. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21754. ASSERT_EQ(
  21755. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21756. << "attempt " << attempt;
  21757. ASSERT_TRUE(send_bytes(sock,
  21758. "GET /ws HTTP/1.1\r\n"
  21759. "Host: 127.0.0.1\r\n"
  21760. "Upgrade: websocket\r\n"
  21761. "Connection: Upgrade\r\n"
  21762. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21763. "Sec-WebSocket-Version: 13\r\n"
  21764. "\r\n"))
  21765. << "attempt " << attempt;
  21766. std::string response;
  21767. while (response.find("\r\n\r\n") == std::string::npos) {
  21768. char buf[512];
  21769. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21770. if (n <= 0) { break; }
  21771. response.append(buf, static_cast<size_t>(n));
  21772. }
  21773. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21774. << "attempt " << attempt;
  21775. // Send the header of a Binary message but only the first prefix_len bytes
  21776. // of its payload, leaving the reader thread stalled inside the payload.
  21777. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21778. expected.substr(0, prefix_len)))
  21779. << "attempt " << attempt;
  21780. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21781. peer_stalled = true;
  21782. // Let close() send its Close frame and park in its own read before the
  21783. // rest of the payload arrives, so both threads are waiting for it.
  21784. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21785. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21786. close_frame += static_cast<char>(0x03); // status 1000
  21787. close_frame += static_cast<char>(0xE8);
  21788. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21789. << "attempt " << attempt;
  21790. // Closing the peer releases the reader thread even on the buggy path,
  21791. // where it waits for bytes another thread already consumed.
  21792. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21793. detail::close_socket(sock);
  21794. sock = INVALID_SOCKET;
  21795. wait_for(handler_done);
  21796. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21797. }
  21798. std::lock_guard<std::mutex> guard(received_mutex);
  21799. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21800. << "a message in flight when close() ran was dropped";
  21801. for (size_t i = 0; i < received.size(); i++) {
  21802. EXPECT_EQ(expected, received[i]) << "message " << i;
  21803. }
  21804. }
  21805. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21806. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21807. protected:
  21808. void SetUp() override {
  21809. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21810. SERVER_PRIVATE_KEY_FILE);
  21811. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21812. std::string msg;
  21813. ws::ReadResult ret;
  21814. while ((ret = ws.read(msg))) {
  21815. if (ret == ws::Binary) {
  21816. ws.send(msg.data(), msg.size());
  21817. } else {
  21818. ws.send(msg);
  21819. }
  21820. }
  21821. });
  21822. port_ = server_->bind_to_any_port(HOST);
  21823. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21824. server_->wait_until_ready();
  21825. }
  21826. void TearDown() override {
  21827. server_->stop();
  21828. if (server_thread_.joinable()) { server_thread_.join(); }
  21829. }
  21830. std::unique_ptr<SSLServer> server_;
  21831. std::thread server_thread_;
  21832. int port_ = 0;
  21833. };
  21834. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21835. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21836. "/ws-echo");
  21837. client.enable_server_certificate_verification(false);
  21838. ASSERT_TRUE(client.connect());
  21839. ASSERT_TRUE(client.is_open());
  21840. ASSERT_TRUE(client.send("Hello WSS"));
  21841. std::string msg;
  21842. EXPECT_EQ(ws::Text, client.read(msg));
  21843. EXPECT_EQ("Hello WSS", msg);
  21844. client.close();
  21845. }
  21846. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21847. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21848. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21849. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21850. // client (without calling close() first) is the only path that runs
  21851. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21852. // bug exactly.
  21853. //
  21854. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21855. // when linked against an instrumented libssl; run under Valgrind to catch it
  21856. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21857. // suite (the freed session otherwise stalls on the close handshake) — this test
  21858. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21859. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21860. {
  21861. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21862. "/ws-echo");
  21863. client.enable_server_certificate_verification(false);
  21864. client.set_read_timeout(2, 0);
  21865. client.set_write_timeout(2, 0);
  21866. ASSERT_TRUE(client.connect());
  21867. ASSERT_TRUE(client.is_open());
  21868. ASSERT_TRUE(client.send("still open"));
  21869. // Intentionally do NOT call client.close(): leaving scope runs
  21870. // shutdown_and_close() with the WebSocket still open, which must send the
  21871. // close frame while the TLS session is still alive.
  21872. }
  21873. }
  21874. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21875. // shutdown_and_close() at the start of connect(), reproducing the same
  21876. // use-after-free within the test body rather than at scope exit. The second
  21877. // connect must succeed and echo, proving the close handshake ran over a live
  21878. // session. See the note above about memory-tool requirements.
  21879. TEST_F(WebSocketSSLIntegrationTest,
  21880. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21881. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21882. "/ws-echo");
  21883. client.enable_server_certificate_verification(false);
  21884. client.set_read_timeout(2, 0);
  21885. client.set_write_timeout(2, 0);
  21886. ASSERT_TRUE(client.connect());
  21887. ASSERT_TRUE(client.is_open());
  21888. ASSERT_TRUE(client.send("still open"));
  21889. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21890. // the still-open connection, which must not touch a freed TLS session.
  21891. ASSERT_TRUE(client.connect());
  21892. ASSERT_TRUE(client.is_open());
  21893. ASSERT_TRUE(client.send("after reconnect"));
  21894. std::string msg;
  21895. EXPECT_EQ(ws::Text, client.read(msg));
  21896. EXPECT_EQ("after reconnect", msg);
  21897. client.close();
  21898. }
  21899. #endif
  21900. #ifdef CPPHTTPLIB_SSL_ENABLED
  21901. class WebSocketSSLCATest : public ::testing::Test {
  21902. protected:
  21903. void SetUp() override {
  21904. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21905. SERVER_PRIVATE_KEY_FILE);
  21906. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21907. std::string msg;
  21908. while (ws.read(msg)) {
  21909. ws.send(msg);
  21910. }
  21911. });
  21912. port_ = server_->bind_to_any_port("127.0.0.1");
  21913. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21914. server_->wait_until_ready();
  21915. }
  21916. void TearDown() override {
  21917. server_->stop();
  21918. if (server_thread_.joinable()) { server_thread_.join(); }
  21919. }
  21920. std::string url() const {
  21921. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21922. }
  21923. std::unique_ptr<SSLServer> server_;
  21924. std::thread server_thread_;
  21925. int port_ = 0;
  21926. };
  21927. // A custom CA loaded as PEM verifies the server with full certificate
  21928. // verification enabled
  21929. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21930. ws::WebSocketClient client(url());
  21931. std::string cert;
  21932. read_file(SERVER_CERT2_FILE, cert);
  21933. client.load_ca_cert_store(cert.c_str(), cert.size());
  21934. ASSERT_TRUE(client.connect());
  21935. ASSERT_TRUE(client.send("hello"));
  21936. std::string msg;
  21937. EXPECT_EQ(ws::Text, client.read(msg));
  21938. EXPECT_EQ("hello", msg);
  21939. client.close();
  21940. }
  21941. // A custom CA that does not cover the server must fail verification (the
  21942. // custom CA is exclusive; system certs are not loaded alongside it)
  21943. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21944. ws::WebSocketClient client(url());
  21945. std::string cert;
  21946. read_file(CLIENT_CA_CERT_FILE, cert);
  21947. client.load_ca_cert_store(cert.c_str(), cert.size());
  21948. auto res = client.connect();
  21949. ASSERT_FALSE(res);
  21950. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21951. EXPECT_EQ(-1, res.status());
  21952. EXPECT_NE(0u, res.ssl_backend_error());
  21953. }
  21954. // The same CA as a file path rather than PEM in memory
  21955. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21956. ws::WebSocketClient client(url());
  21957. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21958. ASSERT_TRUE(client.connect());
  21959. ASSERT_TRUE(client.send("hello"));
  21960. std::string msg;
  21961. EXPECT_EQ(ws::Text, client.read(msg));
  21962. EXPECT_EQ("hello", msg);
  21963. client.close();
  21964. }
  21965. // ...and a CA file that does not cover the server still fails, so it is the
  21966. // path above that decides the outcome
  21967. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21968. ws::WebSocketClient client(url());
  21969. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21970. ASSERT_FALSE(client.connect());
  21971. }
  21972. // Regression test: reconnecting with a native custom CA store used to reuse
  21973. // a store handle the previous TLS context had already freed (use-after-free
  21974. // under the OpenSSL backend). The context now lives as long as the client.
  21975. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21976. ws::WebSocketClient client(url());
  21977. std::string cert;
  21978. read_file(SERVER_CERT2_FILE, cert);
  21979. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21980. ASSERT_TRUE(client.connect());
  21981. client.close();
  21982. ASSERT_TRUE(client.connect());
  21983. ASSERT_TRUE(client.send("again"));
  21984. std::string msg;
  21985. EXPECT_EQ(ws::Text, client.read(msg));
  21986. EXPECT_EQ("again", msg);
  21987. client.close();
  21988. }
  21989. // Regression test: a certificate with a trusted chain but no identity match
  21990. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21991. // verification entirely for IP hosts, so this connection succeeded there.
  21992. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21993. // chain verification while the identity check must still fail.
  21994. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21996. ASSERT_TRUE(svr.is_valid());
  21997. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21998. std::string msg;
  21999. while (ws.read(msg)) {
  22000. ws.send(msg);
  22001. }
  22002. });
  22003. auto port = svr.bind_to_any_port("127.0.0.1");
  22004. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22005. auto se = detail::scope_exit([&] {
  22006. svr.stop();
  22007. t.join();
  22008. });
  22009. svr.wait_until_ready();
  22010. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22011. "/echo");
  22012. std::string cert;
  22013. read_file(SERVER_CERT_FILE, cert);
  22014. client.load_ca_cert_store(cert.c_str(), cert.size());
  22015. ASSERT_FALSE(client.connect());
  22016. }
  22017. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22018. // SNI, so nothing binds the host name to the TLS session. These bind the
  22019. // server to "localhost" instead, the only shape that exercises the SNI and
  22020. // hostname-verification path with certificate verification left enabled.
  22021. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22022. protected:
  22023. void Start(const char *cert_file) {
  22024. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22025. SERVER_PRIVATE_KEY_FILE);
  22026. ASSERT_TRUE(server_->is_valid());
  22027. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22028. std::string msg;
  22029. while (ws.read(msg)) {
  22030. ws.send(msg);
  22031. }
  22032. });
  22033. port_ = server_->bind_to_any_port("localhost");
  22034. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22035. server_->wait_until_ready();
  22036. }
  22037. void TearDown() override {
  22038. if (server_) { server_->stop(); }
  22039. if (server_thread_.joinable()) { server_thread_.join(); }
  22040. }
  22041. std::string url() const {
  22042. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22043. }
  22044. std::unique_ptr<SSLServer> server_;
  22045. std::thread server_thread_;
  22046. int port_ = 0;
  22047. };
  22048. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22049. // out and the connection is usable
  22050. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22051. Start(SERVER_CERT2_FILE);
  22052. ws::WebSocketClient client(url());
  22053. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22054. ASSERT_TRUE(client.connect());
  22055. ASSERT_TRUE(client.send("hello"));
  22056. std::string msg;
  22057. EXPECT_EQ(ws::Text, client.read(msg));
  22058. EXPECT_EQ("hello", msg);
  22059. client.close();
  22060. }
  22061. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22062. // while the identity check must still reject "localhost"
  22063. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22064. Start(SERVER_CERT_FILE);
  22065. ws::WebSocketClient client(url());
  22066. client.set_ca_cert_path(SERVER_CERT_FILE);
  22067. auto res = client.connect();
  22068. ASSERT_FALSE(res);
  22069. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22070. EXPECT_EQ(-1, res.status());
  22071. }
  22072. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22073. // disabled: the chain is still checked, only the identity check is skipped
  22074. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22075. Start(SERVER_CERT_FILE);
  22076. ws::WebSocketClient client(url());
  22077. client.set_ca_cert_path(SERVER_CERT_FILE);
  22078. client.enable_server_hostname_verification(false);
  22079. ASSERT_TRUE(client.connect());
  22080. ASSERT_TRUE(client.send("hello"));
  22081. std::string msg;
  22082. EXPECT_EQ(ws::Text, client.read(msg));
  22083. EXPECT_EQ("hello", msg);
  22084. client.close();
  22085. }
  22086. // A CA that did not sign the server certificate fails the chain, even though
  22087. // the name would match
  22088. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22089. Start(SERVER_CERT2_FILE);
  22090. ws::WebSocketClient client(url());
  22091. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22092. ASSERT_FALSE(client.connect());
  22093. }
  22094. // With verification disabled, neither the chain nor the name is checked
  22095. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22096. Start(SERVER_CERT_FILE);
  22097. ws::WebSocketClient client(url());
  22098. client.enable_server_certificate_verification(false);
  22099. ASSERT_TRUE(client.connect());
  22100. ASSERT_TRUE(client.send("hello"));
  22101. std::string msg;
  22102. EXPECT_EQ(ws::Text, client.read(msg));
  22103. EXPECT_EQ("hello", msg);
  22104. client.close();
  22105. }
  22106. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22107. protected:
  22108. void SetUp() override {
  22109. server_ = httplib::detail::make_unique<SSLServer>(
  22110. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22111. ASSERT_TRUE(server_->is_valid());
  22112. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22113. std::string msg;
  22114. while (ws.read(msg)) {
  22115. ws.send(msg);
  22116. }
  22117. });
  22118. port_ = server_->bind_to_any_port("localhost");
  22119. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22120. server_->wait_until_ready();
  22121. }
  22122. void TearDown() override {
  22123. server_->stop();
  22124. if (server_thread_.joinable()) { server_thread_.join(); }
  22125. }
  22126. std::string url() const {
  22127. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22128. }
  22129. void ConnectWithClientCert(const std::string &client_cert_file,
  22130. const std::string &client_private_key_file,
  22131. const char *private_key_password) {
  22132. std::string cert_pem, key_pem;
  22133. read_file(client_cert_file, cert_pem);
  22134. read_file(client_private_key_file, key_pem);
  22135. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22136. key_pem.c_str(), key_pem.size(),
  22137. private_key_password};
  22138. ws::WebSocketClient client(url(), pem);
  22139. ASSERT_TRUE(client.is_valid());
  22140. client.enable_server_certificate_verification(false);
  22141. ASSERT_TRUE(client.connect());
  22142. ASSERT_TRUE(client.send("hello"));
  22143. std::string msg;
  22144. EXPECT_EQ(ws::Text, client.read(msg));
  22145. EXPECT_EQ("hello", msg);
  22146. client.close();
  22147. }
  22148. std::unique_ptr<SSLServer> server_;
  22149. std::thread server_thread_;
  22150. int port_ = 0;
  22151. };
  22152. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22153. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22154. }
  22155. // Control for the tests above: the fixture's server really does require a
  22156. // client certificate, so it is the PEM the constructor installed that decides
  22157. // the outcome.
  22158. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22159. ws::WebSocketClient client(url());
  22160. ASSERT_TRUE(client.is_valid());
  22161. client.enable_server_certificate_verification(false);
  22162. EXPECT_FALSE(client.connect());
  22163. }
  22164. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22165. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22166. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22167. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22168. }
  22169. #endif
  22170. #if !defined(_WIN32)
  22171. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22172. auto secret_dir = std::string("./symlink_test_secret");
  22173. auto served_dir = std::string("./symlink_test_served");
  22174. auto secret_file = secret_dir + "/secret.txt";
  22175. auto symlink_path = served_dir + "/escape";
  22176. // Setup: create directories and files
  22177. mkdir(secret_dir.c_str(), 0755);
  22178. mkdir(served_dir.c_str(), 0755);
  22179. {
  22180. std::ofstream ofs(secret_file);
  22181. ofs << "SECRET_DATA";
  22182. }
  22183. // Create symlink using absolute path so it resolves correctly
  22184. #ifdef PATH_MAX
  22185. char abs_secret[PATH_MAX];
  22186. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22187. #else
  22188. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22189. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22190. ASSERT_NE(nullptr, abs_secret);
  22191. #endif
  22192. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22193. auto se = detail::scope_exit([&] {
  22194. unlink(symlink_path.c_str());
  22195. unlink(secret_file.c_str());
  22196. rmdir(served_dir.c_str());
  22197. rmdir(secret_dir.c_str());
  22198. });
  22199. Server svr;
  22200. svr.set_mount_point("/", served_dir);
  22201. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22202. auto se2 = detail::scope_exit([&] {
  22203. svr.stop();
  22204. listen_thread.join();
  22205. });
  22206. svr.wait_until_ready();
  22207. Client cli("localhost", PORT);
  22208. // Symlink pointing outside base dir should be blocked
  22209. auto res = cli.Get("/escape/secret.txt");
  22210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22211. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22212. }
  22213. #endif
  22214. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22215. // "GET /smuggled" request), reads the first response, and only then sends the
  22216. // embedded request as the body. Returns how many times /smuggled ran.
  22217. //
  22218. // The body is sent AFTER receiving the first response (as in the original
  22219. // PoC) so that the stream_line_reader cannot buffer it together with the
  22220. // headers of the first request.
  22221. static int count_smuggled_requests(const std::string &outer_head,
  22222. std::string &first_response) {
  22223. Server svr;
  22224. svr.set_mount_point("/", "./www");
  22225. std::atomic<int> smuggled_count(0);
  22226. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22227. smuggled_count++;
  22228. res.set_content("oops", "text/plain");
  22229. });
  22230. svr.Post("/post", [&](const Request &req, Response &res) {
  22231. res.set_content(req.body, "text/plain");
  22232. });
  22233. auto port = svr.bind_to_any_port("localhost");
  22234. thread t = thread([&] { svr.listen_after_bind(); });
  22235. auto se = detail::scope_exit([&] {
  22236. svr.stop();
  22237. t.join();
  22238. });
  22239. svr.wait_until_ready();
  22240. auto error = Error::Success;
  22241. auto sock = detail::create_client_socket(
  22242. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22243. /*connection_timeout_sec=*/2, 0,
  22244. /*read_timeout_sec=*/2, 0,
  22245. /*write_timeout_sec=*/2, 0, std::string(), error);
  22246. EXPECT_NE(INVALID_SOCKET, sock);
  22247. if (sock == INVALID_SOCKET) { return -1; }
  22248. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22249. // The "smuggled" request will be sent as the body of the outer request
  22250. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22251. "Host: localhost\r\n"
  22252. "Connection: close\r\n"
  22253. "\r\n";
  22254. auto head = outer_head;
  22255. auto len = std::to_string(smuggled.size());
  22256. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22257. pos = head.find("{len}", pos + len.size())) {
  22258. head.replace(pos, 5, len);
  22259. }
  22260. // Step 1: Send only the outer request headers (no body yet)
  22261. auto sent = send(sock, head.data(), head.size(), 0);
  22262. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22263. // Step 2: Read the first response
  22264. char buf[4096];
  22265. for (;;) {
  22266. auto n = recv(sock, buf, sizeof(buf), 0);
  22267. if (n <= 0) break;
  22268. first_response.append(buf, static_cast<size_t>(n));
  22269. // Stop once we have a complete response (headers + body)
  22270. auto hdr_end = first_response.find("\r\n\r\n");
  22271. if (hdr_end != std::string::npos) {
  22272. // Check for Content-Length to know when the body is complete
  22273. auto cl_pos = first_response.find("Content-Length:");
  22274. if (cl_pos != std::string::npos) {
  22275. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22276. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22277. auto cl = std::stoul(
  22278. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22279. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22280. } else {
  22281. break; // No Content-Length, assume headers-only response
  22282. }
  22283. }
  22284. }
  22285. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22286. // vulnerable server the keep-alive loop reads this as a second request. The
  22287. // server may already have closed the connection, so the result is ignored.
  22288. send(sock, smuggled.data(), smuggled.size(), 0);
  22289. // Half-close so that a server which drained the body sees EOF and closes,
  22290. // instead of the read below waiting for the read timeout.
  22291. #ifdef _WIN32
  22292. ::shutdown(sock, SD_SEND);
  22293. #else
  22294. ::shutdown(sock, SHUT_WR);
  22295. #endif
  22296. // Step 4: Read until the server closes the connection
  22297. for (;;) {
  22298. auto n = recv(sock, buf, sizeof(buf), 0);
  22299. if (n <= 0) break;
  22300. }
  22301. return smuggled_count.load();
  22302. }
  22303. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22304. // A GET request with Content-Length to a static file handler must have its
  22305. // body drained before the keep-alive connection is reused. Otherwise the
  22306. // unread body bytes are interpreted as the next HTTP request.
  22307. std::string first_response;
  22308. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22309. "Host: localhost\r\n"
  22310. "Content-Length: {len}\r\n"
  22311. "\r\n",
  22312. first_response));
  22313. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22314. }
  22315. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22316. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22317. // be answered with 400 and the connection closed. Treating it as "no body"
  22318. // leaves the body to be parsed as the next request.
  22319. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22320. const char *targets[] = {
  22321. "GET /file", // handler that never reads the body
  22322. "GET /not-found", // no handler matches (404)
  22323. "POST /post", // handler that reads the body
  22324. };
  22325. for (auto target : targets) {
  22326. for (auto value : values) {
  22327. std::string first_response;
  22328. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22329. " HTTP/1.1\r\n"
  22330. "Host: localhost\r\n"
  22331. "Content-Length: " +
  22332. value + "\r\n\r\n",
  22333. first_response))
  22334. << target << " with Content-Length: " << value;
  22335. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22336. << target << " with Content-Length: " << value;
  22337. }
  22338. }
  22339. }
  22340. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22341. // A 400 for an unparseable request line leaves the rest of the message
  22342. // unread, so the connection must be closed rather than reused.
  22343. std::string first_response;
  22344. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22345. "Host: localhost\r\n"
  22346. "Content-Length: {len}\r\n"
  22347. "\r\n",
  22348. first_response));
  22349. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22350. }
  22351. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22352. // Same as above for a header block that fails to parse.
  22353. std::string first_response;
  22354. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22355. "Host: localhost\r\n"
  22356. "Bad Header\r\n"
  22357. "Content-Length: {len}\r\n"
  22358. "\r\n",
  22359. first_response));
  22360. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22361. }
  22362. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22363. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22364. // server must not read another request on that connection, even when the
  22365. // request had no body to drain.
  22366. std::string first_response;
  22367. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22368. "Host: localhost\r\n"
  22369. "\r\n",
  22370. first_response));
  22371. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22372. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22373. }
  22374. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22375. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22376. // must be rejected with 400 Bad Request.
  22377. Server svr;
  22378. svr.Post("/test", [&](const Request &, Response &res) {
  22379. res.set_content("ok", "text/plain");
  22380. });
  22381. thread t = thread([&] { svr.listen(HOST, PORT); });
  22382. auto se = detail::scope_exit([&] {
  22383. svr.stop();
  22384. t.join();
  22385. ASSERT_FALSE(svr.is_running());
  22386. });
  22387. svr.wait_until_ready();
  22388. // Exact "chunked"
  22389. {
  22390. auto req = "POST /test HTTP/1.1\r\n"
  22391. "Host: localhost\r\n"
  22392. "Content-Length: 5\r\n"
  22393. "Transfer-Encoding: chunked\r\n"
  22394. "Connection: close\r\n"
  22395. "\r\n"
  22396. "hello";
  22397. std::string response;
  22398. ASSERT_TRUE(send_request(1, req, &response));
  22399. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22400. response.substr(0, response.find("\r\n")));
  22401. }
  22402. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22403. {
  22404. auto req = "POST /test HTTP/1.1\r\n"
  22405. "Host: localhost\r\n"
  22406. "Content-Length: 5\r\n"
  22407. "Transfer-Encoding: gzip, chunked\r\n"
  22408. "Connection: close\r\n"
  22409. "\r\n"
  22410. "hello";
  22411. std::string response;
  22412. ASSERT_TRUE(send_request(1, req, &response));
  22413. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22414. response.substr(0, response.find("\r\n")));
  22415. }
  22416. }
  22417. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22418. Server svr;
  22419. svr.Post("/test", [&](const Request &, Response &res) {
  22420. res.set_content("ok", "text/plain");
  22421. });
  22422. thread t = thread([&] { svr.listen(HOST, PORT); });
  22423. auto se = detail::scope_exit([&] {
  22424. svr.stop();
  22425. t.join();
  22426. ASSERT_FALSE(svr.is_running());
  22427. });
  22428. svr.wait_until_ready();
  22429. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22430. // length cannot be determined, so the server must answer 400 and close
  22431. // rather than treat the request as bodyless and leave the body in the
  22432. // socket for the next request to pick up.
  22433. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22434. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22435. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22436. std::string response;
  22437. ASSERT_TRUE(send_request(1, req, &response));
  22438. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22439. response.substr(0, response.find("\r\n")))
  22440. << transfer_encoding;
  22441. }
  22442. // RFC 9110 5.3: the codings may also be split across several
  22443. // Transfer-Encoding lines, which combine in the order they were received.
  22444. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22445. // just like the single-line "chunked, gzip" above.
  22446. {
  22447. auto req = "POST /test HTTP/1.1\r\n"
  22448. "Host: localhost\r\n"
  22449. "Transfer-Encoding: chunked\r\n"
  22450. "Transfer-Encoding: gzip\r\n"
  22451. "\r\n"
  22452. "0\r\n\r\n";
  22453. std::string response;
  22454. ASSERT_TRUE(send_request(1, req, &response));
  22455. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22456. response.substr(0, response.find("\r\n")));
  22457. }
  22458. // A sequence ending in chunked stays valid.
  22459. auto req = "POST /test HTTP/1.1\r\n"
  22460. "Host: localhost\r\n"
  22461. "Transfer-Encoding: gzip, chunked\r\n"
  22462. "Connection: close\r\n"
  22463. "\r\n"
  22464. "0\r\n\r\n";
  22465. std::string response;
  22466. ASSERT_TRUE(send_request(1, req, &response));
  22467. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22468. // ...including when it is spread over several lines.
  22469. auto split_req = "POST /test HTTP/1.1\r\n"
  22470. "Host: localhost\r\n"
  22471. "Transfer-Encoding: gzip\r\n"
  22472. "Transfer-Encoding: chunked\r\n"
  22473. "Connection: close\r\n"
  22474. "\r\n"
  22475. "0\r\n\r\n";
  22476. std::string split_response;
  22477. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22478. EXPECT_EQ("HTTP/1.1 200 OK",
  22479. split_response.substr(0, split_response.find("\r\n")));
  22480. }
  22481. // Regression for issue #2450: a DELETE without Content-Length on a
  22482. // keep-alive connection must not let the post-response drain consume the
  22483. // next request's bytes.
  22484. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22485. Server svr;
  22486. std::atomic<int> delete_count(0);
  22487. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22488. delete_count++;
  22489. res.status = StatusCode::NoContent_204;
  22490. });
  22491. auto port = svr.bind_to_any_port(HOST);
  22492. thread t = thread([&] { svr.listen_after_bind(); });
  22493. auto se = detail::scope_exit([&] {
  22494. svr.stop();
  22495. t.join();
  22496. });
  22497. svr.wait_until_ready();
  22498. auto error = Error::Success;
  22499. auto sock = detail::create_client_socket(
  22500. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22501. /*connection_timeout_sec=*/2, 0,
  22502. /*read_timeout_sec=*/2, 0,
  22503. /*write_timeout_sec=*/2, 0, std::string(), error);
  22504. ASSERT_NE(INVALID_SOCKET, sock);
  22505. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22506. auto send_request_and_read_response = [&](const std::string &req,
  22507. std::string &out) -> bool {
  22508. auto sent = send(sock, req.data(), req.size(), 0);
  22509. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22510. char buf[4096];
  22511. for (;;) {
  22512. auto n = recv(sock, buf, sizeof(buf), 0);
  22513. if (n <= 0) { return !out.empty(); }
  22514. out.append(buf, static_cast<size_t>(n));
  22515. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22516. }
  22517. };
  22518. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22519. "Host: localhost\r\n"
  22520. "\r\n";
  22521. std::string resp1;
  22522. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22523. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22524. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22525. "Host: localhost\r\n"
  22526. "Connection: close\r\n"
  22527. "\r\n";
  22528. std::string resp2;
  22529. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22530. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22531. EXPECT_EQ(2, delete_count.load());
  22532. }
  22533. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22534. Server svr;
  22535. svr.Post("/ingest", [&](const Request &, Response &res,
  22536. const ContentReader &content_reader) {
  22537. auto consumed = content_reader([](const char *, size_t) { return false; });
  22538. EXPECT_FALSE(consumed);
  22539. res.status = StatusCode::Conflict_409;
  22540. res.set_header("Connection", "close");
  22541. });
  22542. auto port = svr.bind_to_any_port(HOST);
  22543. thread t = thread([&] { svr.listen_after_bind(); });
  22544. auto se = detail::scope_exit([&] {
  22545. svr.stop();
  22546. t.join();
  22547. });
  22548. svr.wait_until_ready();
  22549. auto error = Error::Success;
  22550. auto sock = detail::create_client_socket(
  22551. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22552. /*connection_timeout_sec=*/2, 0,
  22553. /*read_timeout_sec=*/1, 0,
  22554. /*write_timeout_sec=*/2, 0, std::string(), error);
  22555. ASSERT_NE(INVALID_SOCKET, sock);
  22556. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22557. std::string request = "POST /ingest HTTP/1.1\r\n"
  22558. "Host: localhost\r\n"
  22559. "Transfer-Encoding: chunked\r\n"
  22560. "\r\n"
  22561. "4\r\n"
  22562. "data\r\n";
  22563. auto sent = send(sock, request.data(), request.size(), 0);
  22564. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22565. std::string response;
  22566. ssize_t received = 0;
  22567. do {
  22568. char buf[4096];
  22569. received = recv(sock, buf, sizeof(buf), 0);
  22570. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22571. } while (received > 0);
  22572. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22573. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22574. EXPECT_EQ(0, received);
  22575. }
  22576. namespace no_proxy_test {
  22577. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22578. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22579. // calling listen().
  22580. class ScopedServer {
  22581. public:
  22582. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22583. ~ScopedServer() {
  22584. svr_.stop();
  22585. if (th_.joinable()) { th_.join(); }
  22586. }
  22587. Server &svr() { return svr_; }
  22588. int port() const { return port_; }
  22589. void listen() {
  22590. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22591. svr_.wait_until_ready();
  22592. }
  22593. private:
  22594. Server svr_;
  22595. std::thread th_;
  22596. int port_ = 0;
  22597. };
  22598. class ProxyAndTargetServers {
  22599. public:
  22600. ProxyAndTargetServers() {
  22601. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22602. proxy_hits_++;
  22603. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22604. res.set_content("via-proxy", "text/plain");
  22605. });
  22606. target_.Get(".*", [this](const Request &req, Response &res) {
  22607. target_hits_++;
  22608. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22609. res.set_content("direct", "text/plain");
  22610. });
  22611. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22612. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22613. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22614. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22615. proxy_mock_.wait_until_ready();
  22616. target_.wait_until_ready();
  22617. }
  22618. ~ProxyAndTargetServers() {
  22619. proxy_mock_.stop();
  22620. target_.stop();
  22621. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22622. if (target_thread_.joinable()) { target_thread_.join(); }
  22623. }
  22624. Server &proxy_mock() { return proxy_mock_; }
  22625. Server &target() { return target_; }
  22626. int proxy_port() const { return proxy_port_; }
  22627. int target_port() const { return target_port_; }
  22628. int proxy_hits() const { return proxy_hits_.load(); }
  22629. int target_hits() const { return target_hits_.load(); }
  22630. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22631. void reset_counters() {
  22632. proxy_hits_ = 0;
  22633. target_hits_ = 0;
  22634. last_had_proxy_authz_ = false;
  22635. }
  22636. private:
  22637. Server proxy_mock_;
  22638. Server target_;
  22639. std::thread proxy_thread_;
  22640. std::thread target_thread_;
  22641. int proxy_port_ = 0;
  22642. int target_port_ = 0;
  22643. std::atomic<int> proxy_hits_{0};
  22644. std::atomic<int> target_hits_{0};
  22645. std::atomic<bool> last_had_proxy_authz_{false};
  22646. };
  22647. inline std::unique_ptr<Client> make_client(const std::string &host,
  22648. ProxyAndTargetServers &s) {
  22649. auto cli = detail::make_unique<Client>(host, s.target_port());
  22650. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22651. cli->set_proxy("127.0.0.1", s.proxy_port());
  22652. return cli;
  22653. }
  22654. } // namespace no_proxy_test
  22655. using no_proxy_test::make_client;
  22656. using no_proxy_test::ProxyAndTargetServers;
  22657. TEST(NoProxyTest, ExactHostnameBypasses) {
  22658. ProxyAndTargetServers s;
  22659. auto cli = make_client("example.com", s);
  22660. cli->set_no_proxy({"example.com"});
  22661. auto res = cli->Get("/");
  22662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22663. EXPECT_EQ(0, s.proxy_hits());
  22664. EXPECT_EQ(1, s.target_hits());
  22665. }
  22666. TEST(NoProxyTest, SubdomainBypasses) {
  22667. ProxyAndTargetServers s;
  22668. auto cli = make_client("foo.example.com", s);
  22669. cli->set_no_proxy({"example.com"});
  22670. auto res = cli->Get("/");
  22671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22672. EXPECT_EQ(0, s.proxy_hits());
  22673. EXPECT_EQ(1, s.target_hits());
  22674. }
  22675. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22676. // Regression guard: "evilexample.com" must not be considered a subdomain
  22677. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22678. // check would let traffic bypass the proxy and leak credentials direct
  22679. // to the attacker host.
  22680. ProxyAndTargetServers s;
  22681. auto cli = make_client("evilexample.com", s);
  22682. cli->set_no_proxy({"example.com"});
  22683. auto res = cli->Get("/");
  22684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22685. EXPECT_GE(s.proxy_hits(), 1);
  22686. EXPECT_EQ(0, s.target_hits());
  22687. }
  22688. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22689. ProxyAndTargetServers s;
  22690. auto cli = make_client("example.com.evil.com", s);
  22691. cli->set_no_proxy({"example.com"});
  22692. auto res = cli->Get("/");
  22693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22694. EXPECT_GE(s.proxy_hits(), 1);
  22695. EXPECT_EQ(0, s.target_hits());
  22696. }
  22697. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22698. ProxyAndTargetServers s;
  22699. auto cli = make_client("example.com", s);
  22700. cli->set_no_proxy({".example.com"});
  22701. auto res = cli->Get("/");
  22702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22703. EXPECT_EQ(0, s.proxy_hits());
  22704. EXPECT_EQ(1, s.target_hits());
  22705. }
  22706. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22707. ProxyAndTargetServers s;
  22708. auto cli = make_client("Example.COM", s);
  22709. cli->set_no_proxy({"EXAMPLE.com"});
  22710. auto res = cli->Get("/");
  22711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22712. EXPECT_EQ(0, s.proxy_hits());
  22713. EXPECT_EQ(1, s.target_hits());
  22714. }
  22715. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22716. ProxyAndTargetServers s;
  22717. auto cli = make_client("example.com.", s);
  22718. cli->set_no_proxy({"example.com"});
  22719. auto res = cli->Get("/");
  22720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22721. EXPECT_EQ(0, s.proxy_hits());
  22722. EXPECT_EQ(1, s.target_hits());
  22723. }
  22724. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22725. // Trailing dots must be normalized on BOTH sides — host and entry.
  22726. // An implementation that only strips the host-side trailing dot would
  22727. // fail to match host "example.com" against entry "example.com." because
  22728. // a literal substring search would compare 11 chars against 12.
  22729. ProxyAndTargetServers s;
  22730. auto cli = make_client("example.com", s);
  22731. cli->set_no_proxy({"example.com."});
  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, WildcardBypassesEverything) {
  22738. ProxyAndTargetServers s;
  22739. auto cli = make_client("anything.invalid.test", s);
  22740. cli->set_no_proxy({"*"});
  22741. auto res = cli->Get("/");
  22742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22743. EXPECT_EQ(0, s.proxy_hits());
  22744. EXPECT_EQ(1, s.target_hits());
  22745. }
  22746. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22747. ProxyAndTargetServers s;
  22748. Client cli("127.0.0.1", s.target_port());
  22749. cli.set_proxy("127.0.0.1", s.proxy_port());
  22750. cli.set_no_proxy({"127.0.0.1"});
  22751. auto res = cli.Get("/");
  22752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22753. EXPECT_EQ(0, s.proxy_hits());
  22754. EXPECT_EQ(1, s.target_hits());
  22755. }
  22756. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22757. ProxyAndTargetServers s;
  22758. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22759. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22760. cli.set_proxy("127.0.0.1", s.proxy_port());
  22761. cli.set_no_proxy({"::1"});
  22762. auto res = cli.Get("/");
  22763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22764. EXPECT_EQ(0, s.proxy_hits());
  22765. EXPECT_EQ(1, s.target_hits());
  22766. }
  22767. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22768. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22769. // must still be recognized as IPv6 for CIDR matching. Implementations
  22770. // that detect IPv6 only when the host begins with '[' would parse the
  22771. // host as a hostname and miss the match.
  22772. ProxyAndTargetServers s;
  22773. Client cli("fe80::1", s.target_port());
  22774. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22775. cli.set_proxy("127.0.0.1", s.proxy_port());
  22776. cli.set_no_proxy({"fe80::/10"});
  22777. auto res = cli.Get("/");
  22778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22779. EXPECT_EQ(0, s.proxy_hits());
  22780. EXPECT_EQ(1, s.target_hits());
  22781. }
  22782. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22783. ProxyAndTargetServers s;
  22784. Client cli("::1", s.target_port());
  22785. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22786. cli.set_proxy("127.0.0.1", s.proxy_port());
  22787. cli.set_no_proxy({"[::1]"});
  22788. auto res = cli.Get("/");
  22789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22790. EXPECT_EQ(0, s.proxy_hits());
  22791. EXPECT_EQ(1, s.target_hits());
  22792. }
  22793. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22794. ProxyAndTargetServers s;
  22795. Client cli("fe80::1", s.target_port());
  22796. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22797. cli.set_proxy("127.0.0.1", s.proxy_port());
  22798. cli.set_no_proxy({"[fe80::]/10"});
  22799. auto res = cli.Get("/");
  22800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22801. EXPECT_EQ(0, s.proxy_hits());
  22802. EXPECT_EQ(1, s.target_hits());
  22803. }
  22804. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22805. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22806. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22807. // tricks via address-family conversion.
  22808. ProxyAndTargetServers s;
  22809. Client cli("::ffff:127.0.0.1", s.target_port());
  22810. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22811. cli.set_proxy("127.0.0.1", s.proxy_port());
  22812. cli.set_no_proxy({"127.0.0.1"});
  22813. auto res = cli.Get("/");
  22814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22815. EXPECT_GE(s.proxy_hits(), 1);
  22816. EXPECT_EQ(0, s.target_hits());
  22817. }
  22818. TEST(NoProxyTest, IPv4CidrMatch) {
  22819. ProxyAndTargetServers s;
  22820. Client cli("127.0.0.1", s.target_port());
  22821. cli.set_proxy("127.0.0.1", s.proxy_port());
  22822. cli.set_no_proxy({"127.0.0.0/8"});
  22823. auto res = cli.Get("/");
  22824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22825. EXPECT_EQ(0, s.proxy_hits());
  22826. EXPECT_EQ(1, s.target_hits());
  22827. }
  22828. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22829. ProxyAndTargetServers s;
  22830. Client cli("127.0.0.1", s.target_port());
  22831. cli.set_proxy("127.0.0.1", s.proxy_port());
  22832. cli.set_no_proxy({"10.0.0.0/8"});
  22833. auto res = cli.Get("/");
  22834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22835. EXPECT_GE(s.proxy_hits(), 1);
  22836. EXPECT_EQ(0, s.target_hits());
  22837. }
  22838. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22839. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22840. // IPv4 target matches.
  22841. ProxyAndTargetServers s;
  22842. Client cli("127.0.0.1", s.target_port());
  22843. cli.set_proxy("127.0.0.1", s.proxy_port());
  22844. cli.set_no_proxy({"0.0.0.0/0"});
  22845. auto res = cli.Get("/");
  22846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22847. EXPECT_EQ(0, s.proxy_hits());
  22848. EXPECT_EQ(1, s.target_hits());
  22849. }
  22850. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22851. ProxyAndTargetServers s;
  22852. Client cli("127.0.0.1", s.target_port());
  22853. cli.set_proxy("127.0.0.1", s.proxy_port());
  22854. cli.set_no_proxy({"127.0.0.1"});
  22855. auto res = cli.Get("/");
  22856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22857. EXPECT_EQ(0, s.proxy_hits());
  22858. EXPECT_EQ(1, s.target_hits());
  22859. }
  22860. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22861. ProxyAndTargetServers s;
  22862. Client cli("127.0.0.1", s.target_port());
  22863. cli.set_proxy("127.0.0.1", s.proxy_port());
  22864. cli.set_no_proxy({"127.0.0.0/33"});
  22865. auto res = cli.Get("/");
  22866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22867. EXPECT_GE(s.proxy_hits(), 1);
  22868. EXPECT_EQ(0, s.target_hits());
  22869. }
  22870. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22871. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22872. ProxyAndTargetServers s;
  22873. Client cli("127.0.0.1", s.target_port());
  22874. cli.set_proxy("127.0.0.1", s.proxy_port());
  22875. cli.set_no_proxy({"127.0.0.1/"});
  22876. auto res = cli.Get("/");
  22877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22878. EXPECT_GE(s.proxy_hits(), 1);
  22879. EXPECT_EQ(0, s.target_hits());
  22880. }
  22881. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22882. ProxyAndTargetServers s;
  22883. auto cli = make_client("internal.corp", s);
  22884. cli->set_proxy_basic_auth("u", "p");
  22885. cli->set_no_proxy({"internal.corp"});
  22886. auto res = cli->Get("/");
  22887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22888. EXPECT_EQ(1, s.target_hits());
  22889. EXPECT_EQ(0, s.proxy_hits());
  22890. EXPECT_FALSE(s.last_had_proxy_authz())
  22891. << "Proxy-Authorization must not be sent direct to the target";
  22892. }
  22893. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22894. ProxyAndTargetServers s;
  22895. auto cli = make_client("public.example", s);
  22896. cli->set_proxy_basic_auth("u", "p");
  22897. cli->set_no_proxy({"internal.corp"}); // does not match
  22898. auto res = cli->Get("/");
  22899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22900. EXPECT_GE(s.proxy_hits(), 1);
  22901. EXPECT_TRUE(s.last_had_proxy_authz());
  22902. }
  22903. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22904. std::atomic<int> hits{0};
  22905. std::atomic<int> hits_with_authz{0};
  22906. no_proxy_test::ScopedServer proxy_mock;
  22907. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22908. hits++;
  22909. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  22910. if (req.target.find("/redir") != std::string::npos) {
  22911. res.set_redirect("http://other.example/landed");
  22912. } else {
  22913. res.set_content("via-proxy", "text/plain");
  22914. }
  22915. });
  22916. proxy_mock.listen();
  22917. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  22918. hits = 0;
  22919. hits_with_authz = 0;
  22920. Client cli("public.example", 80);
  22921. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22922. cli.set_proxy_basic_auth(c.first, c.second);
  22923. cli.set_follow_location(true);
  22924. // The redirect to another host goes through the proxy as well
  22925. auto res = cli.Get("/redir");
  22926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22927. EXPECT_EQ(2, hits.load());
  22928. EXPECT_EQ(2, hits_with_authz.load());
  22929. }
  22930. }
  22931. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22932. ProxyAndTargetServers s;
  22933. auto cli = make_client("anything.test", s);
  22934. auto res = cli->Get("/");
  22935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22936. EXPECT_GE(s.proxy_hits(), 1);
  22937. EXPECT_EQ(0, s.target_hits());
  22938. }
  22939. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22940. ProxyAndTargetServers s;
  22941. auto cli = make_client("example.com", s);
  22942. cli->set_no_proxy({"example.com:8080"});
  22943. auto res = cli->Get("/");
  22944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22945. EXPECT_GE(s.proxy_hits(), 1);
  22946. EXPECT_EQ(0, s.target_hits());
  22947. }
  22948. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22949. ProxyAndTargetServers s;
  22950. auto cli = make_client("anything.test", s);
  22951. cli->set_no_proxy({"", " ", "\t"});
  22952. auto res = cli->Get("/");
  22953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22954. EXPECT_GE(s.proxy_hits(), 1);
  22955. EXPECT_EQ(0, s.target_hits());
  22956. }
  22957. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22958. // An entry with leading/trailing whitespace must still match — env-style
  22959. // values are commonly pasted with stray spaces and an implementation
  22960. // that feeds the raw token directly to inet_pton would fail to match
  22961. // valid CIDRs because of the spaces.
  22962. ProxyAndTargetServers s;
  22963. Client cli("127.0.0.1", s.target_port());
  22964. cli.set_proxy("127.0.0.1", s.proxy_port());
  22965. cli.set_no_proxy({" 127.0.0.0/8 "});
  22966. auto res = cli.Get("/");
  22967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22968. EXPECT_EQ(0, s.proxy_hits());
  22969. EXPECT_EQ(1, s.target_hits());
  22970. }
  22971. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22972. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22973. // go direct and must NOT carry Proxy-Authorization.
  22974. std::atomic<int> proxy_hits{0};
  22975. std::atomic<int> target_hits{0};
  22976. std::atomic<bool> target_saw_authz{false};
  22977. no_proxy_test::ScopedServer proxy_mock, target;
  22978. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22979. proxy_hits++;
  22980. res.status = 302;
  22981. res.set_header("Location", "http://127.0.0.1:" +
  22982. std::to_string(target.port()) + "/landed");
  22983. });
  22984. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22985. target_hits++;
  22986. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22987. res.set_content("direct", "text/plain");
  22988. });
  22989. proxy_mock.listen();
  22990. target.listen();
  22991. Client cli("public.example", target.port());
  22992. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22993. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22994. cli.set_proxy_basic_auth("u", "p");
  22995. cli.set_no_proxy({"127.0.0.1"});
  22996. cli.set_follow_location(true);
  22997. auto res = cli.Get("/redir");
  22998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22999. EXPECT_GE(proxy_hits.load(), 1);
  23000. EXPECT_GE(target_hits.load(), 1);
  23001. EXPECT_FALSE(target_saw_authz.load());
  23002. }
  23003. #ifdef CPPHTTPLIB_SSL_ENABLED
  23004. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23005. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23006. // proxy creds would be sent to the (possibly hostile) origin.
  23007. std::atomic<int> target_hits{0};
  23008. std::atomic<bool> target_saw_proxy_authz{false};
  23009. no_proxy_test::ScopedServer target;
  23010. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23011. target_hits++;
  23012. if (req.has_header("Proxy-Authorization")) {
  23013. target_saw_proxy_authz = true;
  23014. }
  23015. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23016. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23017. "nonce=\"abc\", algorithm=MD5");
  23018. });
  23019. target.listen();
  23020. // The proxy address is set to the target's port: the bypass MUST kick in;
  23021. // if it doesn't, the test still routes "via proxy" to the same server and
  23022. // the Proxy-Authorization assertion below catches the leak.
  23023. Client cli("evil.example", target.port());
  23024. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23025. cli.set_proxy("127.0.0.1", target.port());
  23026. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23027. cli.set_no_proxy({"evil.example"});
  23028. auto res = cli.Get("/x");
  23029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23030. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23031. EXPECT_EQ(1, target_hits.load());
  23032. EXPECT_FALSE(target_saw_proxy_authz.load());
  23033. }
  23034. #endif
  23035. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23036. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23037. std::atomic<int> proxy_hits{0};
  23038. std::atomic<int> bypass_hits{0};
  23039. std::atomic<bool> proxy_saw_c_url{false};
  23040. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23041. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23042. proxy_hits++;
  23043. if (req.path.find("/start") != std::string::npos) {
  23044. res.status = 302;
  23045. res.set_header("Location", "http://127.0.0.1:" +
  23046. std::to_string(bypass_server.port()) +
  23047. "/middle");
  23048. return;
  23049. }
  23050. if (req.path.find("/end") != std::string::npos) {
  23051. proxy_saw_c_url = true;
  23052. res.set_content("c-via-proxy", "text/plain");
  23053. return;
  23054. }
  23055. res.set_content("unexpected", "text/plain");
  23056. });
  23057. // public.example's "advertised" port is arbitrary (the request never lands
  23058. // there — it goes through the proxy), but use a dynamic value to stay
  23059. // friendly with sharded parallel runs.
  23060. int public_port = bypass_server.port();
  23061. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23062. bypass_hits++;
  23063. res.status = 302;
  23064. res.set_header("Location", "http://public.example:" +
  23065. std::to_string(public_port) + "/end");
  23066. });
  23067. proxy_mock.listen();
  23068. bypass_server.listen();
  23069. Client cli("public.example", public_port);
  23070. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23071. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23072. cli.set_no_proxy({"127.0.0.1"});
  23073. cli.set_follow_location(true);
  23074. auto res = cli.Get("/start");
  23075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23076. EXPECT_EQ(StatusCode::OK_200, res->status);
  23077. EXPECT_EQ("c-via-proxy", res->body);
  23078. EXPECT_GE(proxy_hits.load(), 2);
  23079. EXPECT_GE(bypass_hits.load(), 1);
  23080. EXPECT_TRUE(proxy_saw_c_url.load());
  23081. }
  23082. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23083. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23084. // request reconnects to the correct endpoint.
  23085. std::atomic<int> proxy_hits{0};
  23086. std::atomic<int> target_hits{0};
  23087. no_proxy_test::ScopedServer proxy_mock, target;
  23088. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23089. proxy_hits++;
  23090. res.set_content("via-proxy", "text/plain");
  23091. });
  23092. target.svr().Get(".*", [&](const Request &, Response &res) {
  23093. target_hits++;
  23094. res.set_content("direct", "text/plain");
  23095. });
  23096. proxy_mock.listen();
  23097. target.listen();
  23098. Client cli("public.example", target.port());
  23099. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23100. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23101. cli.set_keep_alive(true);
  23102. auto res1 = cli.Get("/a");
  23103. ASSERT_TRUE(res1);
  23104. EXPECT_EQ("via-proxy", res1->body);
  23105. EXPECT_EQ(1, proxy_hits.load());
  23106. EXPECT_EQ(0, target_hits.load());
  23107. cli.set_no_proxy({"public.example"});
  23108. auto res2 = cli.Get("/b");
  23109. ASSERT_TRUE(res2);
  23110. EXPECT_EQ("direct", res2->body);
  23111. EXPECT_EQ(1, proxy_hits.load());
  23112. EXPECT_EQ(1, target_hits.load());
  23113. }
  23114. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23115. namespace proxy_tunnel_test {
  23116. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23117. class ScopedSSLServer {
  23118. public:
  23119. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23120. port_ = svr_.bind_to_any_port("127.0.0.1");
  23121. }
  23122. ~ScopedSSLServer() {
  23123. svr_.stop();
  23124. if (th_.joinable()) { th_.join(); }
  23125. }
  23126. SSLServer &svr() { return svr_; }
  23127. int port() const { return port_; }
  23128. void listen() {
  23129. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23130. svr_.wait_until_ready();
  23131. }
  23132. private:
  23133. SSLServer svr_;
  23134. std::thread th_;
  23135. int port_ = 0;
  23136. };
  23137. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23138. class ScopedConnectProxy {
  23139. public:
  23140. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23141. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23142. if (listen_fd_ < 0) { return; }
  23143. int yes = 1;
  23144. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23145. sockaddr_in a{};
  23146. a.sin_family = AF_INET;
  23147. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23148. a.sin_port = 0;
  23149. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23150. return;
  23151. }
  23152. socklen_t alen = sizeof(a);
  23153. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23154. 0) {
  23155. return;
  23156. }
  23157. port_ = ntohs(a.sin_port);
  23158. if (::listen(listen_fd_, 1) != 0) { return; }
  23159. th_ = std::thread([this] { run(); });
  23160. }
  23161. ~ScopedConnectProxy() {
  23162. stop_ = true;
  23163. if (listen_fd_ >= 0) {
  23164. ::shutdown(listen_fd_, SHUT_RDWR);
  23165. ::close(listen_fd_);
  23166. }
  23167. if (th_.joinable()) { th_.join(); }
  23168. }
  23169. int port() const { return port_; }
  23170. int connect_hits() const { return connect_hits_.load(); }
  23171. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23172. std::string connect_request() const {
  23173. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23174. return connect_request_;
  23175. }
  23176. private:
  23177. void run() {
  23178. while (!stop_.load()) {
  23179. fd_set rfds;
  23180. FD_ZERO(&rfds);
  23181. FD_SET(listen_fd_, &rfds);
  23182. timeval tv{0, 100 * 1000};
  23183. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23184. if (sel <= 0) { continue; }
  23185. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23186. if (client_fd < 0) { continue; }
  23187. std::string req;
  23188. char buf[2048];
  23189. while (req.find("\r\n\r\n") == std::string::npos) {
  23190. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23191. if (n <= 0) { break; }
  23192. req.append(buf, static_cast<size_t>(n));
  23193. }
  23194. if (req.compare(0, 7, "CONNECT") != 0) {
  23195. ::close(client_fd);
  23196. continue;
  23197. }
  23198. connect_hits_++;
  23199. {
  23200. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23201. connect_request_ = req;
  23202. }
  23203. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23204. ::send(client_fd, ok, std::strlen(ok), 0);
  23205. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23206. sockaddr_in o{};
  23207. o.sin_family = AF_INET;
  23208. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23209. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23210. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23211. 0) {
  23212. ::close(client_fd);
  23213. ::close(origin_fd);
  23214. continue;
  23215. }
  23216. auto forward = [](int from, int to) {
  23217. char b[8192];
  23218. for (;;) {
  23219. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23220. if (n <= 0) { break; }
  23221. ssize_t off = 0;
  23222. while (off < n) {
  23223. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23224. if (s <= 0) {
  23225. off = n;
  23226. break;
  23227. }
  23228. off += s;
  23229. }
  23230. }
  23231. ::shutdown(to, SHUT_WR);
  23232. };
  23233. std::thread t1([&] { forward(client_fd, origin_fd); });
  23234. std::thread t2([&] { forward(origin_fd, client_fd); });
  23235. t1.join();
  23236. t2.join();
  23237. ::close(client_fd);
  23238. ::close(origin_fd);
  23239. }
  23240. }
  23241. int forward_port_ = -1;
  23242. int listen_fd_ = -1;
  23243. int port_ = 0;
  23244. std::thread th_;
  23245. std::atomic<bool> stop_{false};
  23246. std::atomic<int> connect_hits_{0};
  23247. mutable std::mutex connect_request_mutex_;
  23248. std::string connect_request_;
  23249. };
  23250. // Sends one request through the CONNECT proxy to the TLS origin with a
  23251. // credential configured for each hop, and checks that each credential reaches
  23252. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23253. // origin's (every header in origin_headers) on the tunnelled request.
  23254. void CredentialsStayWithTheirHop(
  23255. const std::function<void(SSLClient &)> &set_credentials,
  23256. const std::string &scheme,
  23257. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23258. std::atomic<int> origin_hits{0};
  23259. std::atomic<bool> origin_saw_proxy_authz{false};
  23260. std::atomic<bool> origin_saw_headers{false};
  23261. ScopedSSLServer origin;
  23262. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23263. origin_hits++;
  23264. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23265. origin_saw_headers =
  23266. std::all_of(origin_headers.begin(), origin_headers.end(),
  23267. [&](const std::string &h) { return req.has_header(h); });
  23268. res.set_content("ok", "text/plain");
  23269. });
  23270. origin.listen();
  23271. ScopedConnectProxy proxy(origin.port());
  23272. ASSERT_NE(0, proxy.port());
  23273. // Pinned to 127.0.0.1 for the same reason as the test below.
  23274. SSLClient cli("127.0.0.1", origin.port());
  23275. cli.enable_server_certificate_verification(false);
  23276. cli.set_proxy("127.0.0.1", proxy.port());
  23277. set_credentials(cli);
  23278. auto res = cli.Get("/x");
  23279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23280. EXPECT_EQ(StatusCode::OK_200, res->status);
  23281. EXPECT_EQ(1, origin_hits.load());
  23282. EXPECT_EQ(1, proxy.connect_hits());
  23283. EXPECT_TRUE(origin_saw_headers.load());
  23284. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23285. << "Proxy-Authorization must not be sent inside the tunnel";
  23286. auto connect_req = proxy.connect_request();
  23287. EXPECT_NE(std::string::npos,
  23288. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23289. for (const auto &h : origin_headers) {
  23290. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23291. << h << " must not be sent to the proxy on CONNECT";
  23292. }
  23293. }
  23294. } // namespace proxy_tunnel_test
  23295. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23296. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23297. [](SSLClient &cli) {
  23298. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23299. cli.set_basic_auth("origin-user", "origin-pass");
  23300. },
  23301. "Basic");
  23302. }
  23303. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23304. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23305. [](SSLClient &cli) {
  23306. cli.set_proxy_bearer_token_auth("proxy-token");
  23307. cli.set_bearer_token_auth("origin-token");
  23308. },
  23309. "Bearer");
  23310. }
  23311. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23312. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23313. [](SSLClient &cli) {
  23314. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23315. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23316. {"Cookie", "sid=origin-session"},
  23317. {"X-Api-Key", "origin-key"}});
  23318. },
  23319. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23320. }
  23321. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23322. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23323. // retry; otherwise proxy creds would be sent to the origin.
  23324. std::atomic<int> origin_hits{0};
  23325. std::atomic<bool> origin_saw_proxy_authz{false};
  23326. proxy_tunnel_test::ScopedSSLServer origin;
  23327. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23328. origin_hits++;
  23329. if (req.has_header("Proxy-Authorization")) {
  23330. origin_saw_proxy_authz = true;
  23331. }
  23332. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23333. res.set_header("Proxy-Authenticate",
  23334. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23335. "algorithm=MD5");
  23336. });
  23337. origin.listen();
  23338. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23339. ASSERT_NE(0, proxy.port());
  23340. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23341. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23342. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23343. // and answer with its own status, making this test flaky.
  23344. SSLClient cli("127.0.0.1", origin.port());
  23345. cli.enable_server_certificate_verification(false);
  23346. cli.set_proxy("127.0.0.1", proxy.port());
  23347. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23348. auto res = cli.Get("/x");
  23349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23350. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23351. EXPECT_EQ(1, origin_hits.load());
  23352. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23353. EXPECT_EQ(1, proxy.connect_hits());
  23354. }
  23355. #endif