test.cc 901 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declaration: in split builds split.py strips `inline` and moves the
  474. // definition into httplib.cc, so detail::base64_encode is not visible from the
  475. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  476. // in both header-only and split builds.
  477. namespace httplib {
  478. namespace detail {
  479. std::string base64_encode(const std::string &in);
  480. } // namespace detail
  481. } // namespace httplib
  482. TEST(Base64EncodeTest, KnownAnswers) {
  483. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  484. // where the accumulator's top bit is already set before the next shift.
  485. EXPECT_EQ("", detail::base64_encode(""));
  486. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  487. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  488. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  489. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  490. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  491. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  492. // High bytes keep the top bit set across several rounds.
  493. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  494. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  495. }
  496. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  497. string unescapedCharacters = "-_.!~*'()";
  498. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  499. }
  500. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  501. string reservedCharacters = ";,/?:@&=+$";
  502. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  503. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  504. }
  505. TEST(ClientQueryOrder, PreserveOrder) {
  506. // This test reproduces Issue #2259: client may reorder query parameters
  507. // when sending a GET request. The expected behavior is that the client
  508. // preserves the original query string order when the caller supplied it
  509. // as part of the path.
  510. Server svr;
  511. svr.Get("/", [&](const Request &req, Response &res) {
  512. // Echo back the raw target so the test can assert ordering
  513. res.set_content(req.target, "text/plain");
  514. });
  515. std::thread t{[&] { svr.listen(HOST, PORT); }};
  516. auto se = detail::scope_exit([&] {
  517. svr.stop();
  518. t.join();
  519. ASSERT_FALSE(svr.is_running());
  520. });
  521. svr.wait_until_ready();
  522. Client cli(HOST, PORT);
  523. ASSERT_TRUE(cli.is_valid());
  524. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  525. auto res = cli.Get(original);
  526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  527. // Expect the echoed target to exactly match the original path (order
  528. // preserved)
  529. EXPECT_EQ(res->body, original);
  530. }
  531. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  532. string chineseCharacters = U8("中国語");
  533. string russianCharacters = U8("дом");
  534. string brazilianCharacters = U8("óculos");
  535. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  536. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  537. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  538. "%D0%B4%D0%BE%D0%BC");
  539. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  540. }
  541. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  546. string reservedCharacters = ";,/?:@&=+$";
  547. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  548. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  549. }
  550. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  551. string chineseCharacters = U8("中国語");
  552. string russianCharacters = U8("дом");
  553. string brazilianCharacters = U8("óculos");
  554. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  555. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  556. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  557. "%D0%B4%D0%BE%D0%BC");
  558. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  559. }
  560. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  561. // Issue #2082 use case: encoding path component with ampersand
  562. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  563. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  564. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  565. }
  566. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  567. string unescapedCharacters = "-_.!~*'()";
  568. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  569. }
  570. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  571. string reservedCharacters = ";,/?:@&=+$#";
  572. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  573. }
  574. TEST(EncodeUriTest, TestUTF8Characters) {
  575. string chineseCharacters = U8("中国語");
  576. string russianCharacters = U8("дом");
  577. string brazilianCharacters = U8("óculos");
  578. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  579. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  580. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  581. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  582. }
  583. TEST(EncodeUriTest, TestCompleteUri) {
  584. string uri =
  585. "https://example.com/path/to/resource?query=value&param=test#fragment";
  586. EXPECT_EQ(
  587. httplib::encode_uri(uri),
  588. "https://example.com/path/to/resource?query=value&param=test#fragment");
  589. }
  590. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  591. string uri =
  592. "https://example.com/path with spaces/file name.html?q=hello world";
  593. EXPECT_EQ(httplib::encode_uri(uri),
  594. "https://example.com/path%20with%20spaces/"
  595. "file%20name.html?q=hello%20world");
  596. }
  597. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  598. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  599. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  600. }
  601. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  602. string unescapedCharacters = "-_.!~*'()";
  603. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  604. }
  605. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  606. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  607. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  608. string encodedBrazilian = "%C3%B3culos";
  609. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  612. }
  613. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  614. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  615. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  616. "Piri Tommy Villiers - on & on");
  617. }
  618. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  619. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  620. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  621. }
  622. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  623. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  624. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  625. }
  626. TEST(DecodeUriTest, TestUTF8Characters) {
  627. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  628. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  629. string encodedBrazilian = "%C3%B3culos";
  630. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  631. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  632. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  633. }
  634. TEST(DecodeUriTest, TestCompleteUri) {
  635. string encodedUri = "https://example.com/path%20with%20spaces/"
  636. "file%20name.html?q=hello%20world";
  637. EXPECT_EQ(
  638. httplib::decode_uri(encodedUri),
  639. "https://example.com/path with spaces/file name.html?q=hello world");
  640. }
  641. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  642. string original =
  643. "https://example.com/path with spaces/file name.html?q=hello world";
  644. string encoded = httplib::encode_uri(original);
  645. string decoded = httplib::decode_uri(encoded);
  646. EXPECT_EQ(decoded, original);
  647. }
  648. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  649. // decode_uri is the inverse of encode_uri: an escaped reserved character
  650. // stays encoded so it is not promoted into a real delimiter, while
  651. // non-reserved escapes still decode (like JS decodeURI).
  652. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  653. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  654. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  655. "%3F%3A%40%26%3D%2B%24%2C%3B");
  656. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  657. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  658. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  659. "http://example.com/a%2Fb");
  660. // decode_uri_component still decodes the reserved character.
  661. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  662. }
  663. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  664. string original = "Piri Tommy Villiers - on & on";
  665. string encoded = httplib::encode_uri_component(original);
  666. string decoded = httplib::decode_uri_component(encoded);
  667. EXPECT_EQ(decoded, original);
  668. }
  669. TEST(TrimTests, TrimStringTests) {
  670. EXPECT_EQ("abc", detail::trim_copy("abc"));
  671. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  672. EXPECT_TRUE(detail::trim_copy("").empty());
  673. }
  674. TEST(AsciiTest, LocaleIndependentClassification) {
  675. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  676. // which consult the global C locale: std::isalnum(0xC5) can return true
  677. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  678. // helpers must classify every byte by the ASCII grammar alone.
  679. for (int i = 0; i < 256; i++) {
  680. auto c = static_cast<char>(i);
  681. auto is_digit = i >= '0' && i <= '9';
  682. auto is_upper = i >= 'A' && i <= 'Z';
  683. auto is_lower = i >= 'a' && i <= 'z';
  684. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  685. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  686. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  687. << "byte " << i;
  688. }
  689. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  690. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  691. // Non-ASCII bytes must be percent-encoded, never passed through as
  692. // alphanumeric.
  693. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  694. }
  695. TEST(FromCharsTest, Double) {
  696. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  697. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  698. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  699. auto parse = [](const std::string &s, double &v) {
  700. return detail::from_chars(s.data(), s.data() + s.size(), v);
  701. };
  702. double v = -1.0;
  703. // Representative quality values.
  704. EXPECT_EQ(parse("0", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 0.0);
  706. EXPECT_EQ(parse("1", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 1.0);
  708. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.8);
  710. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 0.001);
  712. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  713. EXPECT_DOUBLE_EQ(v, 1.0);
  714. // A missing integer or fractional part is tolerated.
  715. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 0.5);
  717. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  718. EXPECT_DOUBLE_EQ(v, 5.0);
  719. // Values outside [0, 1] still parse; the caller range-checks them.
  720. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  721. EXPECT_DOUBLE_EQ(v, 123.456);
  722. // Stops at the first byte that is not part of the number and reports where.
  723. std::string trailing = "0.9, text/html";
  724. auto r = parse(trailing, v);
  725. EXPECT_EQ(r.ec, std::errc{});
  726. EXPECT_DOUBLE_EQ(v, 0.9);
  727. EXPECT_EQ(*r.ptr, ',');
  728. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  729. // outright, and an 'e'/'E' simply ends the number.
  730. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  731. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  732. std::string exp_input = "1.5e3";
  733. r = parse(exp_input, v);
  734. EXPECT_EQ(r.ec, std::errc{});
  735. EXPECT_DOUBLE_EQ(v, 1.5);
  736. EXPECT_EQ(*r.ptr, 'e');
  737. // Invalid inputs.
  738. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  743. // Pathological but well-formed inputs must stay bounded (no overflow, no
  744. // out-of-bounds table access) and stay within [0, 1] for the caller.
  745. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  746. std::errc{});
  747. EXPECT_DOUBLE_EQ(v, 0.0);
  748. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  749. std::errc{});
  750. EXPECT_GE(v, 0.0);
  751. EXPECT_LE(v, 1.0);
  752. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  753. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  754. }
  755. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  756. // Simple case without quality values
  757. std::vector<std::string> result1;
  758. EXPECT_TRUE(detail::parse_accept_header(
  759. "text/html,application/json,text/plain", result1));
  760. EXPECT_EQ(result1.size(), 3U);
  761. EXPECT_EQ(result1[0], "text/html");
  762. EXPECT_EQ(result1[1], "application/json");
  763. EXPECT_EQ(result1[2], "text/plain");
  764. // With quality values
  765. std::vector<std::string> result2;
  766. EXPECT_TRUE(detail::parse_accept_header(
  767. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  768. EXPECT_EQ(result2.size(), 3U);
  769. EXPECT_EQ(result2[0], "application/json"); // highest q value
  770. EXPECT_EQ(result2[1], "text/html");
  771. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  772. }
  773. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  774. // Mixed with and without quality values
  775. std::vector<std::string> result;
  776. EXPECT_TRUE(detail::parse_accept_header(
  777. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  778. EXPECT_EQ(result.size(), 3U);
  779. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  780. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  781. EXPECT_EQ(result[2], "application/json"); // q=0.5
  782. }
  783. TEST(ParseAcceptHeaderTest, EdgeCases) {
  784. // Empty header
  785. std::vector<std::string> empty_result;
  786. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  787. EXPECT_TRUE(empty_result.empty());
  788. // Single type
  789. std::vector<std::string> single_result;
  790. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  791. EXPECT_EQ(single_result.size(), 1U);
  792. EXPECT_EQ(single_result[0], "application/json");
  793. // Wildcard types
  794. std::vector<std::string> wildcard_result;
  795. EXPECT_TRUE(detail::parse_accept_header(
  796. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  797. EXPECT_EQ(wildcard_result.size(), 3U);
  798. EXPECT_EQ(wildcard_result[0], "application/json");
  799. EXPECT_EQ(wildcard_result[1], "text/*");
  800. EXPECT_EQ(wildcard_result[2], "*/*");
  801. }
  802. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  803. // Common browser Accept header
  804. std::vector<std::string> browser_result;
  805. EXPECT_TRUE(
  806. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  807. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  808. browser_result));
  809. EXPECT_EQ(browser_result.size(), 6U);
  810. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  815. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  816. // API client header
  817. std::vector<std::string> api_result;
  818. EXPECT_TRUE(detail::parse_accept_header(
  819. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  820. api_result));
  821. EXPECT_EQ(api_result.size(), 3U);
  822. EXPECT_EQ(api_result[0], "application/json");
  823. EXPECT_EQ(api_result[1], "application/xml");
  824. EXPECT_EQ(api_result[2], "text/plain");
  825. }
  826. TEST(ParseAcceptHeaderTest, SpecialCases) {
  827. // Quality value with 3 decimal places
  828. std::vector<std::string> decimal_result;
  829. EXPECT_TRUE(detail::parse_accept_header(
  830. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  831. EXPECT_EQ(decimal_result.size(), 2U);
  832. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  833. EXPECT_EQ(decimal_result[1], "text/html");
  834. // Zero quality (should still be included but with lowest priority)
  835. std::vector<std::string> zero_q_result;
  836. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  837. zero_q_result));
  838. EXPECT_EQ(zero_q_result.size(), 2U);
  839. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  840. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  841. // No spaces around commas
  842. std::vector<std::string> no_space_result;
  843. EXPECT_TRUE(detail::parse_accept_header(
  844. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  845. no_space_result));
  846. EXPECT_EQ(no_space_result.size(), 3U);
  847. EXPECT_EQ(no_space_result[0], "text/html");
  848. EXPECT_EQ(no_space_result[1], "application/json");
  849. EXPECT_EQ(no_space_result[2], "text/plain");
  850. }
  851. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  852. // Quality values always use '.' as the decimal separator, so parsing must
  853. // not depend on the process locale. An embedding application may have
  854. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  855. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  856. std::string saved = cur ? cur : "C";
  857. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  858. "fr_FR.UTF-8"};
  859. bool switched = false;
  860. for (const auto loc : comma_locales) {
  861. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  862. std::localeconv()->decimal_point[0] == ',') {
  863. switched = true;
  864. break;
  865. }
  866. }
  867. if (!switched) {
  868. std::setlocale(LC_NUMERIC, saved.c_str());
  869. GTEST_SKIP() << "no comma-decimal locale available on this host";
  870. }
  871. // The higher-weighted type appears later in the list, so a correct parse
  872. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  873. // sensitive parse reads both weights as 0 and leaves the original order.
  874. std::vector<std::string> result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "application/json;q=0.1,text/html;q=0.9", result));
  877. ASSERT_EQ(result.size(), 2U);
  878. EXPECT_EQ(result[0], "text/html");
  879. EXPECT_EQ(result[1], "application/json");
  880. std::setlocale(LC_NUMERIC, saved.c_str());
  881. }
  882. TEST(ParseAcceptHeaderTest, InvalidCases) {
  883. std::vector<std::string> result;
  884. // Invalid quality value (> 1.0)
  885. EXPECT_FALSE(
  886. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  887. // Invalid quality value (< 0.0)
  888. EXPECT_FALSE(
  889. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  890. // Invalid quality value (not a number)
  891. EXPECT_FALSE(detail::parse_accept_header(
  892. "text/html;q=invalid,application/json", result));
  893. // A valid numeric prefix does not make the entire quality value valid.
  894. EXPECT_FALSE(detail::parse_accept_header(
  895. "text/html;q=0.5junk,application/json", result));
  896. // Empty quality value
  897. EXPECT_FALSE(
  898. detail::parse_accept_header("text/html;q=,application/json", result));
  899. // Invalid media type format (no slash and not wildcard)
  900. EXPECT_FALSE(
  901. detail::parse_accept_header("invalidtype,application/json", result));
  902. // Valid cases should still work
  903. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  904. EXPECT_EQ(result.size(), 1U);
  905. EXPECT_EQ(result[0], "*/*");
  906. EXPECT_TRUE(detail::parse_accept_header("*", result));
  907. EXPECT_EQ(result.size(), 1U);
  908. EXPECT_EQ(result[0], "*");
  909. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  910. EXPECT_EQ(result.size(), 1U);
  911. EXPECT_EQ(result[0], "text/*");
  912. }
  913. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  914. // elements, so a leading, trailing or doubled comma is a legal Accept value
  915. // and must not be answered with 400 Bad Request.
  916. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  917. struct {
  918. const char *value;
  919. std::vector<std::string> expected;
  920. } cases[] = {
  921. {",application/json", {"application/json"}},
  922. {"text/html,", {"text/html"}},
  923. {"text/html,,*/*", {"text/html", "*/*"}},
  924. // An empty element may be spelled with whitespace in it
  925. {"text/html, , application/json", {"text/html", "application/json"}},
  926. // Nothing but empty elements is an empty list, which means the same
  927. // thing as no Accept header at all
  928. {",,,", {}},
  929. // Quality values still apply across ignored empty elements
  930. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  931. };
  932. for (const auto &c : cases) {
  933. std::vector<std::string> result;
  934. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  935. << "value: " << c.value;
  936. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  937. }
  938. // An invalid entry is still rejected when empty elements surround it
  939. std::vector<std::string> result;
  940. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  941. }
  942. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  943. // or ';' inside one does not end the list element or the parameter. Section
  944. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  945. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  946. struct {
  947. const char *value;
  948. std::vector<std::string> expected;
  949. } cases[] = {
  950. {"text/html;profile=\"a,b\",application/json",
  951. {"text/html", "application/json"}},
  952. // A "q=" inside a quoted value is not the weight
  953. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  954. {"text/html", "application/json"}},
  955. // The weight after a quoted value still applies
  956. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  957. {"application/json", "text/html"}},
  958. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  959. {"application/json", "text/html"}},
  960. {"text/html;profile=\"a\\\"b\",application/json",
  961. {"text/html", "application/json"}},
  962. // An escaped backslash does not escape the '"' after it
  963. {"text/html;profile=\"a\\\\\",application/json",
  964. {"text/html", "application/json"}},
  965. };
  966. for (const auto &c : cases) {
  967. std::vector<std::string> result;
  968. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  969. << "value: " << c.value;
  970. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  971. }
  972. }
  973. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  974. Server svr;
  975. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  976. EXPECT_EQ(req.accept_content_types.size(), 3U);
  977. EXPECT_EQ(req.accept_content_types[0], "application/json");
  978. EXPECT_EQ(req.accept_content_types[1], "text/html");
  979. EXPECT_EQ(req.accept_content_types[2], "*/*");
  980. res.set_content("ok", "text/plain");
  981. });
  982. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  983. EXPECT_TRUE(false);
  984. res.set_content("bad request", "text/plain");
  985. });
  986. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  987. auto se = detail::scope_exit([&] {
  988. svr.stop();
  989. listen_thread.join();
  990. ASSERT_FALSE(svr.is_running());
  991. });
  992. svr.wait_until_ready();
  993. Client cli("localhost", PORT);
  994. {
  995. auto res = cli.Get(
  996. "/accept_ok",
  997. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  999. EXPECT_EQ(StatusCode::OK_200, res->status);
  1000. }
  1001. {
  1002. auto res = cli.Get("/accept_bad_request",
  1003. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1005. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1006. }
  1007. }
  1008. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1009. Server svr;
  1010. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1011. res.set_content("ok", "text/plain");
  1012. });
  1013. std::atomic<int> start_count{0};
  1014. std::atomic<bool> running_when_called{false};
  1015. svr.set_start_handler([&]() {
  1016. running_when_called = svr.is_running();
  1017. start_count++;
  1018. });
  1019. auto port = svr.bind_to_any_port(HOST);
  1020. std::thread t([&]() { svr.listen_after_bind(); });
  1021. auto se = detail::scope_exit([&] {
  1022. svr.stop();
  1023. t.join();
  1024. ASSERT_FALSE(svr.is_running());
  1025. });
  1026. svr.wait_until_ready();
  1027. // A successful request proves the accept loop is running, which the start
  1028. // handler precedes; so by now the handler must have run exactly once.
  1029. Client cli(HOST, port);
  1030. cli.set_connection_timeout(std::chrono::seconds(5));
  1031. auto res = cli.Get("/");
  1032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1033. EXPECT_EQ(StatusCode::OK_200, res->status);
  1034. EXPECT_EQ(1, start_count.load());
  1035. EXPECT_TRUE(running_when_called.load());
  1036. }
  1037. TEST(DivideTest, DivideStringTests) {
  1038. auto divide = [](const std::string &str, char d) {
  1039. std::string lhs;
  1040. std::string rhs;
  1041. detail::divide(str, d,
  1042. [&](const char *lhs_data, std::size_t lhs_size,
  1043. const char *rhs_data, std::size_t rhs_size) {
  1044. lhs.assign(lhs_data, lhs_size);
  1045. rhs.assign(rhs_data, rhs_size);
  1046. });
  1047. return std::make_pair(std::move(lhs), std::move(rhs));
  1048. };
  1049. {
  1050. const auto res = divide("", '=');
  1051. EXPECT_EQ(res.first, "");
  1052. EXPECT_EQ(res.second, "");
  1053. }
  1054. {
  1055. const auto res = divide("=", '=');
  1056. EXPECT_EQ(res.first, "");
  1057. EXPECT_EQ(res.second, "");
  1058. }
  1059. {
  1060. const auto res = divide(" ", '=');
  1061. EXPECT_EQ(res.first, " ");
  1062. EXPECT_EQ(res.second, "");
  1063. }
  1064. {
  1065. const auto res = divide("a", '=');
  1066. EXPECT_EQ(res.first, "a");
  1067. EXPECT_EQ(res.second, "");
  1068. }
  1069. {
  1070. const auto res = divide("a=", '=');
  1071. EXPECT_EQ(res.first, "a");
  1072. EXPECT_EQ(res.second, "");
  1073. }
  1074. {
  1075. const auto res = divide("=b", '=');
  1076. EXPECT_EQ(res.first, "");
  1077. EXPECT_EQ(res.second, "b");
  1078. }
  1079. {
  1080. const auto res = divide("a=b", '=');
  1081. EXPECT_EQ(res.first, "a");
  1082. EXPECT_EQ(res.second, "b");
  1083. }
  1084. {
  1085. const auto res = divide("a=b=", '=');
  1086. EXPECT_EQ(res.first, "a");
  1087. EXPECT_EQ(res.second, "b=");
  1088. }
  1089. {
  1090. const auto res = divide("a=b=c", '=');
  1091. EXPECT_EQ(res.first, "a");
  1092. EXPECT_EQ(res.second, "b=c");
  1093. }
  1094. }
  1095. TEST(SplitTest, ParseQueryString) {
  1096. string s = "key1=val1&key2=val2&key3=val3";
  1097. Params dic;
  1098. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1099. [&](const char *b, const char *e) {
  1100. string key, val;
  1101. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1102. if (key.empty()) {
  1103. key.assign(b2, e2);
  1104. } else {
  1105. val.assign(b2, e2);
  1106. }
  1107. });
  1108. dic.emplace(key, val);
  1109. });
  1110. EXPECT_EQ("val1", dic.find("key1")->second);
  1111. EXPECT_EQ("val2", dic.find("key2")->second);
  1112. EXPECT_EQ("val3", dic.find("key3")->second);
  1113. }
  1114. TEST(SplitTest, ParseInvalidQueryTests) {
  1115. {
  1116. string s = " ";
  1117. Params dict;
  1118. detail::parse_query_text(s, dict);
  1119. EXPECT_TRUE(dict.empty());
  1120. }
  1121. {
  1122. string s = " = =";
  1123. Params dict;
  1124. detail::parse_query_text(s, dict);
  1125. EXPECT_TRUE(dict.empty());
  1126. }
  1127. }
  1128. TEST(ParseQueryTest, ParseQueryString) {
  1129. {
  1130. std::string s = "key1=val1&key2=val2&key3=val3";
  1131. Params dic;
  1132. detail::parse_query_text(s, dic);
  1133. EXPECT_EQ("val1", dic.find("key1")->second);
  1134. EXPECT_EQ("val2", dic.find("key2")->second);
  1135. EXPECT_EQ("val3", dic.find("key3")->second);
  1136. }
  1137. {
  1138. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1139. Params dic;
  1140. detail::parse_query_text(s, dic);
  1141. EXPECT_EQ("", dic.find("key1")->second);
  1142. EXPECT_EQ("val1", dic.find("key2")->second);
  1143. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1144. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1145. }
  1146. }
  1147. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1148. Params dic;
  1149. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1150. dic.emplace("key1", "val1");
  1151. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1152. dic.emplace("key2", "val2");
  1153. dic.emplace("key3", "val3");
  1154. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1155. }
  1156. // Joins every entry of a Headers or Params into "key=value " so a whole
  1157. // traversal can be compared in one assertion. Both are instantiations of the
  1158. // same insertion-ordered container, so one helper serves both.
  1159. template <typename Map> static std::string entries_to_string(const Map &m) {
  1160. std::string s;
  1161. for (const auto &entry : m) {
  1162. s += entry.first + "=" + entry.second + " ";
  1163. }
  1164. return s;
  1165. }
  1166. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1167. // Params used to be a std::multimap, which sorted by name and handed the
  1168. // caller's query back alphabetised. A client signing its query string could
  1169. // not reproduce the order it asked for.
  1170. Params dic;
  1171. dic.emplace("zulu", "1");
  1172. dic.emplace("alpha", "2");
  1173. dic.emplace("mike", "3");
  1174. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1175. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1176. }
  1177. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1178. Params dic;
  1179. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1180. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1181. }
  1182. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1183. Request req;
  1184. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1185. req.params);
  1186. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1187. EXPECT_EQ("first", req.get_param_value("tag"));
  1188. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1189. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1190. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1191. EXPECT_EQ("", req.get_param_value("tag", 3));
  1192. }
  1193. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1194. // Params shares its container with Headers, which matches field names
  1195. // case-insensitively. Parameter names must not pick that up.
  1196. Params dic;
  1197. dic.emplace("Key", "upper");
  1198. dic.emplace("key", "lower");
  1199. EXPECT_EQ(2U, dic.size());
  1200. EXPECT_EQ(1U, dic.count("Key"));
  1201. EXPECT_EQ(1U, dic.count("key"));
  1202. EXPECT_EQ("upper", dic.find("Key")->second);
  1203. EXPECT_EQ("lower", dic.find("key")->second);
  1204. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1205. }
  1206. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1207. Server svr;
  1208. std::string order;
  1209. svr.Get("/order", [&](const Request &req, Response &res) {
  1210. order = entries_to_string(req.params);
  1211. res.set_content("ok", "text/plain");
  1212. });
  1213. auto port = svr.bind_to_any_port(HOST);
  1214. thread t = thread([&] { svr.listen_after_bind(); });
  1215. auto se = detail::scope_exit([&] {
  1216. svr.stop();
  1217. t.join();
  1218. ASSERT_FALSE(svr.is_running());
  1219. });
  1220. svr.wait_until_ready();
  1221. Client cli(HOST, port);
  1222. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1223. ASSERT_TRUE(res);
  1224. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1225. }
  1226. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1227. Server svr;
  1228. std::string field_order, file_order;
  1229. svr.Post("/order", [&](const Request &req, Response &res) {
  1230. for (const auto &field : req.form.fields) {
  1231. field_order += field.first + "=" + field.second.content + " ";
  1232. }
  1233. for (const auto &file : req.form.files) {
  1234. file_order += file.first + "=" + file.second.filename + " ";
  1235. }
  1236. res.set_content("ok", "text/plain");
  1237. });
  1238. auto port = svr.bind_to_any_port(HOST);
  1239. thread t = thread([&] { svr.listen_after_bind(); });
  1240. auto se = detail::scope_exit([&] {
  1241. svr.stop();
  1242. t.join();
  1243. ASSERT_FALSE(svr.is_running());
  1244. });
  1245. svr.wait_until_ready();
  1246. UploadFormDataItems items = {
  1247. {"zulu", "1", "", ""},
  1248. {"alpha", "2", "", ""},
  1249. {"mike", "3", "", ""},
  1250. {"zebra", "z", "z.txt", "text/plain"},
  1251. {"apple", "a", "a.txt", "text/plain"},
  1252. };
  1253. Client cli(HOST, port);
  1254. auto res = cli.Post("/order", items);
  1255. ASSERT_TRUE(res);
  1256. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1257. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1258. }
  1259. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1260. Server svr;
  1261. std::vector<std::string> values;
  1262. std::string first, second, out_of_range, order;
  1263. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1264. values = req.form.get_fields("tag");
  1265. first = req.form.get_field("tag", 0);
  1266. second = req.form.get_field("tag", 1);
  1267. out_of_range = req.form.get_field("tag", 2);
  1268. for (const auto &field : req.form.fields) {
  1269. order += field.first + "=" + field.second.content + " ";
  1270. }
  1271. res.set_content("ok", "text/plain");
  1272. });
  1273. auto port = svr.bind_to_any_port(HOST);
  1274. thread t = thread([&] { svr.listen_after_bind(); });
  1275. auto se = detail::scope_exit([&] {
  1276. svr.stop();
  1277. t.join();
  1278. ASSERT_FALSE(svr.is_running());
  1279. });
  1280. svr.wait_until_ready();
  1281. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1282. // not adjacent in the container.
  1283. UploadFormDataItems items = {
  1284. {"tag", "first", "", ""},
  1285. {"other", "x", "", ""},
  1286. {"tag", "second", "", ""},
  1287. };
  1288. Client cli(HOST, port);
  1289. auto res = cli.Post("/repeated", items);
  1290. ASSERT_TRUE(res);
  1291. ASSERT_EQ(2U, values.size());
  1292. EXPECT_EQ("first", values[0]);
  1293. EXPECT_EQ("second", values[1]);
  1294. EXPECT_EQ("first", first);
  1295. EXPECT_EQ("second", second);
  1296. // std::multimap already kept entries sharing a name in insertion order, so
  1297. // everything above passes without this change too. The whole traversal is
  1298. // what tells the two apart: sorting by name would hoist "other" to the front
  1299. // and the two "tag" parts would end up adjacent.
  1300. EXPECT_EQ("tag=first other=x tag=second ", order);
  1301. // Advancing past the last entry of a name used to run off the container;
  1302. // the container's saturating increment makes it return the default instead.
  1303. EXPECT_EQ("", out_of_range);
  1304. }
  1305. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1306. // Server::read_content() keeps a FormFields::iterator alive across the
  1307. // content callbacks that fill the part it points at. The container is
  1308. // vector-backed, so a later emplace can reallocate and invalidate an older
  1309. // iterator; 64 parts grow the vector through seven reallocations, which
  1310. // checks that every part's content still lands in its own entry.
  1311. const size_t part_count = 64;
  1312. // One formula for both the parts sent and the values expected back, so the
  1313. // two cannot drift apart.
  1314. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1315. auto content_of = [](size_t i) {
  1316. return std::string(64, static_cast<char>('a' + (i % 26)));
  1317. };
  1318. Server svr;
  1319. std::vector<std::pair<std::string, std::string>> received;
  1320. svr.Post("/many", [&](const Request &req, Response &res) {
  1321. for (const auto &field : req.form.fields) {
  1322. received.emplace_back(field.first, field.second.content);
  1323. }
  1324. res.set_content("ok", "text/plain");
  1325. });
  1326. auto port = svr.bind_to_any_port(HOST);
  1327. thread t = thread([&] { svr.listen_after_bind(); });
  1328. auto se = detail::scope_exit([&] {
  1329. svr.stop();
  1330. t.join();
  1331. ASSERT_FALSE(svr.is_running());
  1332. });
  1333. svr.wait_until_ready();
  1334. UploadFormDataItems items;
  1335. for (size_t i = 0; i < part_count; i++) {
  1336. items.push_back({name_of(i), content_of(i), "", ""});
  1337. }
  1338. Client cli(HOST, port);
  1339. auto res = cli.Post("/many", items);
  1340. ASSERT_TRUE(res);
  1341. ASSERT_EQ(part_count, received.size());
  1342. for (size_t i = 0; i < part_count; i++) {
  1343. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1344. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1345. }
  1346. }
  1347. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1348. string content_type = "multipart/form-data; boundary=something";
  1349. string boundary;
  1350. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1351. EXPECT_TRUE(ret);
  1352. EXPECT_EQ(boundary, "something");
  1353. }
  1354. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1355. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1356. string boundary;
  1357. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1358. EXPECT_TRUE(ret);
  1359. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1360. }
  1361. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1362. string content_type =
  1363. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1364. string boundary;
  1365. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1366. EXPECT_TRUE(ret);
  1367. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1368. }
  1369. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1370. string content_type =
  1371. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1372. string boundary;
  1373. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1374. EXPECT_TRUE(ret);
  1375. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1376. }
  1377. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1378. const string boundary(70, 'a');
  1379. string content_type = "multipart/form-data; boundary=" + boundary;
  1380. string parsed;
  1381. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1382. EXPECT_TRUE(ret);
  1383. EXPECT_EQ(parsed, boundary);
  1384. }
  1385. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1386. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1387. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1388. string parsed;
  1389. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1390. EXPECT_FALSE(ret);
  1391. }
  1392. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1393. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1394. // is 72 characters on the wire and still valid.
  1395. const string boundary(70, 'a');
  1396. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1397. string parsed;
  1398. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1399. EXPECT_EQ(parsed, boundary);
  1400. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1401. parsed.clear();
  1402. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1403. }
  1404. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1405. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1406. // The parameter parser must not treat that '=' as the key/value separator.
  1407. string content_type =
  1408. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1409. "charset=UTF-8";
  1410. string parsed;
  1411. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1412. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1413. }
  1414. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1415. // A ';' inside the quoted-string is part of the value, not a parameter
  1416. // separator, so it must not truncate the boundary.
  1417. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1418. string parsed;
  1419. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1420. EXPECT_EQ(parsed, "a;b");
  1421. }
  1422. TEST(ParseDispositionParamsTest, QuotedValues) {
  1423. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1424. // ';' and '=' are ordinary characters inside one.
  1425. struct {
  1426. const char *value;
  1427. std::vector<std::pair<const char *, const char *>> expected;
  1428. } cases[] = {
  1429. {"name=\"file1\"; filename=\"a.txt\"",
  1430. {{"name", "file1"}, {"filename", "a.txt"}}},
  1431. // Whitespace around '=' and ';' is still trimmed
  1432. {"name=\"file2\" ;filename = \"a.html\"",
  1433. {{"name", "file2"}, {"filename", "a.html"}}},
  1434. // '=' inside the value used to leave only the text after the last one
  1435. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1436. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1437. {"name=\"x=y\"", {{"name", "x=y"}}},
  1438. // ';' inside the value used to truncate the pair and leave a bogus one
  1439. {"name=\"file3\"; filename=\"a;b.txt\"",
  1440. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1441. // An unquoted value keeps working, and so does filename*
  1442. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1443. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1444. // A parameter with no key is dropped rather than turned into one whose
  1445. // key is the value
  1446. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1447. };
  1448. for (const auto &c : cases) {
  1449. Params params;
  1450. detail::parse_disposition_params(c.value, params);
  1451. for (const auto &kv : c.expected) {
  1452. auto it = params.find(kv.first);
  1453. ASSERT_NE(it, params.end())
  1454. << "value: " << c.value << ", key: " << kv.first;
  1455. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1456. }
  1457. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1458. }
  1459. }
  1460. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1461. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1462. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1463. Server svr;
  1464. std::string field_value, file_name, file_filename;
  1465. bool has_field = false, has_file = false;
  1466. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1467. has_field = req.form.has_field("x=y");
  1468. field_value = req.form.get_field("x=y");
  1469. has_file = req.form.has_file("file1");
  1470. const auto &file = req.form.get_file("file1");
  1471. file_name = file.name;
  1472. file_filename = file.filename;
  1473. res.set_content("ok", "text/plain");
  1474. });
  1475. auto port = svr.bind_to_any_port(HOST);
  1476. thread t = thread([&] { svr.listen_after_bind(); });
  1477. auto se = detail::scope_exit([&] {
  1478. svr.stop();
  1479. t.join();
  1480. ASSERT_FALSE(svr.is_running());
  1481. });
  1482. svr.wait_until_ready();
  1483. UploadFormDataItems items = {
  1484. {"x=y", "field-value", "", ""},
  1485. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1486. };
  1487. Client cli(HOST, port);
  1488. auto res = cli.Post("/quoted", items);
  1489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1490. ASSERT_EQ(StatusCode::OK_200, res->status);
  1491. EXPECT_TRUE(has_field);
  1492. EXPECT_EQ("field-value", field_value);
  1493. EXPECT_TRUE(has_file);
  1494. EXPECT_EQ("file1", file_name);
  1495. EXPECT_EQ("a;b=report.pdf", file_filename);
  1496. }
  1497. TEST(GetHeaderValueTest, DefaultValue) {
  1498. Headers headers = {{"Dummy", "Dummy"}};
  1499. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1500. EXPECT_STREQ("text/plain", val);
  1501. }
  1502. TEST(GetHeaderValueTest, DefaultValueInt) {
  1503. Headers headers = {{"Dummy", "Dummy"}};
  1504. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1505. EXPECT_EQ(100ull, val);
  1506. }
  1507. TEST(GetHeaderValueTest, RegularValue) {
  1508. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1509. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1510. EXPECT_STREQ("text/html", val);
  1511. }
  1512. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1513. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1514. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1515. EXPECT_STREQ("text/html", val);
  1516. }
  1517. TEST(GetHeaderValueTest, SetContent) {
  1518. Response res;
  1519. res.set_content("html", "text/html");
  1520. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1521. res.set_content("text", "text/plain");
  1522. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1523. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1524. }
  1525. TEST(GetHeaderValueTest, RegularValueInt) {
  1526. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1527. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1528. EXPECT_EQ(100ull, val);
  1529. }
  1530. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1531. Headers headers = {{"Content-Length", "x"}};
  1532. auto is_invalid_value = false;
  1533. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1534. is_invalid_value);
  1535. EXPECT_EQ(0ull, val);
  1536. EXPECT_TRUE(is_invalid_value);
  1537. }
  1538. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1539. // An all-digit value that overflows size_t must be reported as invalid, not
  1540. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1541. // a large length to a small one on 32-bit builds, leaving the framing length
  1542. // wrong while is_invalid_value stayed false.
  1543. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1544. auto is_invalid_value = false;
  1545. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1546. is_invalid_value);
  1547. EXPECT_TRUE(is_invalid_value);
  1548. // A well-formed length is unaffected.
  1549. Headers ok = {{"Content-Length", "1234"}};
  1550. is_invalid_value = false;
  1551. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1552. is_invalid_value);
  1553. EXPECT_EQ(1234ull, val);
  1554. EXPECT_FALSE(is_invalid_value);
  1555. }
  1556. TEST(GetHeaderValueTest, Range) {
  1557. {
  1558. Headers headers = {make_range_header({{1, -1}})};
  1559. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1560. EXPECT_STREQ("bytes=1-", val);
  1561. }
  1562. {
  1563. Headers headers = {make_range_header({{-1, 1}})};
  1564. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1565. EXPECT_STREQ("bytes=-1", val);
  1566. }
  1567. {
  1568. Headers headers = {make_range_header({{1, 10}})};
  1569. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1570. EXPECT_STREQ("bytes=1-10", val);
  1571. }
  1572. {
  1573. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1574. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1575. EXPECT_STREQ("bytes=1-10, 100-", val);
  1576. }
  1577. {
  1578. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1579. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1580. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1581. }
  1582. {
  1583. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1584. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1585. EXPECT_STREQ("bytes=0-0, -1", val);
  1586. }
  1587. }
  1588. TEST(BearerTokenAuthTest, SchemeValidation) {
  1589. // A value shorter than "Bearer " must not throw from the fixed-length
  1590. // substr, and a non-Bearer scheme must not be reported as a token.
  1591. struct {
  1592. const char *value;
  1593. const char *expected;
  1594. } cases[] = {
  1595. {"x", ""},
  1596. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1597. {"Bearer abc123", "abc123"},
  1598. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1599. };
  1600. for (const auto &c : cases) {
  1601. Request req;
  1602. req.set_header("Authorization", c.value);
  1603. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1604. }
  1605. }
  1606. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1607. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1608. // to depend on the standard library (libstdc++ handed back duplicates in
  1609. // reverse insertion order, libc++ in insertion order).
  1610. Request req;
  1611. req.set_header("Accept-Encoding", "gzip");
  1612. req.set_header("Accept-Encoding", "deflate");
  1613. req.set_header("Accept-Encoding", "br");
  1614. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1615. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1616. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1617. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1618. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1619. }
  1620. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1621. Request req;
  1622. req.set_header("X-Test", "only");
  1623. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1624. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1625. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1626. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1627. }
  1628. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1629. Request req;
  1630. req.set_header("X-First", "1");
  1631. req.set_header("X-Test", "2");
  1632. req.params.emplace("first", "1");
  1633. req.params.emplace("test", "2");
  1634. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1635. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1636. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1637. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1638. // The second one is negative when read as a signed value
  1639. const auto max_id = (std::numeric_limits<size_t>::max)();
  1640. for (auto id : {max_id / 2, max_id}) {
  1641. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1642. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1643. EXPECT_EQ("", req.get_param_value("test", id));
  1644. EXPECT_EQ("", req.form.get_field("test", id));
  1645. EXPECT_EQ("", req.form.get_file("test", id).content);
  1646. }
  1647. }
  1648. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1649. Headers headers;
  1650. headers.emplace("Host", "example.com");
  1651. headers.emplace("Accept-Encoding", "gzip");
  1652. headers.emplace("User-Agent", "test");
  1653. headers.emplace("Accept-Encoding", "deflate");
  1654. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1655. "Accept-Encoding=deflate ",
  1656. entries_to_string(headers));
  1657. }
  1658. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1659. Headers headers = {{"Content-Type", "text/html"},
  1660. {"CONTENT-TYPE", "text/xml"}};
  1661. EXPECT_EQ(2U, headers.count("content-type"));
  1662. auto it = headers.find("content-type");
  1663. ASSERT_TRUE(it != headers.end());
  1664. EXPECT_EQ("text/html", it->second);
  1665. }
  1666. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1667. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1668. // drop only those fields and leave everything positioned between them.
  1669. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1670. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1671. auto rng = headers.equal_range("a");
  1672. headers.erase(rng.first, rng.second);
  1673. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1674. }
  1675. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1676. Headers headers = {
  1677. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1678. EXPECT_EQ(3U, headers.erase("A"));
  1679. EXPECT_EQ(0U, headers.count("A"));
  1680. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1681. }
  1682. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1683. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1684. headers.emplace_front("Host", "example.com");
  1685. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1686. entries_to_string(headers));
  1687. }
  1688. TEST(ParseHeaderValueTest, Range) {
  1689. {
  1690. Ranges ranges;
  1691. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1692. EXPECT_TRUE(ret);
  1693. EXPECT_EQ(1u, ranges.size());
  1694. EXPECT_EQ(1u, ranges[0].first);
  1695. EXPECT_EQ(-1, ranges[0].second);
  1696. }
  1697. {
  1698. Ranges ranges;
  1699. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1700. EXPECT_TRUE(ret);
  1701. EXPECT_EQ(1u, ranges.size());
  1702. EXPECT_EQ(-1, ranges[0].first);
  1703. EXPECT_EQ(1u, ranges[0].second);
  1704. }
  1705. {
  1706. Ranges ranges;
  1707. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1708. EXPECT_TRUE(ret);
  1709. EXPECT_EQ(1u, ranges.size());
  1710. EXPECT_EQ(1u, ranges[0].first);
  1711. EXPECT_EQ(10u, ranges[0].second);
  1712. }
  1713. {
  1714. Ranges ranges;
  1715. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1716. EXPECT_FALSE(ret);
  1717. }
  1718. {
  1719. Ranges ranges;
  1720. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(2u, ranges.size());
  1723. EXPECT_EQ(1u, ranges[0].first);
  1724. EXPECT_EQ(10u, ranges[0].second);
  1725. EXPECT_EQ(100u, ranges[1].first);
  1726. EXPECT_EQ(-1, ranges[1].second);
  1727. }
  1728. {
  1729. Ranges ranges;
  1730. auto ret =
  1731. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1732. EXPECT_TRUE(ret);
  1733. EXPECT_EQ(3u, ranges.size());
  1734. EXPECT_EQ(1u, ranges[0].first);
  1735. EXPECT_EQ(10u, ranges[0].second);
  1736. EXPECT_EQ(100u, ranges[1].first);
  1737. EXPECT_EQ(200u, ranges[1].second);
  1738. EXPECT_EQ(300u, ranges[2].first);
  1739. EXPECT_EQ(400u, ranges[2].second);
  1740. }
  1741. {
  1742. Ranges ranges;
  1743. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1744. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1745. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1746. EXPECT_FALSE(detail::parse_range_header("bytes=-", 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=a-b", ranges));
  1752. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1753. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1754. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1755. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1756. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1757. EXPECT_FALSE(
  1758. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1759. EXPECT_TRUE(ranges.empty());
  1760. }
  1761. {
  1762. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1763. // remainder of the representation, so it stays accepted.
  1764. Ranges ranges;
  1765. auto ret =
  1766. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1767. EXPECT_TRUE(ret);
  1768. ASSERT_EQ(1u, ranges.size());
  1769. EXPECT_EQ(0, ranges[0].first);
  1770. EXPECT_EQ(-1, ranges[0].second);
  1771. }
  1772. // RFC 9110 14.1: range unit names are case-insensitive.
  1773. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1774. Ranges ranges;
  1775. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1776. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1777. }
  1778. }
  1779. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1780. Request req;
  1781. req.set_header("Accept-Encoding", "gzip");
  1782. Response res;
  1783. res.set_header("Content-Type", "text/plain");
  1784. auto ret = detail::encoding_type(req, res);
  1785. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1786. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1787. #else
  1788. EXPECT_TRUE(ret == detail::EncodingType::None);
  1789. #endif
  1790. }
  1791. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1798. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1799. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1800. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1801. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1802. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1803. #else
  1804. EXPECT_TRUE(ret == detail::EncodingType::None);
  1805. #endif
  1806. }
  1807. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1808. Request req;
  1809. req.set_header("Accept-Encoding",
  1810. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1811. Response res;
  1812. res.set_header("Content-Type", "text/plain");
  1813. auto ret = detail::encoding_type(req, res);
  1814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1815. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1816. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1817. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1818. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1819. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1820. #else
  1821. EXPECT_TRUE(ret == detail::EncodingType::None);
  1822. #endif
  1823. }
  1824. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1825. // All supported encodings rejected with q=0 should return None
  1826. Request req;
  1827. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1828. Response res;
  1829. res.set_header("Content-Type", "text/plain");
  1830. auto ret = detail::encoding_type(req, res);
  1831. EXPECT_TRUE(ret == detail::EncodingType::None);
  1832. }
  1833. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1834. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1835. Request req;
  1836. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1837. Response res;
  1838. res.set_header("Content-Type", "text/plain");
  1839. auto ret = detail::encoding_type(req, res);
  1840. EXPECT_TRUE(ret == detail::EncodingType::None);
  1841. }
  1842. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1843. Request req;
  1844. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1845. Response res;
  1846. res.set_header("Content-Type", "text/plain");
  1847. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1848. }
  1849. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1850. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1851. Request req;
  1852. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1853. Response res;
  1854. res.set_header("Content-Type", "text/plain");
  1855. auto ret = detail::encoding_type(req, res);
  1856. EXPECT_TRUE(ret == detail::EncodingType::None);
  1857. }
  1858. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1859. // RFC 7231: Accept-Encoding values are case-insensitive
  1860. Request req;
  1861. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1862. Response res;
  1863. res.set_header("Content-Type", "text/plain");
  1864. auto ret = detail::encoding_type(req, res);
  1865. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1866. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1867. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1868. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1869. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1870. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1871. #else
  1872. EXPECT_TRUE(ret == detail::EncodingType::None);
  1873. #endif
  1874. }
  1875. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1876. // q value should determine priority, not hardcoded order
  1877. Request req;
  1878. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1879. Response res;
  1880. res.set_header("Content-Type", "text/plain");
  1881. auto ret = detail::encoding_type(req, res);
  1882. // gzip has highest q=1.0, so it should be selected even though
  1883. // br and zstd are also supported
  1884. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1885. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1886. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1887. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1888. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1889. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1890. #else
  1891. EXPECT_TRUE(ret == detail::EncodingType::None);
  1892. #endif
  1893. }
  1894. TEST(BufferStreamTest, read) {
  1895. detail::BufferStream strm1;
  1896. Stream &strm = strm1;
  1897. EXPECT_EQ(5, strm.write("hello"));
  1898. char buf[512];
  1899. EXPECT_EQ(2, strm.read(buf, 2));
  1900. EXPECT_EQ('h', buf[0]);
  1901. EXPECT_EQ('e', buf[1]);
  1902. EXPECT_EQ(2, strm.read(buf, 2));
  1903. EXPECT_EQ('l', buf[0]);
  1904. EXPECT_EQ('l', buf[1]);
  1905. EXPECT_EQ(1, strm.read(buf, 1));
  1906. EXPECT_EQ('o', buf[0]);
  1907. EXPECT_EQ(0, strm.read(buf, 1));
  1908. }
  1909. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1910. auto host = "www.httpwatch.com";
  1911. auto ip = hosted_at(host);
  1912. EXPECT_EQ("23.96.13.243", ip);
  1913. std::vector<std::string> addrs;
  1914. hosted_at(host, addrs);
  1915. EXPECT_EQ(1u, addrs.size());
  1916. }
  1917. #if 0 // It depends on each test environment...
  1918. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1919. auto host = "www.youtube.com";
  1920. std::vector<std::string> addrs;
  1921. hosted_at(host, addrs);
  1922. EXPECT_EQ(20u, addrs.size());
  1923. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1924. EXPECT_TRUE(it != addrs.end());
  1925. }
  1926. #endif
  1927. class ChunkedEncodingTest : public ::testing::Test {
  1928. protected:
  1929. ChunkedEncodingTest()
  1930. : cli_(HOST, PORT)
  1931. #ifdef CPPHTTPLIB_SSL_ENABLED
  1932. ,
  1933. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1934. #endif
  1935. {
  1936. cli_.set_connection_timeout(2);
  1937. #ifdef CPPHTTPLIB_SSL_ENABLED
  1938. cli_.enable_server_certificate_verification(false);
  1939. #endif
  1940. }
  1941. virtual void SetUp() {
  1942. read_file("./image.jpg", image_data_);
  1943. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1944. res.set_content("Hello World!", "text/plain");
  1945. });
  1946. svr_.Get(
  1947. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1948. res.set_chunked_content_provider(
  1949. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1950. size_t remaining = image_data_.size() - offset;
  1951. if (remaining == 0) {
  1952. sink.done();
  1953. } else {
  1954. constexpr size_t CHUNK_SIZE = 1024;
  1955. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1956. sink.write(&image_data_[offset], send_size);
  1957. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1958. }
  1959. return true;
  1960. });
  1961. });
  1962. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1963. svr_.wait_until_ready();
  1964. }
  1965. virtual void TearDown() {
  1966. svr_.stop();
  1967. if (!request_threads_.empty()) {
  1968. std::this_thread::sleep_for(std::chrono::seconds(1));
  1969. for (auto &t : request_threads_) {
  1970. t.join();
  1971. }
  1972. }
  1973. t_.join();
  1974. }
  1975. #ifdef CPPHTTPLIB_SSL_ENABLED
  1976. SSLClient cli_;
  1977. SSLServer svr_;
  1978. #else
  1979. Client cli_;
  1980. Server svr_;
  1981. #endif
  1982. thread t_;
  1983. std::vector<thread> request_threads_;
  1984. std::string image_data_;
  1985. };
  1986. TEST_F(ChunkedEncodingTest, NormalGet) {
  1987. auto res = cli_.Get("/chunked");
  1988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1989. std::string out;
  1990. read_file("./image.jpg", out);
  1991. EXPECT_EQ(StatusCode::OK_200, res->status);
  1992. EXPECT_EQ(out, res->body);
  1993. }
  1994. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1995. std::string body;
  1996. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1997. body.append(data, data_length);
  1998. return true;
  1999. });
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. std::string out;
  2002. read_file("./image.jpg", out);
  2003. EXPECT_EQ(StatusCode::OK_200, res->status);
  2004. EXPECT_EQ(out, body);
  2005. }
  2006. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2007. std::string body;
  2008. auto res = cli_.Get(
  2009. "/chunked",
  2010. [&](const Response &response) {
  2011. EXPECT_EQ(StatusCode::OK_200, response.status);
  2012. return true;
  2013. },
  2014. [&](const char *data, size_t data_length) {
  2015. body.append(data, data_length);
  2016. return true;
  2017. });
  2018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2019. std::string out;
  2020. read_file("./image.jpg", out);
  2021. EXPECT_EQ(StatusCode::OK_200, res->status);
  2022. EXPECT_EQ(out, body);
  2023. }
  2024. TEST(RangeTest, FromHTTPBin_Online) {
  2025. auto host = "httpbingo.org";
  2026. auto path = std::string{"/range/32"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(5);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2038. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. }
  2041. {
  2042. Headers headers = {make_range_header({{1, -1}})};
  2043. auto res = cli.Get(path, headers);
  2044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2045. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2046. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2047. }
  2048. {
  2049. Headers headers = {make_range_header({{1, 10}})};
  2050. auto res = cli.Get(path, headers);
  2051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2052. EXPECT_EQ("bcdefghijk", res->body);
  2053. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2054. }
  2055. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2056. // entire resource, while the original httpbin returned 200. Both are
  2057. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2058. {
  2059. Headers headers = {make_range_header({{0, 31}})};
  2060. auto res = cli.Get(path, headers);
  2061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2062. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2063. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2064. res->status == StatusCode::PartialContent_206);
  2065. }
  2066. {
  2067. Headers headers = {make_range_header({{0, -1}})};
  2068. auto res = cli.Get(path, headers);
  2069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2070. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2071. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2072. res->status == StatusCode::PartialContent_206);
  2073. }
  2074. // go-httpbin returns 206 with clamped range for over-range requests,
  2075. // while the original httpbin returned 416. Both behaviors are observed
  2076. // in real servers, so we only verify the request succeeds.
  2077. {
  2078. Headers headers = {make_range_header({{0, 32}})};
  2079. auto res = cli.Get(path, headers);
  2080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2081. }
  2082. }
  2083. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2084. auto host = "unresolvableaddress.local";
  2085. auto path = std::string{"/"};
  2086. #ifdef CPPHTTPLIB_SSL_ENABLED
  2087. auto port = 443;
  2088. SSLClient cli(host, port);
  2089. #else
  2090. auto port = 80;
  2091. Client cli(host, port);
  2092. #endif
  2093. cli.set_connection_timeout(1);
  2094. {
  2095. auto res = cli.Get(path);
  2096. ASSERT_FALSE(res);
  2097. }
  2098. std::this_thread::sleep_for(std::chrono::seconds(8));
  2099. }
  2100. #if defined(__linux__) && defined(__GLIBC__) && \
  2101. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2102. // Forward declaration: in split builds split.py strips `inline` and moves the
  2103. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2104. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2105. // against the symbol in both header-only and split builds.
  2106. namespace httplib {
  2107. namespace detail {
  2108. int getaddrinfo_with_timeout(const char *node, const char *service,
  2109. const struct addrinfo *hints,
  2110. struct addrinfo **res, time_t timeout_sec);
  2111. } // namespace detail
  2112. } // namespace httplib
  2113. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2114. //
  2115. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2116. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2117. // gai_suspend() call hits the connection timeout the function calls
  2118. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2119. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2120. // still alive and still references the now-destroyed stack frame.
  2121. //
  2122. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2123. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2124. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2125. // and runs them in a container.
  2126. namespace {
  2127. bool should_run_issue_2431_tests() {
  2128. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2129. return v && *v && std::string(v) != "0";
  2130. }
  2131. std::string unique_unresolvable_host(int n) {
  2132. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2133. // glibc still asks the configured nameserver — which is exactly the path
  2134. // we want to exercise. A unique label per call avoids the resolver cache.
  2135. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2136. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2137. std::to_string(n) + ".invalid";
  2138. }
  2139. } // namespace
  2140. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2141. if (!should_run_issue_2431_tests()) {
  2142. GTEST_SKIP()
  2143. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2144. }
  2145. for (int i = 0; i < 8; ++i) {
  2146. struct addrinfo hints;
  2147. memset(&hints, 0, sizeof(hints));
  2148. hints.ai_family = AF_UNSPEC;
  2149. hints.ai_socktype = SOCK_STREAM;
  2150. auto host = unique_unresolvable_host(i);
  2151. struct addrinfo *result = nullptr;
  2152. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2153. &result, /*timeout_sec=*/1);
  2154. if (rc == 0 && result) { freeaddrinfo(result); }
  2155. }
  2156. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2157. // stack region they still believe holds their gaicb.
  2158. std::this_thread::sleep_for(std::chrono::seconds(3));
  2159. }
  2160. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2161. if (!should_run_issue_2431_tests()) {
  2162. GTEST_SKIP()
  2163. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2164. }
  2165. std::atomic<bool> stop{false};
  2166. std::vector<std::thread> threads;
  2167. for (int t = 0; t < 8; ++t) {
  2168. threads.emplace_back([t, &stop] {
  2169. int i = 0;
  2170. while (!stop.load(std::memory_order_relaxed)) {
  2171. struct addrinfo hints;
  2172. memset(&hints, 0, sizeof(hints));
  2173. hints.ai_family = AF_UNSPEC;
  2174. hints.ai_socktype = SOCK_STREAM;
  2175. auto host = unique_unresolvable_host(t * 100000 + i++);
  2176. struct addrinfo *result = nullptr;
  2177. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2178. &result, /*timeout_sec=*/1);
  2179. if (rc == 0 && result) { freeaddrinfo(result); }
  2180. }
  2181. });
  2182. }
  2183. std::this_thread::sleep_for(std::chrono::seconds(8));
  2184. stop.store(true, std::memory_order_relaxed);
  2185. for (auto &th : threads) {
  2186. th.join();
  2187. }
  2188. std::this_thread::sleep_for(std::chrono::seconds(3));
  2189. }
  2190. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2191. if (!should_run_issue_2431_tests()) {
  2192. GTEST_SKIP()
  2193. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2194. }
  2195. std::atomic<bool> stop{false};
  2196. std::vector<std::thread> threads;
  2197. for (int t = 0; t < 8; ++t) {
  2198. threads.emplace_back([t, &stop] {
  2199. int i = 0;
  2200. while (!stop.load(std::memory_order_relaxed)) {
  2201. auto host = unique_unresolvable_host(t * 100000 + i++);
  2202. Client cli(host, 80);
  2203. cli.set_connection_timeout(1, 0);
  2204. cli.set_read_timeout(1, 0);
  2205. cli.set_write_timeout(1, 0);
  2206. (void)cli.Get("/");
  2207. }
  2208. });
  2209. }
  2210. std::this_thread::sleep_for(std::chrono::seconds(8));
  2211. stop.store(true, std::memory_order_relaxed);
  2212. for (auto &th : threads) {
  2213. th.join();
  2214. }
  2215. std::this_thread::sleep_for(std::chrono::seconds(3));
  2216. }
  2217. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2218. TEST(ConnectionErrorTest, InvalidHost) {
  2219. auto host = "-abcde.com";
  2220. #ifdef CPPHTTPLIB_SSL_ENABLED
  2221. auto port = 443;
  2222. SSLClient cli(host, port);
  2223. #else
  2224. auto port = 80;
  2225. Client cli(host, port);
  2226. #endif
  2227. cli.set_connection_timeout(std::chrono::seconds(2));
  2228. auto res = cli.Get("/");
  2229. ASSERT_TRUE(!res);
  2230. EXPECT_EQ(Error::Connection, res.error());
  2231. }
  2232. TEST(ConnectionErrorTest, InvalidHost2) {
  2233. auto host = "httpcan.org/";
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. SSLClient cli(host);
  2236. #else
  2237. Client cli(host);
  2238. #endif
  2239. cli.set_connection_timeout(std::chrono::seconds(2));
  2240. auto res = cli.Get("/");
  2241. ASSERT_TRUE(!res);
  2242. EXPECT_EQ(Error::Connection, res.error());
  2243. }
  2244. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2245. auto host = "httpcan.org/";
  2246. #ifdef CPPHTTPLIB_SSL_ENABLED
  2247. SSLClient cli(host);
  2248. #else
  2249. Client cli(host);
  2250. #endif
  2251. cli.set_connection_timeout(std::chrono::seconds(2));
  2252. auto res = cli.Get("/");
  2253. ASSERT_TRUE(!res);
  2254. stringstream s;
  2255. s << "error code: " << res.error();
  2256. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2257. }
  2258. TEST(ConnectionErrorTest, InvalidPort) {
  2259. auto host = "localhost";
  2260. auto port = 44380;
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. SSLClient cli(host, port);
  2263. #else
  2264. Client cli(host, port);
  2265. #endif
  2266. cli.set_connection_timeout(std::chrono::seconds(2));
  2267. auto res = cli.Get("/");
  2268. ASSERT_TRUE(!res);
  2269. EXPECT_TRUE(Error::Connection == res.error() ||
  2270. Error::ConnectionTimeout == res.error());
  2271. }
  2272. TEST(ConnectionErrorTest, Timeout_Online) {
  2273. auto host = "google.com";
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 44380;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 8080;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(std::chrono::seconds(2));
  2282. // only probe one address type so that the error reason
  2283. // correlates to the timed-out IPv4, not the unsupported
  2284. // IPv6 connection attempt
  2285. cli.set_address_family(AF_INET);
  2286. auto res = cli.Get("/");
  2287. ASSERT_TRUE(!res);
  2288. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2289. }
  2290. TEST(CancelTest, NoCancel_Online) {
  2291. auto host = "httpbingo.org";
  2292. auto path = std::string{"/range/32"};
  2293. #ifdef CPPHTTPLIB_SSL_ENABLED
  2294. auto port = 443;
  2295. SSLClient cli(host, port);
  2296. #else
  2297. auto port = 80;
  2298. Client cli(host, port);
  2299. #endif
  2300. cli.set_connection_timeout(std::chrono::seconds(5));
  2301. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_EQ(StatusCode::OK_200, res->status);
  2305. }
  2306. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2307. // Use /bytes with a large payload so that the DownloadProgress callback
  2308. // (which only fires for Content-Length responses) is invoked before the
  2309. // entire body is received, giving cancellation a chance to fire.
  2310. auto host = "httpbingo.org";
  2311. auto path = std::string{"/bytes/524288"};
  2312. #ifdef CPPHTTPLIB_SSL_ENABLED
  2313. auto port = 443;
  2314. SSLClient cli(host, port);
  2315. #else
  2316. auto port = 80;
  2317. Client cli(host, port);
  2318. #endif
  2319. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2320. cli.set_connection_timeout(std::chrono::seconds(5));
  2321. ASSERT_TRUE(!res);
  2322. EXPECT_EQ(Error::Canceled, res.error());
  2323. }
  2324. TEST(CancelTest, WithCancelLargePayload_Online) {
  2325. auto host = "httpbingo.org";
  2326. auto path = std::string{"/bytes/524288"};
  2327. #ifdef CPPHTTPLIB_SSL_ENABLED
  2328. auto port = 443;
  2329. SSLClient cli(host, port);
  2330. #else
  2331. auto port = 80;
  2332. Client cli(host, port);
  2333. #endif
  2334. cli.set_connection_timeout(std::chrono::seconds(5));
  2335. uint32_t count = 0;
  2336. auto res =
  2337. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2338. ASSERT_TRUE(!res);
  2339. EXPECT_EQ(Error::Canceled, res.error());
  2340. }
  2341. TEST(CancelTest, NoCancelPost) {
  2342. Server svr;
  2343. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2344. res.set_content("Hello World!", "text/plain");
  2345. });
  2346. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2347. auto se = detail::scope_exit([&] {
  2348. svr.stop();
  2349. thread.join();
  2350. ASSERT_FALSE(svr.is_running());
  2351. });
  2352. svr.wait_until_ready();
  2353. Client cli(HOST, PORT);
  2354. cli.set_connection_timeout(std::chrono::seconds(5));
  2355. auto res =
  2356. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2357. "application/json", [](uint64_t, uint64_t) { return true; });
  2358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2359. EXPECT_EQ("Hello World!", res->body);
  2360. EXPECT_EQ(StatusCode::OK_200, res->status);
  2361. }
  2362. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2363. Server svr;
  2364. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2365. res.set_content("Hello World!", "text/plain");
  2366. });
  2367. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2368. auto se = detail::scope_exit([&] {
  2369. svr.stop();
  2370. thread.join();
  2371. ASSERT_FALSE(svr.is_running());
  2372. });
  2373. svr.wait_until_ready();
  2374. Client cli(HOST, PORT);
  2375. cli.set_connection_timeout(std::chrono::seconds(5));
  2376. auto res =
  2377. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2378. "application/json", [](uint64_t, uint64_t) { return false; });
  2379. ASSERT_TRUE(!res);
  2380. EXPECT_EQ(Error::Canceled, res.error());
  2381. }
  2382. TEST(CancelTest, WithCancelLargePayloadPost) {
  2383. Server svr;
  2384. svr.set_payload_max_length(200 * 1024 * 1024);
  2385. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2386. res.set_content(LARGE_DATA, "text/plain");
  2387. });
  2388. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2389. auto se = detail::scope_exit([&] {
  2390. svr.stop();
  2391. thread.join();
  2392. ASSERT_FALSE(svr.is_running());
  2393. });
  2394. svr.wait_until_ready();
  2395. Client cli(HOST, PORT);
  2396. cli.set_payload_max_length(200 * 1024 * 1024);
  2397. cli.set_connection_timeout(std::chrono::seconds(5));
  2398. auto res =
  2399. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2400. "application/json", [](uint64_t, uint64_t) { return false; });
  2401. ASSERT_TRUE(!res);
  2402. EXPECT_EQ(Error::Canceled, res.error());
  2403. }
  2404. TEST(CancelTest, NoCancelPut) {
  2405. Server svr;
  2406. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2407. res.set_content("Hello World!", "text/plain");
  2408. });
  2409. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2410. auto se = detail::scope_exit([&] {
  2411. svr.stop();
  2412. thread.join();
  2413. ASSERT_FALSE(svr.is_running());
  2414. });
  2415. svr.wait_until_ready();
  2416. Client cli(HOST, PORT);
  2417. cli.set_connection_timeout(std::chrono::seconds(5));
  2418. auto res =
  2419. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2420. "application/json", [](uint64_t, uint64_t) { return true; });
  2421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2422. EXPECT_EQ("Hello World!", res->body);
  2423. EXPECT_EQ(StatusCode::OK_200, res->status);
  2424. }
  2425. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2426. Server svr;
  2427. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2428. res.set_content("Hello World!", "text/plain");
  2429. });
  2430. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2431. auto se = detail::scope_exit([&] {
  2432. svr.stop();
  2433. thread.join();
  2434. ASSERT_FALSE(svr.is_running());
  2435. });
  2436. svr.wait_until_ready();
  2437. Client cli(HOST, PORT);
  2438. cli.set_connection_timeout(std::chrono::seconds(5));
  2439. auto res =
  2440. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2441. "application/json", [](uint64_t, uint64_t) { return false; });
  2442. ASSERT_TRUE(!res);
  2443. EXPECT_EQ(Error::Canceled, res.error());
  2444. }
  2445. TEST(CancelTest, WithCancelLargePayloadPut) {
  2446. Server svr;
  2447. svr.set_payload_max_length(200 * 1024 * 1024);
  2448. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2449. res.set_content(LARGE_DATA, "text/plain");
  2450. });
  2451. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2452. auto se = detail::scope_exit([&] {
  2453. svr.stop();
  2454. thread.join();
  2455. ASSERT_FALSE(svr.is_running());
  2456. });
  2457. svr.wait_until_ready();
  2458. Client cli(HOST, PORT);
  2459. cli.set_payload_max_length(200 * 1024 * 1024);
  2460. cli.set_connection_timeout(std::chrono::seconds(5));
  2461. auto res =
  2462. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2463. "application/json", [](uint64_t, uint64_t) { return false; });
  2464. ASSERT_TRUE(!res);
  2465. EXPECT_EQ(Error::Canceled, res.error());
  2466. }
  2467. TEST(CancelTest, NoCancelPatch) {
  2468. Server svr;
  2469. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2470. res.set_content("Hello World!", "text/plain");
  2471. });
  2472. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2473. auto se = detail::scope_exit([&] {
  2474. svr.stop();
  2475. thread.join();
  2476. ASSERT_FALSE(svr.is_running());
  2477. });
  2478. svr.wait_until_ready();
  2479. Client cli(HOST, PORT);
  2480. cli.set_connection_timeout(std::chrono::seconds(5));
  2481. auto res =
  2482. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2483. "application/json", [](uint64_t, uint64_t) { return true; });
  2484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2485. EXPECT_EQ("Hello World!", res->body);
  2486. EXPECT_EQ(StatusCode::OK_200, res->status);
  2487. }
  2488. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2489. Server svr;
  2490. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2491. res.set_content("Hello World!", "text/plain");
  2492. });
  2493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2494. auto se = detail::scope_exit([&] {
  2495. svr.stop();
  2496. thread.join();
  2497. ASSERT_FALSE(svr.is_running());
  2498. });
  2499. svr.wait_until_ready();
  2500. Client cli(HOST, PORT);
  2501. cli.set_connection_timeout(std::chrono::seconds(5));
  2502. auto res =
  2503. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2504. "application/json", [](uint64_t, uint64_t) { return false; });
  2505. ASSERT_TRUE(!res);
  2506. EXPECT_EQ(Error::Canceled, res.error());
  2507. }
  2508. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2509. Server svr;
  2510. svr.set_payload_max_length(200 * 1024 * 1024);
  2511. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2512. res.set_content(LARGE_DATA, "text/plain");
  2513. });
  2514. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2515. auto se = detail::scope_exit([&] {
  2516. svr.stop();
  2517. thread.join();
  2518. ASSERT_FALSE(svr.is_running());
  2519. });
  2520. svr.wait_until_ready();
  2521. Client cli(HOST, PORT);
  2522. cli.set_payload_max_length(200 * 1024 * 1024);
  2523. cli.set_connection_timeout(std::chrono::seconds(5));
  2524. auto res =
  2525. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2526. "application/json", [](uint64_t, uint64_t) { return false; });
  2527. ASSERT_TRUE(!res);
  2528. EXPECT_EQ(Error::Canceled, res.error());
  2529. }
  2530. TEST(CancelTest, NoCancelDelete) {
  2531. Server svr;
  2532. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2533. res.set_content("Hello World!", "text/plain");
  2534. });
  2535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2536. auto se = detail::scope_exit([&] {
  2537. svr.stop();
  2538. thread.join();
  2539. ASSERT_FALSE(svr.is_running());
  2540. });
  2541. svr.wait_until_ready();
  2542. Client cli(HOST, PORT);
  2543. cli.set_connection_timeout(std::chrono::seconds(5));
  2544. auto res =
  2545. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2546. "application/json", [](uint64_t, uint64_t) { return true; });
  2547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2548. EXPECT_EQ("Hello World!", res->body);
  2549. EXPECT_EQ(StatusCode::OK_200, res->status);
  2550. }
  2551. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2552. Server svr;
  2553. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2554. res.set_content("Hello World!", "text/plain");
  2555. });
  2556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2557. auto se = detail::scope_exit([&] {
  2558. svr.stop();
  2559. thread.join();
  2560. ASSERT_FALSE(svr.is_running());
  2561. });
  2562. svr.wait_until_ready();
  2563. Client cli(HOST, PORT);
  2564. cli.set_connection_timeout(std::chrono::seconds(5));
  2565. auto res =
  2566. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2567. "application/json", [](uint64_t, uint64_t) { return false; });
  2568. ASSERT_TRUE(!res);
  2569. EXPECT_EQ(Error::Canceled, res.error());
  2570. }
  2571. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2572. Server svr;
  2573. svr.set_payload_max_length(200 * 1024 * 1024);
  2574. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2575. res.set_content(LARGE_DATA, "text/plain");
  2576. });
  2577. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2578. auto se = detail::scope_exit([&] {
  2579. svr.stop();
  2580. thread.join();
  2581. ASSERT_FALSE(svr.is_running());
  2582. });
  2583. svr.wait_until_ready();
  2584. Client cli(HOST, PORT);
  2585. cli.set_payload_max_length(200 * 1024 * 1024);
  2586. cli.set_connection_timeout(std::chrono::seconds(5));
  2587. auto res =
  2588. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2589. "application/json", [](uint64_t, uint64_t) { return false; });
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Canceled, res.error());
  2592. }
  2593. static std::string remove_whitespace(const std::string &input) {
  2594. std::string output;
  2595. output.reserve(input.size());
  2596. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2597. [](unsigned char c) { return !std::isspace(c); });
  2598. return output;
  2599. }
  2600. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2601. auto host = "httpbingo.org";
  2602. auto path = std::string{"/basic-auth/hello/world"};
  2603. #ifdef CPPHTTPLIB_SSL_ENABLED
  2604. auto port = 443;
  2605. SSLClient cli(host, port);
  2606. #else
  2607. auto port = 80;
  2608. Client cli(host, port);
  2609. #endif
  2610. {
  2611. auto res = cli.Get(path);
  2612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2613. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2614. }
  2615. {
  2616. auto res = cli.Get(
  2617. path, Headers{make_basic_authentication_header("hello", "world")});
  2618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2619. auto body = remove_whitespace(res->body);
  2620. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2621. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2622. EXPECT_EQ(StatusCode::OK_200, res->status);
  2623. }
  2624. {
  2625. cli.set_basic_auth("hello", "world");
  2626. auto res = cli.Get(path);
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. auto body = remove_whitespace(res->body);
  2629. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2630. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2631. EXPECT_EQ(StatusCode::OK_200, res->status);
  2632. }
  2633. {
  2634. cli.set_basic_auth("hello", "bad");
  2635. auto res = cli.Get(path);
  2636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2637. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2638. }
  2639. {
  2640. cli.set_basic_auth("bad", "world");
  2641. auto res = cli.Get(path);
  2642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2643. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2644. }
  2645. }
  2646. #ifdef CPPHTTPLIB_SSL_ENABLED
  2647. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2648. auto host = "httpbingo.org";
  2649. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2650. auto paths = std::vector<std::string>{
  2651. "/digest-auth/auth/hello/world/MD5",
  2652. "/digest-auth/auth/hello/world/SHA-256",
  2653. };
  2654. auto port = 443;
  2655. SSLClient cli(host, port);
  2656. {
  2657. auto res = cli.Get(unauth_path);
  2658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2659. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2660. }
  2661. {
  2662. cli.set_digest_auth("hello", "world");
  2663. for (const auto &path : paths) {
  2664. auto res = cli.Get(path.c_str());
  2665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2666. auto body = remove_whitespace(res->body);
  2667. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2668. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2669. EXPECT_EQ(StatusCode::OK_200, res->status);
  2670. }
  2671. cli.set_digest_auth("hello", "bad");
  2672. for (const auto &path : paths) {
  2673. auto res = cli.Get(path.c_str());
  2674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2675. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2676. }
  2677. }
  2678. }
  2679. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2680. // comma-separated list of challenges, and each challenge may itself carry a
  2681. // comma-separated auth-param list, so a server can legally offer Basic
  2682. // before Digest, either as two field lines or packed into one. Runs one 401
  2683. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2684. // value() joins them in receipt order) and checks that the retry carries a
  2685. // well-formed Digest Authorization header naming expected_realm.
  2686. static void
  2687. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2688. const std::string &expected_realm) {
  2689. std::atomic<int> hits{0};
  2690. Server svr;
  2691. svr.Get("/x", [&](const Request &req, Response &res) {
  2692. if (++hits == 1) {
  2693. res.status = StatusCode::Unauthorized_401;
  2694. for (const auto &challenge : challenges) {
  2695. res.set_header("WWW-Authenticate", challenge);
  2696. }
  2697. } else {
  2698. auto authorization = req.get_header_value("Authorization");
  2699. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2700. EXPECT_NE(std::string::npos,
  2701. authorization.find("realm=\"" + expected_realm + "\""));
  2702. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2703. res.set_content("ok", "text/plain");
  2704. }
  2705. });
  2706. auto port = svr.bind_to_any_port(HOST);
  2707. std::thread t([&]() { svr.listen_after_bind(); });
  2708. auto se = detail::scope_exit([&] {
  2709. svr.stop();
  2710. t.join();
  2711. });
  2712. svr.wait_until_ready();
  2713. Client cli(HOST, port);
  2714. cli.set_digest_auth("hello", "world");
  2715. auto res = cli.Get("/x");
  2716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2717. EXPECT_EQ(2, hits.load());
  2718. }
  2719. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2720. static const char *kDigestChallenge =
  2721. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2722. "algorithm=MD5";
  2723. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2724. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2725. "testrealm");
  2726. }
  2727. // Same challenge list with the schemes in the opposite order, to make sure
  2728. // the fix above didn't just special-case "Basic first".
  2729. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2730. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2731. "testrealm");
  2732. }
  2733. // A comma inside a quoted auth-param value must not be mistaken for the
  2734. // separator between two challenges (or two auth-params).
  2735. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2736. run_digest_challenge_list_test(
  2737. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2738. "algorithm=MD5"},
  2739. "test,realm");
  2740. }
  2741. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2742. // make_digest_authentication_header() dereferences both unconditionally, so
  2743. // a server sending a challenge missing either one must not be treated as
  2744. // usable -- doing so used to crash the client with std::out_of_range.
  2745. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2746. Server svr;
  2747. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2748. res.status = StatusCode::Unauthorized_401;
  2749. res.set_header("WWW-Authenticate", challenge);
  2750. });
  2751. auto port = svr.bind_to_any_port(HOST);
  2752. std::thread t([&]() { svr.listen_after_bind(); });
  2753. auto se = detail::scope_exit([&] {
  2754. svr.stop();
  2755. t.join();
  2756. });
  2757. svr.wait_until_ready();
  2758. Client cli(HOST, port);
  2759. cli.set_digest_auth("hello", "world");
  2760. auto res = cli.Get("/x");
  2761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2762. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2763. }
  2764. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2765. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2766. }
  2767. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2768. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2769. }
  2770. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2771. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2772. }
  2773. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2774. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2775. // when storing the values, so the header builder has to re-escape them (and
  2776. // keep algorithm a bare token); otherwise the value breaks out of its
  2777. // quoted-string and injects extra auth-params into the client's Authorization.
  2778. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2779. std::atomic<int> hits{0};
  2780. std::string authorization;
  2781. Server svr;
  2782. svr.Get("/x", [&](const Request &req, Response &res) {
  2783. if (++hits == 1) {
  2784. res.status = StatusCode::Unauthorized_401;
  2785. // On the wire the quotes embedded in the values are backslash-escaped.
  2786. res.set_header("WWW-Authenticate",
  2787. "Digest realm=\"testrealm\", "
  2788. "nonce=\"n\\\"; injected=\\\"x\", "
  2789. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2790. } else {
  2791. authorization = req.get_header_value("Authorization");
  2792. res.set_content("ok", "text/plain");
  2793. }
  2794. });
  2795. auto port = svr.bind_to_any_port(HOST);
  2796. std::thread t([&]() { svr.listen_after_bind(); });
  2797. auto se = detail::scope_exit([&] {
  2798. svr.stop();
  2799. t.join();
  2800. });
  2801. svr.wait_until_ready();
  2802. Client cli(HOST, port);
  2803. cli.set_digest_auth("hello", "world");
  2804. auto res = cli.Get("/x");
  2805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2806. EXPECT_EQ(2, hits.load());
  2807. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2808. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2809. // inside its quoted-string rather than starting an "injected" auth-param.
  2810. EXPECT_NE(std::string::npos,
  2811. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2812. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2813. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2814. }
  2815. #endif
  2816. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2817. auto host = "google.com";
  2818. auto another_host = "example.com";
  2819. auto wrong_ip = "0.0.0.0";
  2820. #ifdef CPPHTTPLIB_SSL_ENABLED
  2821. SSLClient cli(host);
  2822. #else
  2823. Client cli(host);
  2824. #endif
  2825. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2826. auto res = cli.Get("/");
  2827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2828. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2829. }
  2830. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2831. auto host = "google.com";
  2832. auto wrong_ip = "0.0.0.0";
  2833. #ifdef CPPHTTPLIB_SSL_ENABLED
  2834. SSLClient cli(host);
  2835. #else
  2836. Client cli(host);
  2837. #endif
  2838. cli.set_hostname_addr_map({{host, wrong_ip}});
  2839. auto res = cli.Get("/");
  2840. ASSERT_TRUE(!res);
  2841. EXPECT_EQ(Error::Connection, res.error());
  2842. }
  2843. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2844. // A mapped value that is not an IP literal must be resolved. "localhost"
  2845. // resolves from the hosts file, so this test needs no external DNS.
  2846. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2847. auto host = "target.invalid";
  2848. Server svr;
  2849. std::string received_host;
  2850. svr.Get("/hi", [&](const Request &req, Response &res) {
  2851. received_host = req.get_header_value("Host");
  2852. res.set_content("Hello World!", "text/plain");
  2853. });
  2854. auto port = svr.bind_to_any_port(HOST);
  2855. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2856. auto se = detail::scope_exit([&] {
  2857. svr.stop();
  2858. thread.join();
  2859. ASSERT_FALSE(svr.is_running());
  2860. });
  2861. svr.wait_until_ready();
  2862. Client cli(host, port);
  2863. cli.set_hostname_addr_map({{host, HOST}});
  2864. auto res = cli.Get("/hi");
  2865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2866. EXPECT_EQ(StatusCode::OK_200, res->status);
  2867. // The mapping only redirects the connection; the identity stays host_.
  2868. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2869. }
  2870. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2871. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2872. auto host = "target.invalid";
  2873. Server svr;
  2874. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2875. res.set_content("Hello World!", "text/plain");
  2876. });
  2877. auto port = svr.bind_to_any_port("127.0.0.1");
  2878. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2879. auto se = detail::scope_exit([&] {
  2880. svr.stop();
  2881. thread.join();
  2882. ASSERT_FALSE(svr.is_running());
  2883. });
  2884. svr.wait_until_ready();
  2885. Client cli(host, port);
  2886. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2887. auto res = cli.Get("/hi");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2892. // An empty mapped value must leave host_ as the connection target. Without
  2893. // that guard the empty value would become the host argument, getaddrinfo
  2894. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2895. // loopback - silently connecting somewhere the caller never asked for.
  2896. // The server listens on loopback, so such a fallback would succeed and is
  2897. // therefore observable as a failure of this test.
  2898. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2899. Server svr;
  2900. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2901. res.set_content("Hello World!", "text/plain");
  2902. });
  2903. auto port = svr.bind_to_any_port(HOST);
  2904. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2905. auto se = detail::scope_exit([&] {
  2906. svr.stop();
  2907. thread.join();
  2908. ASSERT_FALSE(svr.is_running());
  2909. });
  2910. svr.wait_until_ready();
  2911. Client cli(blackhole, port);
  2912. cli.set_hostname_addr_map({{blackhole, ""}});
  2913. cli.set_connection_timeout(1);
  2914. auto res = cli.Get("/hi");
  2915. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2916. }
  2917. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2918. auto host = "httpbingo.org";
  2919. auto path = std::string{"/absolute-redirect/3"};
  2920. #ifdef CPPHTTPLIB_SSL_ENABLED
  2921. SSLClient cli(host);
  2922. #else
  2923. Client cli(host);
  2924. #endif
  2925. cli.set_follow_location(true);
  2926. auto res = cli.Get(path);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::OK_200, res->status);
  2929. }
  2930. TEST(RedirectTest, Redirect_Online) {
  2931. auto host = "httpbingo.org";
  2932. auto path = std::string{"/redirect/3"};
  2933. #ifdef CPPHTTPLIB_SSL_ENABLED
  2934. SSLClient cli(host);
  2935. #else
  2936. Client cli(host);
  2937. #endif
  2938. cli.set_follow_location(true);
  2939. auto res = cli.Get(path);
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(RelativeRedirectTest, Redirect_Online) {
  2944. auto host = "httpbingo.org";
  2945. auto path = std::string{"/relative-redirect/3"};
  2946. #ifdef CPPHTTPLIB_SSL_ENABLED
  2947. SSLClient cli(host);
  2948. #else
  2949. Client cli(host);
  2950. #endif
  2951. cli.set_follow_location(true);
  2952. auto res = cli.Get(path);
  2953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2954. EXPECT_EQ(StatusCode::OK_200, res->status);
  2955. }
  2956. TEST(TooManyRedirectTest, Redirect_Online) {
  2957. auto host = "httpbingo.org";
  2958. auto path = std::string{"/redirect/21"};
  2959. #ifdef CPPHTTPLIB_SSL_ENABLED
  2960. SSLClient cli(host);
  2961. #else
  2962. Client cli(host);
  2963. #endif
  2964. cli.set_follow_location(true);
  2965. auto res = cli.Get(path);
  2966. ASSERT_TRUE(!res);
  2967. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2968. }
  2969. #ifdef CPPHTTPLIB_SSL_ENABLED
  2970. TEST(YahooRedirectTest, Redirect_Online) {
  2971. Client cli("yahoo.com");
  2972. auto res = cli.Get("/");
  2973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2974. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2975. cli.set_follow_location(true);
  2976. res = cli.Get("/");
  2977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2978. EXPECT_EQ(StatusCode::OK_200, res->status);
  2979. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2980. }
  2981. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2982. #define REDIR_HOST "httpbingo.org"
  2983. #define REDIR_PATH "/redirect-to"
  2984. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2985. SSLClient cli(REDIR_HOST);
  2986. cli.set_follow_location(true);
  2987. auto res =
  2988. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2990. EXPECT_EQ(StatusCode::OK_200, res->status);
  2991. }
  2992. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2993. SSLClient cli(REDIR_HOST);
  2994. cli.set_follow_location(true);
  2995. Params params;
  2996. params.emplace("url", "http://example.com");
  2997. params.emplace("status_code", "302");
  2998. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3000. EXPECT_EQ(StatusCode::OK_200, res->status);
  3001. }
  3002. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3003. SSLClient cli(REDIR_HOST);
  3004. cli.set_follow_location(true);
  3005. Params params;
  3006. params.emplace("url", "http://example.com");
  3007. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3009. EXPECT_EQ(StatusCode::OK_200, res->status);
  3010. }
  3011. TEST(UrlWithSpace, Redirect_Online) {
  3012. SSLClient cli("edge.forgecdn.net");
  3013. cli.set_follow_location(true);
  3014. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3016. EXPECT_EQ(StatusCode::OK_200, res->status);
  3017. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3018. }
  3019. #endif
  3020. #if !defined(_WIN32) && !defined(_WIN64)
  3021. TEST(ReceiveSignals, Signal) {
  3022. auto setupSignalHandlers = []() {
  3023. struct sigaction act;
  3024. sigemptyset(&act.sa_mask);
  3025. act.sa_flags = SA_SIGINFO;
  3026. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3027. switch (sig) {
  3028. case SIGINT:
  3029. default: break;
  3030. }
  3031. };
  3032. ::sigaction(SIGINT, &act, nullptr);
  3033. };
  3034. Server svr;
  3035. int port = 0;
  3036. auto thread = std::thread([&]() {
  3037. setupSignalHandlers();
  3038. port = svr.bind_to_any_port(HOST);
  3039. svr.listen_after_bind();
  3040. });
  3041. auto se = detail::scope_exit([&] {
  3042. svr.stop();
  3043. thread.join();
  3044. ASSERT_FALSE(svr.is_running());
  3045. });
  3046. svr.wait_until_ready();
  3047. ASSERT_TRUE(svr.is_running());
  3048. pthread_kill(thread.native_handle(), SIGINT);
  3049. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3050. ASSERT_TRUE(svr.is_running());
  3051. }
  3052. #endif
  3053. TEST(RedirectToDifferentPort, Redirect) {
  3054. Server svr1;
  3055. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3056. res.set_content("Hello World!", "text/plain");
  3057. });
  3058. int svr1_port = 0;
  3059. auto thread1 = std::thread([&]() {
  3060. svr1_port = svr1.bind_to_any_port(HOST);
  3061. svr1.listen_after_bind();
  3062. });
  3063. Server svr2;
  3064. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3065. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3066. });
  3067. int svr2_port = 0;
  3068. auto thread2 = std::thread([&]() {
  3069. svr2_port = svr2.bind_to_any_port(HOST);
  3070. svr2.listen_after_bind();
  3071. });
  3072. auto se = detail::scope_exit([&] {
  3073. svr2.stop();
  3074. thread2.join();
  3075. svr1.stop();
  3076. thread1.join();
  3077. ASSERT_FALSE(svr2.is_running());
  3078. ASSERT_FALSE(svr1.is_running());
  3079. });
  3080. svr1.wait_until_ready();
  3081. svr2.wait_until_ready();
  3082. Client cli("localhost", svr2_port);
  3083. cli.set_follow_location(true);
  3084. auto res = cli.Get("/2");
  3085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3086. EXPECT_EQ(StatusCode::OK_200, res->status);
  3087. EXPECT_EQ("Hello World!", res->body);
  3088. }
  3089. static void
  3090. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3091. Server svr1;
  3092. std::string captured_authorization;
  3093. svr1.Get("/target", [&](const Request &req, Response &res) {
  3094. captured_authorization = req.get_header_value("Authorization");
  3095. res.set_content("OK", "text/plain");
  3096. });
  3097. int svr1_port = 0;
  3098. auto thread1 = std::thread([&]() {
  3099. svr1_port = svr1.bind_to_any_port(HOST);
  3100. svr1.listen_after_bind();
  3101. });
  3102. Server svr2;
  3103. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3104. res.set_redirect(
  3105. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3106. });
  3107. int svr2_port = 0;
  3108. auto thread2 = std::thread([&]() {
  3109. svr2_port = svr2.bind_to_any_port(HOST);
  3110. svr2.listen_after_bind();
  3111. });
  3112. auto se = detail::scope_exit([&] {
  3113. svr2.stop();
  3114. thread2.join();
  3115. svr1.stop();
  3116. thread1.join();
  3117. ASSERT_FALSE(svr2.is_running());
  3118. ASSERT_FALSE(svr1.is_running());
  3119. });
  3120. svr1.wait_until_ready();
  3121. svr2.wait_until_ready();
  3122. Client cli("localhost", svr2_port);
  3123. cli.set_follow_location(true);
  3124. set_auth(cli);
  3125. auto res = cli.Get("/redir");
  3126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3127. EXPECT_EQ(StatusCode::OK_200, res->status);
  3128. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3129. EXPECT_TRUE(captured_authorization.empty());
  3130. }
  3131. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3132. TestDoNotForwardCredentialsOnRedirect(
  3133. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3134. }
  3135. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3136. TestDoNotForwardCredentialsOnRedirect(
  3137. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3138. }
  3139. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3140. Server svr1;
  3141. std::string captured_cookie;
  3142. bool target_hit = false;
  3143. svr1.Get("/target", [&](const Request &req, Response &res) {
  3144. captured_cookie = req.get_header_value("Cookie");
  3145. target_hit = true;
  3146. res.set_content("OK", "text/plain");
  3147. });
  3148. int svr1_port = 0;
  3149. auto thread1 = std::thread([&]() {
  3150. svr1_port = svr1.bind_to_any_port(HOST);
  3151. svr1.listen_after_bind();
  3152. });
  3153. Server svr2;
  3154. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3155. res.set_redirect(
  3156. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3157. });
  3158. int svr2_port = 0;
  3159. auto thread2 = std::thread([&]() {
  3160. svr2_port = svr2.bind_to_any_port(HOST);
  3161. svr2.listen_after_bind();
  3162. });
  3163. auto se = detail::scope_exit([&] {
  3164. svr2.stop();
  3165. thread2.join();
  3166. svr1.stop();
  3167. thread1.join();
  3168. ASSERT_FALSE(svr2.is_running());
  3169. ASSERT_FALSE(svr1.is_running());
  3170. });
  3171. svr1.wait_until_ready();
  3172. svr2.wait_until_ready();
  3173. Client cli("localhost", svr2_port);
  3174. cli.set_follow_location(true);
  3175. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3176. auto res = cli.Get("/redir", headers);
  3177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3178. EXPECT_EQ(StatusCode::OK_200, res->status);
  3179. EXPECT_TRUE(target_hit);
  3180. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3181. EXPECT_TRUE(captured_cookie.empty());
  3182. }
  3183. TEST(RedirectToSamePort, ForwardCookie) {
  3184. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3185. // header so that ordinary session flows keep working.
  3186. Server svr;
  3187. std::string captured_cookie;
  3188. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3189. res.set_redirect("/target", 302);
  3190. });
  3191. svr.Get("/target", [&](const Request &req, Response &res) {
  3192. captured_cookie = req.get_header_value("Cookie");
  3193. res.set_content("OK", "text/plain");
  3194. });
  3195. auto port = svr.bind_to_any_port(HOST);
  3196. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3197. auto se = detail::scope_exit([&] {
  3198. svr.stop();
  3199. thread.join();
  3200. ASSERT_FALSE(svr.is_running());
  3201. });
  3202. svr.wait_until_ready();
  3203. Client cli(HOST, port);
  3204. cli.set_follow_location(true);
  3205. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3206. auto res = cli.Get("/redir", headers);
  3207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3208. EXPECT_EQ(StatusCode::OK_200, res->status);
  3209. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3210. }
  3211. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3212. Server svr;
  3213. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3214. // Port number that overflows int — should not crash
  3215. res.set_redirect("http://localhost:99999999999999999999/target");
  3216. });
  3217. auto port = svr.bind_to_any_port(HOST);
  3218. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3219. auto se = detail::scope_exit([&] {
  3220. svr.stop();
  3221. thread.join();
  3222. ASSERT_FALSE(svr.is_running());
  3223. });
  3224. svr.wait_until_ready();
  3225. Client cli(HOST, port);
  3226. cli.set_follow_location(true);
  3227. auto res = cli.Get("/redir");
  3228. // Should fail gracefully, not crash (no valid response due to bad port)
  3229. EXPECT_FALSE(res);
  3230. }
  3231. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3232. Server svr;
  3233. auto port = svr.bind_to_any_port(HOST);
  3234. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3235. // The server's own port followed by junk must not be followed
  3236. res.set_redirect("http://" + std::string(HOST) + ":" +
  3237. std::to_string(port) + "junk/target");
  3238. });
  3239. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3240. res.set_content("target", "text/plain");
  3241. });
  3242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3243. auto se = detail::scope_exit([&] {
  3244. svr.stop();
  3245. thread.join();
  3246. ASSERT_FALSE(svr.is_running());
  3247. });
  3248. svr.wait_until_ready();
  3249. Client cli(HOST, port);
  3250. cli.set_follow_location(true);
  3251. auto res = cli.Get("/redir");
  3252. EXPECT_FALSE(res);
  3253. }
  3254. TEST(RedirectFromPageWithContent, Redirect) {
  3255. Server svr;
  3256. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3257. res.set_content("___", "text/plain");
  3258. res.set_redirect("/2");
  3259. });
  3260. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3261. res.set_content("Hello World!", "text/plain");
  3262. });
  3263. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3264. auto se = detail::scope_exit([&] {
  3265. svr.stop();
  3266. th.join();
  3267. ASSERT_FALSE(svr.is_running());
  3268. });
  3269. svr.wait_until_ready();
  3270. {
  3271. Client cli("localhost", PORT);
  3272. cli.set_follow_location(true);
  3273. std::string body;
  3274. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3275. body.append(data, data_length);
  3276. return true;
  3277. });
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. EXPECT_EQ(StatusCode::OK_200, res->status);
  3280. EXPECT_EQ("Hello World!", body);
  3281. }
  3282. {
  3283. Client cli("localhost", PORT);
  3284. std::string body;
  3285. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3286. body.append(data, data_length);
  3287. return true;
  3288. });
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::Found_302, res->status);
  3291. EXPECT_EQ("___", body);
  3292. }
  3293. }
  3294. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3295. Server svr;
  3296. auto port_str = std::to_string(PORT);
  3297. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3298. auto expected_host = "[::1]:" + port_str;
  3299. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3300. res.set_content("___", "text/plain");
  3301. // res.set_redirect("/2");
  3302. res.set_redirect(redirect_url);
  3303. });
  3304. svr.Get("/2", [&](const Request &req, Response &res) {
  3305. auto host_header = req.headers.find("Host");
  3306. ASSERT_TRUE(host_header != req.headers.end());
  3307. EXPECT_EQ(expected_host, host_header->second);
  3308. res.set_content("Hello World!", "text/plain");
  3309. });
  3310. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. th.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3317. // actually starts anything, so the condition !svr.is_running() will
  3318. // always remain true, and the loop never stops.
  3319. // This basically counts how many milliseconds have passed since the
  3320. // call to svr.listen(), and if after 5 seconds nothing started yet
  3321. // aborts the test.
  3322. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3323. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3324. ASSERT_LT(milliseconds, 5000U);
  3325. }
  3326. {
  3327. Client cli("::1", PORT);
  3328. cli.set_follow_location(true);
  3329. std::string body;
  3330. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3331. body.append(data, data_length);
  3332. return true;
  3333. });
  3334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3335. EXPECT_EQ(StatusCode::OK_200, res->status);
  3336. EXPECT_EQ("Hello World!", body);
  3337. }
  3338. {
  3339. Client cli("::1", PORT);
  3340. std::string body;
  3341. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3342. body.append(data, data_length);
  3343. return true;
  3344. });
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::Found_302, res->status);
  3347. EXPECT_EQ("___", body);
  3348. }
  3349. }
  3350. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3351. Server svr;
  3352. svr.Get("/foo", [](const Request &req, Response &res) {
  3353. auto a = req.params.find("a");
  3354. if (a != req.params.end()) {
  3355. res.set_content((*a).second, "text/plain");
  3356. res.status = StatusCode::OK_200;
  3357. } else {
  3358. res.status = StatusCode::BadRequest_400;
  3359. }
  3360. });
  3361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3362. auto se = detail::scope_exit([&] {
  3363. svr.stop();
  3364. thread.join();
  3365. ASSERT_FALSE(svr.is_running());
  3366. });
  3367. svr.wait_until_ready();
  3368. {
  3369. Client cli(HOST, PORT);
  3370. cli.set_path_encode(false);
  3371. auto res = cli.Get("/foo?a=explicitly+encoded");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(StatusCode::OK_200, res->status);
  3374. // This expects it back with a space, as the `+` won't have been
  3375. // url-encoded, and server-side the params get decoded turning `+`
  3376. // into spaces.
  3377. EXPECT_EQ("explicitly encoded", res->body);
  3378. }
  3379. }
  3380. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3381. // When path encoding is disabled the client must transmit the supplied
  3382. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3383. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3384. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3385. // than a space (0x20). Assert on the raw wire target to catch this.
  3386. Server svr;
  3387. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3388. svr.Get("/foo", [&](const Request &req, Response &res) {
  3389. EXPECT_EQ(expected_target, req.target);
  3390. res.status = StatusCode::OK_200;
  3391. });
  3392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3393. auto se = detail::scope_exit([&] {
  3394. svr.stop();
  3395. thread.join();
  3396. ASSERT_FALSE(svr.is_running());
  3397. });
  3398. svr.wait_until_ready();
  3399. {
  3400. Client cli(HOST, PORT);
  3401. cli.set_path_encode(false);
  3402. auto res = cli.Get(expected_target.c_str());
  3403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3404. EXPECT_EQ(StatusCode::OK_200, res->status);
  3405. }
  3406. }
  3407. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3408. // `open_stream()` used to skip the path encoding that the buffered send
  3409. // path applies, so the same `path` produced different bytes in the request
  3410. // line depending on which API was used. Assert the two agree.
  3411. Server svr;
  3412. std::string target;
  3413. svr.Get(".*", [&](const Request &req, Response &res) {
  3414. target = req.target;
  3415. res.status = StatusCode::OK_200;
  3416. });
  3417. auto port = svr.bind_to_any_port(HOST);
  3418. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3419. auto se = detail::scope_exit([&] {
  3420. svr.stop();
  3421. thread.join();
  3422. ASSERT_FALSE(svr.is_running());
  3423. });
  3424. svr.wait_until_ready();
  3425. struct {
  3426. const char *path;
  3427. const char *expected;
  3428. } cases[] = {
  3429. {"/a b?x=1", "/a%20b?x=1"},
  3430. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3431. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3432. };
  3433. for (const auto &c : cases) {
  3434. Client cli(HOST, port);
  3435. target.clear();
  3436. auto res = cli.Get(c.path);
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3439. auto buffered_target = target;
  3440. target.clear();
  3441. auto handle = cli.open_stream("GET", c.path);
  3442. EXPECT_TRUE(handle.is_valid())
  3443. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3444. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3445. }
  3446. }
  3447. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3448. // The `set_path_encode(false)` contract — transmit the supplied target
  3449. // verbatim — must hold for the streaming API too.
  3450. Server svr;
  3451. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3452. std::string target;
  3453. svr.Get("/foo", [&](const Request &req, Response &res) {
  3454. target = req.target;
  3455. res.status = StatusCode::OK_200;
  3456. });
  3457. auto port = svr.bind_to_any_port(HOST);
  3458. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3459. auto se = detail::scope_exit([&] {
  3460. svr.stop();
  3461. thread.join();
  3462. ASSERT_FALSE(svr.is_running());
  3463. });
  3464. svr.wait_until_ready();
  3465. {
  3466. Client cli(HOST, port);
  3467. cli.set_path_encode(false);
  3468. auto handle = cli.open_stream("GET", expected_target);
  3469. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3470. EXPECT_EQ(expected_target, target);
  3471. }
  3472. }
  3473. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3474. // With path encoding enabled a CR/LF in the target is percent-encoded
  3475. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3476. // write_request_line still backstops `set_path_encode(false)`, which is
  3477. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3478. Server svr;
  3479. // Captured before routing: the decoded path contains a newline, which a
  3480. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3481. std::string target;
  3482. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3483. target = req.target;
  3484. res.status = StatusCode::OK_200;
  3485. return Server::HandlerResponse::Handled;
  3486. });
  3487. auto port = svr.bind_to_any_port(HOST);
  3488. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3489. auto se = detail::scope_exit([&] {
  3490. svr.stop();
  3491. thread.join();
  3492. ASSERT_FALSE(svr.is_running());
  3493. });
  3494. svr.wait_until_ready();
  3495. {
  3496. Client cli(HOST, port);
  3497. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3498. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3499. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3500. }
  3501. }
  3502. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3503. // Every control character is percent-encoded, not just CR/LF, so the target
  3504. // passes the request-target check in write_request_line.
  3505. Server svr;
  3506. std::string target;
  3507. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3508. target = req.target;
  3509. res.status = StatusCode::OK_200;
  3510. return Server::HandlerResponse::Handled;
  3511. });
  3512. auto port = svr.bind_to_any_port(HOST);
  3513. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3514. auto se = detail::scope_exit([&] {
  3515. svr.stop();
  3516. thread.join();
  3517. ASSERT_FALSE(svr.is_running());
  3518. });
  3519. svr.wait_until_ready();
  3520. {
  3521. Client cli(HOST, port);
  3522. auto res = cli.Get("/a\tb\x1b\x7f");
  3523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3524. EXPECT_EQ("/a%09b%1B%7F", target);
  3525. }
  3526. }
  3527. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3528. // Nothing may reach the wire: a raw CR/LF target would split the request
  3529. // line and inject headers.
  3530. Server svr;
  3531. // Pre-routing so that "not called" means nothing reached the server at all,
  3532. // rather than merely failing to match a handler pattern.
  3533. auto handler_called = false;
  3534. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3535. handler_called = true;
  3536. res.status = StatusCode::OK_200;
  3537. return Server::HandlerResponse::Handled;
  3538. });
  3539. auto port = svr.bind_to_any_port(HOST);
  3540. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3541. auto se = detail::scope_exit([&] {
  3542. svr.stop();
  3543. thread.join();
  3544. ASSERT_FALSE(svr.is_running());
  3545. });
  3546. svr.wait_until_ready();
  3547. {
  3548. Client cli(HOST, port);
  3549. cli.set_path_encode(false);
  3550. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3551. EXPECT_FALSE(handle.is_valid());
  3552. EXPECT_EQ(Error::Write, handle.error);
  3553. EXPECT_FALSE(handler_called);
  3554. }
  3555. }
  3556. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3557. // Which of the two branches runs is decided by whether the query component
  3558. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3559. // an empty query and must still fall back to building one from
  3560. // `req.params`, while a non-empty query must win over `req.params`.
  3561. Server svr;
  3562. std::string target;
  3563. svr.Get("/foo", [&](const Request &req, Response &res) {
  3564. target = req.target;
  3565. res.status = StatusCode::OK_200;
  3566. });
  3567. auto port = svr.bind_to_any_port(HOST);
  3568. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3569. auto se = detail::scope_exit([&] {
  3570. svr.stop();
  3571. thread.join();
  3572. ASSERT_FALSE(svr.is_running());
  3573. });
  3574. svr.wait_until_ready();
  3575. {
  3576. // Trailing `?` -> empty query component -> `req.params` is used.
  3577. Client cli(HOST, port);
  3578. Request req;
  3579. req.method = "GET";
  3580. req.path = "/foo?";
  3581. req.params.emplace("a", "1");
  3582. target.clear();
  3583. auto res = cli.send(req);
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ("/foo?a=1", target);
  3586. }
  3587. {
  3588. // Non-empty query in `req.path` -> `req.params` is not appended.
  3589. Client cli(HOST, port);
  3590. Request req;
  3591. req.method = "GET";
  3592. req.path = "/foo?b=2";
  3593. req.params.emplace("a", "1");
  3594. target.clear();
  3595. auto res = cli.send(req);
  3596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3597. EXPECT_EQ("/foo?b=2", target);
  3598. }
  3599. }
  3600. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3601. Server svr;
  3602. svr.Get("/", [](const Request &req, Response &) {
  3603. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3604. });
  3605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. {
  3613. Client cli(HOST, PORT);
  3614. cli.set_path_encode(false);
  3615. auto res = cli.Get("/?something=%0A");
  3616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3617. EXPECT_EQ(StatusCode::OK_200, res->status);
  3618. }
  3619. }
  3620. TEST(BindServerTest, BindDualStack) {
  3621. Server svr;
  3622. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3623. res.set_content("Hello World!", "text/plain");
  3624. });
  3625. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3626. auto se = detail::scope_exit([&] {
  3627. svr.stop();
  3628. thread.join();
  3629. ASSERT_FALSE(svr.is_running());
  3630. });
  3631. svr.wait_until_ready();
  3632. {
  3633. Client cli("127.0.0.1", PORT);
  3634. auto res = cli.Get("/1");
  3635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3636. EXPECT_EQ(StatusCode::OK_200, res->status);
  3637. EXPECT_EQ("Hello World!", res->body);
  3638. }
  3639. {
  3640. Client cli("::1", PORT);
  3641. auto res = cli.Get("/1");
  3642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3643. EXPECT_EQ(StatusCode::OK_200, res->status);
  3644. EXPECT_EQ("Hello World!", res->body);
  3645. }
  3646. }
  3647. TEST(BindServerTest, BindAndListenSeparately) {
  3648. Server svr;
  3649. int port = svr.bind_to_any_port("0.0.0.0");
  3650. ASSERT_TRUE(svr.is_valid());
  3651. ASSERT_TRUE(port > 0);
  3652. svr.stop();
  3653. }
  3654. // Reports whether anything is still listening on a loopback port. A plain
  3655. // connect() is used instead of a Client request because a socket left bound by
  3656. // mistake accepts the connection into its backlog and never answers, which
  3657. // would hang the test instead of failing it.
  3658. static bool is_loopback_port_accepting(int port) {
  3659. sockaddr_in addr{};
  3660. addr.sin_family = AF_INET;
  3661. addr.sin_port = htons(static_cast<uint16_t>(port));
  3662. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3663. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3664. EXPECT_NE(sock, INVALID_SOCKET);
  3665. if (sock == INVALID_SOCKET) { return false; }
  3666. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3667. static_cast<socklen_t>(sizeof(addr)));
  3668. detail::close_socket(sock);
  3669. return ret == 0;
  3670. }
  3671. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3672. Server svr;
  3673. auto port = svr.bind_to_any_port("127.0.0.1");
  3674. ASSERT_TRUE(port > 0);
  3675. svr.stop();
  3676. // bind_to_any_port() already called listen(2), so until stop() closed the
  3677. // descriptor the port kept accepting connections into the backlog. ASSERT
  3678. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3679. // below blocks forever in the accept loop.
  3680. ASSERT_FALSE(is_loopback_port_accepting(port));
  3681. // Nothing is left to accept on, so listen_after_bind() must report failure
  3682. // instead of returning success without ever serving.
  3683. EXPECT_FALSE(svr.listen_after_bind());
  3684. // The failed listen marks the server decommissioned, so a waiter returns
  3685. // instead of spinning forever.
  3686. svr.wait_until_ready();
  3687. }
  3688. #ifdef CPPHTTPLIB_SSL_ENABLED
  3689. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3690. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3691. CLIENT_CA_CERT_DIR);
  3692. int port = svr.bind_to_any_port("0.0.0.0");
  3693. ASSERT_TRUE(svr.is_valid());
  3694. ASSERT_TRUE(port > 0);
  3695. svr.stop();
  3696. }
  3697. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3698. // or a rejected CustomRoute() registration would not stop the server binding.
  3699. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3701. CLIENT_CA_CERT_DIR);
  3702. ASSERT_TRUE(svr.is_valid());
  3703. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3704. EXPECT_FALSE(svr.is_valid());
  3705. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3706. }
  3707. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3708. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3709. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3710. int port = svr.bind_to_any_port("0.0.0.0");
  3711. ASSERT_TRUE(svr.is_valid());
  3712. ASSERT_TRUE(port > 0);
  3713. svr.stop();
  3714. }
  3715. TEST(BindServerTest, UpdateCertsPem) {
  3716. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3717. int port = svr.bind_to_any_port("0.0.0.0");
  3718. ASSERT_TRUE(svr.is_valid());
  3719. ASSERT_TRUE(port > 0);
  3720. // Read PEM files
  3721. std::string cert_pem, key_pem, ca_pem;
  3722. read_file(SERVER_CERT_FILE, cert_pem);
  3723. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3724. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3725. // Update server certificates using PEM API
  3726. ASSERT_TRUE(
  3727. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3728. ASSERT_TRUE(svr.is_valid());
  3729. svr.stop();
  3730. }
  3731. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3732. // Start server with client CA (enables client auth)
  3733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3734. ASSERT_TRUE(svr.is_valid());
  3735. bool handler_called = false;
  3736. svr.Get("/test", [&](const Request &req, Response &res) {
  3737. handler_called = true;
  3738. // Verify client certificate is present
  3739. auto cert = req.peer_cert();
  3740. EXPECT_TRUE(static_cast<bool>(cert));
  3741. res.set_content("ok", "text/plain");
  3742. });
  3743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3744. auto se = detail::scope_exit([&] {
  3745. svr.stop();
  3746. t.join();
  3747. ASSERT_FALSE(svr.is_running());
  3748. });
  3749. svr.wait_until_ready();
  3750. // Read PEM files
  3751. std::string cert_pem, key_pem, ca_pem;
  3752. read_file(SERVER_CERT_FILE, cert_pem);
  3753. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3754. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3755. // Update server certificates and client CA using PEM API while server running
  3756. ASSERT_TRUE(
  3757. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3758. // Connect with client certificate
  3759. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3760. cli.enable_server_certificate_verification(false);
  3761. cli.set_connection_timeout(30);
  3762. auto res = cli.Get("/test");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. ASSERT_EQ(StatusCode::OK_200, res->status);
  3765. ASSERT_TRUE(handler_called);
  3766. EXPECT_EQ("ok", res->body);
  3767. }
  3768. #endif
  3769. TEST(ErrorHandlerTest, ContentLength) {
  3770. Server svr;
  3771. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3772. res.status = StatusCode::OK_200;
  3773. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3774. "text/html"); // <= Content-Length still 13
  3775. });
  3776. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3777. res.set_content("Hello World!\n", "text/plain");
  3778. res.status = 524;
  3779. });
  3780. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3781. auto se = detail::scope_exit([&] {
  3782. svr.stop();
  3783. thread.join();
  3784. ASSERT_FALSE(svr.is_running());
  3785. });
  3786. svr.wait_until_ready();
  3787. {
  3788. Client cli(HOST, PORT);
  3789. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3791. EXPECT_EQ(StatusCode::OK_200, res->status);
  3792. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3793. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3794. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3795. }
  3796. }
  3797. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3798. TEST(ExceptionTest, WithoutExceptionHandler) {
  3799. Server svr;
  3800. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3801. throw std::runtime_error("exception...");
  3802. });
  3803. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3804. throw std::runtime_error("exception\r\n...");
  3805. });
  3806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3807. auto se = detail::scope_exit([&] {
  3808. svr.stop();
  3809. listen_thread.join();
  3810. ASSERT_FALSE(svr.is_running());
  3811. });
  3812. svr.wait_until_ready();
  3813. Client cli("localhost", PORT);
  3814. {
  3815. auto res = cli.Get("/exception");
  3816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3817. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3818. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3819. }
  3820. {
  3821. auto res = cli.Get("/unknown");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3824. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3825. }
  3826. }
  3827. TEST(ExceptionTest, WithExceptionHandler) {
  3828. Server svr;
  3829. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3830. std::exception_ptr ep) {
  3831. EXPECT_FALSE(ep == nullptr);
  3832. try {
  3833. std::rethrow_exception(ep);
  3834. } catch (std::exception &e) {
  3835. EXPECT_EQ("abc", std::string(e.what()));
  3836. } catch (...) {}
  3837. res.status = StatusCode::InternalServerError_500;
  3838. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3839. "text/html"); // <= Content-Length still 13 at this point
  3840. });
  3841. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3842. res.set_content("Hello World!\n", "text/plain");
  3843. throw std::runtime_error("abc");
  3844. });
  3845. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3846. auto se = detail::scope_exit([&] {
  3847. svr.stop();
  3848. thread.join();
  3849. ASSERT_FALSE(svr.is_running());
  3850. });
  3851. svr.wait_until_ready();
  3852. for (size_t i = 0; i < 10; i++) {
  3853. Client cli(HOST, PORT);
  3854. for (size_t j = 0; j < 100; j++) {
  3855. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3857. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3858. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3859. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3860. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3861. }
  3862. cli.set_keep_alive(true);
  3863. for (size_t j = 0; j < 100; j++) {
  3864. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3866. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3867. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3868. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3869. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3870. }
  3871. }
  3872. }
  3873. TEST(ExceptionTest, AndErrorHandler) {
  3874. Server svr;
  3875. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3876. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3877. });
  3878. svr.set_exception_handler(
  3879. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3880. EXPECT_FALSE(ep == nullptr);
  3881. try {
  3882. std::rethrow_exception(ep);
  3883. } catch (std::exception &e) {
  3884. res.set_content(e.what(), "text/html");
  3885. } catch (...) {}
  3886. res.status = StatusCode::InternalServerError_500;
  3887. });
  3888. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3889. throw std::runtime_error("EXCEPTION");
  3890. });
  3891. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3892. res.set_content("ERROR", "text/html");
  3893. res.status = StatusCode::InternalServerError_500;
  3894. });
  3895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3896. auto se = detail::scope_exit([&] {
  3897. svr.stop();
  3898. thread.join();
  3899. ASSERT_FALSE(svr.is_running());
  3900. });
  3901. svr.wait_until_ready();
  3902. Client cli(HOST, PORT);
  3903. {
  3904. auto res = cli.Get("/exception");
  3905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3906. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3907. EXPECT_EQ("EXCEPTION", res->body);
  3908. }
  3909. {
  3910. auto res = cli.Get("/error");
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3913. EXPECT_EQ("ERROR", res->body);
  3914. }
  3915. {
  3916. auto res = cli.Get("/invalid");
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3919. EXPECT_EQ("NOT_FOUND", res->body);
  3920. }
  3921. }
  3922. #endif
  3923. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3924. // process_request() wraps only routing() in a try/catch, so an exception from
  3925. // any other user callback used to unwind into the task queue - which does not
  3926. // catch - and terminate the process. Each test below runs the server on a
  3927. // single worker thread: a guard that catches the exception but still loses the
  3928. // thread would otherwise be hidden by a spare worker serving the follow-up
  3929. // request. Note that a regression here aborts the whole test binary rather
  3930. // than failing one test.
  3931. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3932. Server svr;
  3933. svr.new_task_queue = [] { return new ThreadPool(1); };
  3934. std::atomic<int> reported{0};
  3935. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3936. if (err == Error::UserCallbackException) { reported++; }
  3937. });
  3938. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3939. res.set_content_provider(
  3940. 1024, "text/plain",
  3941. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3942. sink.write("hello", 5);
  3943. throw std::runtime_error("from the content provider");
  3944. });
  3945. });
  3946. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. auto port = svr.bind_to_any_port(HOST);
  3950. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3951. auto se = detail::scope_exit([&] {
  3952. svr.stop();
  3953. listen_thread.join();
  3954. ASSERT_FALSE(svr.is_running());
  3955. });
  3956. svr.wait_until_ready();
  3957. {
  3958. Client cli(HOST, port);
  3959. cli.set_read_timeout(5, 0);
  3960. EXPECT_FALSE(cli.Get("/throw"));
  3961. }
  3962. EXPECT_TRUE(svr.is_running());
  3963. EXPECT_EQ(1, reported.load());
  3964. // A request on a fresh connection is still served.
  3965. {
  3966. Client cli(HOST, port);
  3967. auto res = cli.Get("/ok");
  3968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3969. EXPECT_EQ(StatusCode::OK_200, res->status);
  3970. EXPECT_EQ("ok", res->body);
  3971. }
  3972. }
  3973. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3974. Server svr;
  3975. svr.new_task_queue = [] { return new ThreadPool(1); };
  3976. std::atomic<bool> should_throw{true};
  3977. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3978. res.set_content("hi", "text/plain");
  3979. });
  3980. svr.set_post_routing_handler(
  3981. [&](const Request & /*req*/, Response & /*res*/) {
  3982. if (should_throw) {
  3983. throw std::runtime_error("from the post-routing handler");
  3984. }
  3985. });
  3986. auto port = svr.bind_to_any_port(HOST);
  3987. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3988. auto se = detail::scope_exit([&] {
  3989. svr.stop();
  3990. listen_thread.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. svr.wait_until_ready();
  3994. {
  3995. Client cli(HOST, port);
  3996. cli.set_read_timeout(5, 0);
  3997. EXPECT_FALSE(cli.Get("/hi"));
  3998. }
  3999. EXPECT_TRUE(svr.is_running());
  4000. should_throw = false;
  4001. {
  4002. Client cli(HOST, port);
  4003. auto res = cli.Get("/hi");
  4004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4005. EXPECT_EQ(StatusCode::OK_200, res->status);
  4006. EXPECT_EQ("hi", res->body);
  4007. }
  4008. }
  4009. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4010. // The guard reports the caught exception through the error logger, which is
  4011. // a user callback too. A logger that throws has to be contained as well, or
  4012. // the process would terminate from inside the catch.
  4013. Server svr;
  4014. svr.new_task_queue = [] { return new ThreadPool(1); };
  4015. std::atomic<int> reported{0};
  4016. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4017. if (err == Error::UserCallbackException) {
  4018. reported++;
  4019. throw std::runtime_error("from the error logger");
  4020. }
  4021. });
  4022. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4023. res.set_content_provider(
  4024. 1024, "text/plain",
  4025. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4026. sink.write("hello", 5);
  4027. throw std::runtime_error("from the content provider");
  4028. });
  4029. });
  4030. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4031. res.set_content("ok", "text/plain");
  4032. });
  4033. auto port = svr.bind_to_any_port(HOST);
  4034. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4035. auto se = detail::scope_exit([&] {
  4036. svr.stop();
  4037. listen_thread.join();
  4038. ASSERT_FALSE(svr.is_running());
  4039. });
  4040. svr.wait_until_ready();
  4041. {
  4042. Client cli(HOST, port);
  4043. cli.set_read_timeout(5, 0);
  4044. EXPECT_FALSE(cli.Get("/throw"));
  4045. }
  4046. EXPECT_TRUE(svr.is_running());
  4047. EXPECT_EQ(1, reported.load());
  4048. {
  4049. Client cli(HOST, port);
  4050. auto res = cli.Get("/ok");
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ(StatusCode::OK_200, res->status);
  4053. EXPECT_EQ("ok", res->body);
  4054. }
  4055. }
  4056. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4057. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4058. // so the exception unwinds through the ws::WebSocket object on its way to
  4059. // the guard. None of the HTTP cases above cross that.
  4060. Server svr;
  4061. svr.new_task_queue = [] { return new ThreadPool(1); };
  4062. std::atomic<int> reported{0};
  4063. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4064. if (err == Error::UserCallbackException) { reported++; }
  4065. });
  4066. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4067. throw std::runtime_error("from the WebSocket handler");
  4068. });
  4069. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4070. res.set_content("ok", "text/plain");
  4071. });
  4072. auto port = svr.bind_to_any_port(HOST);
  4073. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4074. auto se = detail::scope_exit([&] {
  4075. svr.stop();
  4076. listen_thread.join();
  4077. ASSERT_FALSE(svr.is_running());
  4078. });
  4079. svr.wait_until_ready();
  4080. {
  4081. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4082. "/ws");
  4083. auto res = client.connect();
  4084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4085. // The server dropped the connection instead of dying.
  4086. std::string msg;
  4087. EXPECT_FALSE(client.read(msg));
  4088. client.close();
  4089. }
  4090. EXPECT_TRUE(svr.is_running());
  4091. EXPECT_EQ(1, reported.load());
  4092. {
  4093. Client cli(HOST, port);
  4094. auto res = cli.Get("/ok");
  4095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4096. EXPECT_EQ(StatusCode::OK_200, res->status);
  4097. EXPECT_EQ("ok", res->body);
  4098. }
  4099. }
  4100. #ifdef CPPHTTPLIB_SSL_ENABLED
  4101. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4102. // SSLServer::process_and_close_socket() is a separate overload with its own
  4103. // guard, so it is exercised on its own.
  4104. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4105. ASSERT_TRUE(svr.is_valid());
  4106. svr.new_task_queue = [] { return new ThreadPool(1); };
  4107. std::atomic<int> reported{0};
  4108. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4109. if (err == Error::UserCallbackException) { reported++; }
  4110. });
  4111. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4112. res.set_content_provider(
  4113. 1024, "text/plain",
  4114. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4115. sink.write("hello", 5);
  4116. throw std::runtime_error("from the content provider");
  4117. });
  4118. });
  4119. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4120. res.set_content("ok", "text/plain");
  4121. });
  4122. auto port = svr.bind_to_any_port(HOST);
  4123. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4124. auto se = detail::scope_exit([&] {
  4125. svr.stop();
  4126. listen_thread.join();
  4127. ASSERT_FALSE(svr.is_running());
  4128. });
  4129. svr.wait_until_ready();
  4130. {
  4131. SSLClient cli(HOST, port);
  4132. cli.enable_server_certificate_verification(false);
  4133. cli.set_read_timeout(5, 0);
  4134. EXPECT_FALSE(cli.Get("/throw"));
  4135. }
  4136. EXPECT_TRUE(svr.is_running());
  4137. EXPECT_EQ(1, reported.load());
  4138. {
  4139. SSLClient cli(HOST, port);
  4140. cli.enable_server_certificate_verification(false);
  4141. auto res = cli.Get("/ok");
  4142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4143. EXPECT_EQ(StatusCode::OK_200, res->status);
  4144. EXPECT_EQ("ok", res->body);
  4145. }
  4146. }
  4147. #endif
  4148. #endif
  4149. TEST(NoContentTest, ContentLength) {
  4150. Server svr;
  4151. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4152. res.status = StatusCode::NoContent_204;
  4153. });
  4154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4155. auto se = detail::scope_exit([&] {
  4156. svr.stop();
  4157. thread.join();
  4158. ASSERT_FALSE(svr.is_running());
  4159. });
  4160. svr.wait_until_ready();
  4161. {
  4162. Client cli(HOST, PORT);
  4163. auto res = cli.Get("/hi");
  4164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4165. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4166. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4167. }
  4168. }
  4169. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4170. #ifdef CPPHTTPLIB_SSL_ENABLED
  4171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4172. ASSERT_TRUE(svr.is_valid());
  4173. #else
  4174. Server svr;
  4175. #endif
  4176. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4177. if (req.path == "/routing_handler") {
  4178. res.set_header("PRE_ROUTING", "on");
  4179. res.set_content("Routing Handler", "text/plain");
  4180. return httplib::Server::HandlerResponse::Handled;
  4181. }
  4182. return httplib::Server::HandlerResponse::Unhandled;
  4183. });
  4184. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4185. res.set_content("Error", "text/html");
  4186. });
  4187. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4188. if (req.path == "/routing_handler") {
  4189. res.set_header("POST_ROUTING", "on");
  4190. }
  4191. });
  4192. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4193. res.set_content("Hello World!\n", "text/plain");
  4194. });
  4195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. #ifdef CPPHTTPLIB_SSL_ENABLED
  4204. SSLClient cli(HOST, PORT);
  4205. cli.enable_server_certificate_verification(false);
  4206. #else
  4207. Client cli(HOST, PORT);
  4208. #endif
  4209. auto res = cli.Get("/routing_handler");
  4210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4211. EXPECT_EQ(StatusCode::OK_200, res->status);
  4212. EXPECT_EQ("Routing Handler", res->body);
  4213. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4214. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4215. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4216. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4217. }
  4218. {
  4219. #ifdef CPPHTTPLIB_SSL_ENABLED
  4220. SSLClient cli(HOST, PORT);
  4221. cli.enable_server_certificate_verification(false);
  4222. #else
  4223. Client cli(HOST, PORT);
  4224. #endif
  4225. auto res = cli.Get("/hi");
  4226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("Hello World!\n", res->body);
  4229. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4230. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4231. }
  4232. {
  4233. #ifdef CPPHTTPLIB_SSL_ENABLED
  4234. SSLClient cli(HOST, PORT);
  4235. cli.enable_server_certificate_verification(false);
  4236. #else
  4237. Client cli(HOST, PORT);
  4238. #endif
  4239. auto res = cli.Get("/aaa");
  4240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4241. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4242. EXPECT_EQ("Error", res->body);
  4243. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4244. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4245. }
  4246. }
  4247. TEST(RequestHandlerTest, PreRequestHandler) {
  4248. auto route_path = "/user/:user";
  4249. Server svr;
  4250. svr.Get("/hi", [](const Request &, Response &res) {
  4251. res.set_content("hi", "text/plain");
  4252. });
  4253. svr.Get(route_path, [](const Request &req, Response &res) {
  4254. res.set_content(req.path_params.at("user"), "text/plain");
  4255. });
  4256. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4257. if (req.matched_route == route_path) {
  4258. auto user = req.path_params.at("user");
  4259. if (user != "john") {
  4260. res.status = StatusCode::Forbidden_403;
  4261. res.set_content("error", "text/html");
  4262. return Server::HandlerResponse::Handled;
  4263. }
  4264. }
  4265. return Server::HandlerResponse::Unhandled;
  4266. });
  4267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4268. auto se = detail::scope_exit([&] {
  4269. svr.stop();
  4270. thread.join();
  4271. ASSERT_FALSE(svr.is_running());
  4272. });
  4273. svr.wait_until_ready();
  4274. Client cli(HOST, PORT);
  4275. {
  4276. auto res = cli.Get("/hi");
  4277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4278. EXPECT_EQ(StatusCode::OK_200, res->status);
  4279. EXPECT_EQ("hi", res->body);
  4280. }
  4281. {
  4282. auto res = cli.Get("/user/john");
  4283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4284. EXPECT_EQ(StatusCode::OK_200, res->status);
  4285. EXPECT_EQ("john", res->body);
  4286. }
  4287. {
  4288. auto res = cli.Get("/user/invalid-user");
  4289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4290. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4291. EXPECT_EQ("error", res->body);
  4292. }
  4293. }
  4294. // The pre-request handler must run before the request body is read, so a
  4295. // rejected request never forces the server to buffer a (potentially large)
  4296. // body. Here the posted body is larger than the payload limit: if the body
  4297. // were read first the server would answer 413, but because the pre-request
  4298. // handler runs first it answers 403 and the body is never read.
  4299. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4300. Server svr;
  4301. svr.set_payload_max_length(8);
  4302. auto handler_ran = false;
  4303. svr.Post("/reject", [&](const Request &req, Response &res) {
  4304. handler_ran = true;
  4305. res.set_content(req.body, "text/plain");
  4306. });
  4307. svr.Post("/accept", [](const Request &req, Response &res) {
  4308. res.set_content(req.body, "text/plain");
  4309. });
  4310. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4311. if (req.matched_route == "/reject") {
  4312. res.status = StatusCode::Forbidden_403;
  4313. res.set_content("denied", "text/plain");
  4314. return Server::HandlerResponse::Handled;
  4315. }
  4316. return Server::HandlerResponse::Unhandled;
  4317. });
  4318. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. Client cli(HOST, PORT);
  4326. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4327. // rejects with 403 before the body is read, so 413 is never reached.
  4328. {
  4329. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4331. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4332. EXPECT_EQ("denied", res->body);
  4333. EXPECT_FALSE(handler_ran);
  4334. }
  4335. // An approved route still reads the body and enforces the payload limit.
  4336. {
  4337. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4340. }
  4341. }
  4342. TEST(UserDataTest, BasicOperations) {
  4343. httplib::UserData ud;
  4344. // Initially empty
  4345. EXPECT_FALSE(ud.has("key"));
  4346. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4347. // set and get
  4348. ud.set("key", 42);
  4349. EXPECT_TRUE(ud.has("key"));
  4350. auto *p = ud.get<int>("key");
  4351. ASSERT_NE(nullptr, p);
  4352. EXPECT_EQ(42, *p);
  4353. // Type mismatch → nullptr
  4354. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4355. // Overwrite with different type
  4356. ud.set("key", std::string("hello"));
  4357. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4358. auto *s = ud.get<std::string>("key");
  4359. ASSERT_NE(nullptr, s);
  4360. EXPECT_EQ("hello", *s);
  4361. // erase
  4362. ud.erase("key");
  4363. EXPECT_FALSE(ud.has("key"));
  4364. // clear
  4365. ud.set("a", 1);
  4366. ud.set("b", 2);
  4367. ud.clear();
  4368. EXPECT_FALSE(ud.has("a"));
  4369. EXPECT_FALSE(ud.has("b"));
  4370. }
  4371. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4372. struct AuthCtx {
  4373. std::string user_id;
  4374. };
  4375. Server svr;
  4376. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4377. res.user_data.set("auth", AuthCtx{"alice"});
  4378. return Server::HandlerResponse::Unhandled;
  4379. });
  4380. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4381. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4382. ASSERT_NE(nullptr, ctx);
  4383. res.set_content("Hello " + ctx->user_id, "text/plain");
  4384. });
  4385. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4386. auto se = detail::scope_exit([&] {
  4387. svr.stop();
  4388. thread.join();
  4389. ASSERT_FALSE(svr.is_running());
  4390. });
  4391. svr.wait_until_ready();
  4392. Client cli(HOST, PORT);
  4393. auto res = cli.Get("/me");
  4394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4395. EXPECT_EQ(StatusCode::OK_200, res->status);
  4396. EXPECT_EQ("Hello alice", res->body);
  4397. }
  4398. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4399. struct RoleCtx {
  4400. std::string role;
  4401. };
  4402. Server svr;
  4403. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4404. res.user_data.set("role", RoleCtx{"admin"});
  4405. return Server::HandlerResponse::Unhandled;
  4406. });
  4407. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4408. auto *ctx = res.user_data.get<RoleCtx>("role");
  4409. ASSERT_NE(nullptr, ctx);
  4410. res.set_content(ctx->role, "text/plain");
  4411. });
  4412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4413. auto se = detail::scope_exit([&] {
  4414. svr.stop();
  4415. thread.join();
  4416. ASSERT_FALSE(svr.is_running());
  4417. });
  4418. svr.wait_until_ready();
  4419. Client cli(HOST, PORT);
  4420. auto res = cli.Get("/role");
  4421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4422. EXPECT_EQ(StatusCode::OK_200, res->status);
  4423. EXPECT_EQ("admin", res->body);
  4424. }
  4425. TEST(InvalidFormatTest, StatusCode) {
  4426. Server svr;
  4427. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4428. res.set_content("Hello World!\n", "text/plain");
  4429. res.status = 9999; // Status should be a three-digit code...
  4430. });
  4431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4432. auto se = detail::scope_exit([&] {
  4433. svr.stop();
  4434. thread.join();
  4435. ASSERT_FALSE(svr.is_running());
  4436. });
  4437. svr.wait_until_ready();
  4438. {
  4439. Client cli(HOST, PORT);
  4440. auto res = cli.Get("/hi");
  4441. ASSERT_FALSE(res);
  4442. }
  4443. }
  4444. TEST(URLFragmentTest, WithFragment) {
  4445. Server svr;
  4446. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4447. EXPECT_TRUE(req.target == "/hi");
  4448. });
  4449. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4450. auto se = detail::scope_exit([&] {
  4451. svr.stop();
  4452. thread.join();
  4453. ASSERT_FALSE(svr.is_running());
  4454. });
  4455. svr.wait_until_ready();
  4456. {
  4457. Client cli(HOST, PORT);
  4458. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4459. EXPECT_TRUE(res);
  4460. EXPECT_EQ(StatusCode::OK_200, res->status);
  4461. res = cli.Get("/hi%23key1=val1=key2=val2");
  4462. EXPECT_TRUE(res);
  4463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4464. }
  4465. }
  4466. TEST(HeaderWriter, SetHeaderWriter) {
  4467. Server svr;
  4468. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4469. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4470. return detail::write_headers(strm, hdrs);
  4471. });
  4472. svr.Get("/hi", [](const Request &req, Response &res) {
  4473. auto it = req.headers.find("CustomClientHeader");
  4474. EXPECT_TRUE(it != req.headers.end());
  4475. EXPECT_EQ(it->second, "CustomClientValue");
  4476. res.set_content("Hello World!\n", "text/plain");
  4477. });
  4478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4479. auto se = detail::scope_exit([&] {
  4480. svr.stop();
  4481. thread.join();
  4482. ASSERT_FALSE(svr.is_running());
  4483. });
  4484. svr.wait_until_ready();
  4485. {
  4486. Client cli(HOST, PORT);
  4487. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4488. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4489. return detail::write_headers(strm, hdrs);
  4490. });
  4491. auto res = cli.Get("/hi");
  4492. EXPECT_TRUE(res);
  4493. EXPECT_EQ(StatusCode::OK_200, res->status);
  4494. auto it = res->headers.find("CustomServerHeader");
  4495. EXPECT_TRUE(it != res->headers.end());
  4496. EXPECT_EQ(it->second, "CustomServerValue");
  4497. }
  4498. }
  4499. class ServerTest : public ::testing::Test {
  4500. protected:
  4501. ServerTest()
  4502. : cli_(HOST, PORT)
  4503. #ifdef CPPHTTPLIB_SSL_ENABLED
  4504. ,
  4505. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4506. #endif
  4507. {
  4508. #ifdef CPPHTTPLIB_SSL_ENABLED
  4509. cli_.enable_server_certificate_verification(false);
  4510. #endif
  4511. // Allow LARGE_DATA (100MB) responses
  4512. cli_.set_payload_max_length(200 * 1024 * 1024);
  4513. }
  4514. virtual void SetUp() {
  4515. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4516. svr_.set_payload_max_length(200 * 1024 * 1024);
  4517. svr_.set_mount_point("/", "./www");
  4518. svr_.set_mount_point("/mount", "./www2");
  4519. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4520. svr_.Get("/hi",
  4521. [&](const Request & /*req*/, Response &res) {
  4522. res.set_content("Hello World!", "text/plain");
  4523. })
  4524. .Get("/file_content",
  4525. [&](const Request & /*req*/, Response &res) {
  4526. res.set_file_content("./www/dir/test.html");
  4527. })
  4528. .Get("/file_content_with_content_type",
  4529. [&](const Request & /*req*/, Response &res) {
  4530. res.set_file_content("./www/file", "text/plain");
  4531. })
  4532. .Get("/invalid_file_content",
  4533. [&](const Request & /*req*/, Response &res) {
  4534. res.set_file_content("./www/dir/invalid_file_path");
  4535. })
  4536. .Get("/http_response_splitting",
  4537. [&](const Request & /*req*/, Response &res) {
  4538. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4539. EXPECT_EQ(0U, res.headers.size());
  4540. EXPECT_FALSE(res.has_header("a"));
  4541. res.set_header("a", "1\nSet-Cookie: a=1");
  4542. EXPECT_EQ(0U, res.headers.size());
  4543. EXPECT_FALSE(res.has_header("a"));
  4544. res.set_header("a", "1\rSet-Cookie: a=1");
  4545. EXPECT_EQ(0U, res.headers.size());
  4546. EXPECT_FALSE(res.has_header("a"));
  4547. res.set_header("a\r\nb", "0");
  4548. EXPECT_EQ(0U, res.headers.size());
  4549. EXPECT_FALSE(res.has_header("a"));
  4550. res.set_header("a\rb", "0");
  4551. EXPECT_EQ(0U, res.headers.size());
  4552. EXPECT_FALSE(res.has_header("a"));
  4553. res.set_header("a\nb", "0");
  4554. EXPECT_EQ(0U, res.headers.size());
  4555. EXPECT_FALSE(res.has_header("a"));
  4556. res.set_redirect("1\r\nSet-Cookie: a=1");
  4557. EXPECT_EQ(0U, res.headers.size());
  4558. EXPECT_FALSE(res.has_header("Location"));
  4559. })
  4560. .Get("/slow",
  4561. [&](const Request & /*req*/, Response &res) {
  4562. std::this_thread::sleep_for(std::chrono::seconds(4));
  4563. res.set_content("slow", "text/plain");
  4564. })
  4565. #if 0
  4566. .Post("/slowpost",
  4567. [&](const Request & /*req*/, Response &res) {
  4568. std::this_thread::sleep_for(std::chrono::seconds(2));
  4569. res.set_content("slow", "text/plain");
  4570. })
  4571. #endif
  4572. .Get("/remote_addr",
  4573. [&](const Request &req, Response &res) {
  4574. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4575. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4576. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4577. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4579. #endif
  4580. res.set_content(req.remote_addr, "text/plain");
  4581. })
  4582. .Get("/local_addr",
  4583. [&](const Request &req, Response &res) {
  4584. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4585. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4586. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4587. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4589. #endif
  4590. auto local_addr = req.local_addr;
  4591. auto local_port = std::to_string(req.local_port);
  4592. res.set_content(local_addr.append(":").append(local_port),
  4593. "text/plain");
  4594. })
  4595. .Get("/endwith%",
  4596. [&](const Request & /*req*/, Response &res) {
  4597. res.set_content("Hello World!", "text/plain");
  4598. })
  4599. .Get("/a\\+\\+b",
  4600. [&](const Request &req, Response &res) {
  4601. ASSERT_TRUE(req.has_param("a +b"));
  4602. auto val = req.get_param_value("a +b");
  4603. res.set_content(val, "text/plain");
  4604. })
  4605. .Get("/", [&](const Request & /*req*/,
  4606. Response &res) { res.set_redirect("/hi"); })
  4607. .Post("/1",
  4608. [](const Request & /*req*/, Response &res) {
  4609. res.set_redirect("/2", StatusCode::SeeOther_303);
  4610. })
  4611. .Get("/2",
  4612. [](const Request & /*req*/, Response &res) {
  4613. res.set_content("redirected.", "text/plain");
  4614. res.status = StatusCode::OK_200;
  4615. })
  4616. .Post("/person",
  4617. [&](const Request &req, Response &res) {
  4618. if (req.has_param("name") && req.has_param("note")) {
  4619. persons_[req.get_param_value("name")] =
  4620. req.get_param_value("note");
  4621. } else {
  4622. res.status = StatusCode::BadRequest_400;
  4623. }
  4624. })
  4625. .Put("/person",
  4626. [&](const Request &req, Response &res) {
  4627. if (req.has_param("name") && req.has_param("note")) {
  4628. persons_[req.get_param_value("name")] =
  4629. req.get_param_value("note");
  4630. } else {
  4631. res.status = StatusCode::BadRequest_400;
  4632. }
  4633. })
  4634. .Get("/person/(.*)",
  4635. [&](const Request &req, Response &res) {
  4636. string name = req.matches[1];
  4637. if (persons_.find(name) != persons_.end()) {
  4638. auto note = persons_[name];
  4639. res.set_content(note, "text/plain");
  4640. } else {
  4641. res.status = StatusCode::NotFound_404;
  4642. }
  4643. })
  4644. .Delete("/person",
  4645. [&](const Request &req, Response &res) {
  4646. if (req.has_param("name")) {
  4647. string name = req.get_param_value("name");
  4648. if (persons_.find(name) != persons_.end()) {
  4649. persons_.erase(name);
  4650. res.set_content("DELETED", "text/plain");
  4651. } else {
  4652. res.status = StatusCode::NotFound_404;
  4653. }
  4654. } else {
  4655. res.status = StatusCode::BadRequest_400;
  4656. }
  4657. })
  4658. .Post("/x-www-form-urlencoded-json",
  4659. [&](const Request &req, Response &res) {
  4660. auto json = req.get_param_value("json");
  4661. ASSERT_EQ(JSON_DATA, json);
  4662. res.set_content(json, "appliation/json");
  4663. res.status = StatusCode::OK_200;
  4664. })
  4665. .Get("/streamed-chunked",
  4666. [&](const Request & /*req*/, Response &res) {
  4667. res.set_chunked_content_provider(
  4668. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4669. sink.os << "123";
  4670. sink.os << "456";
  4671. sink.os << "789";
  4672. sink.done();
  4673. return true;
  4674. });
  4675. })
  4676. .Get("/streamed-chunked-with-prohibited-trailer",
  4677. [&](const Request & /*req*/, Response &res) {
  4678. auto i = new int(0);
  4679. // Declare both a prohibited trailer (Content-Length) and an
  4680. // allowed one
  4681. res.set_header("Trailer", "Content-Length, X-Allowed");
  4682. res.set_chunked_content_provider(
  4683. "text/plain",
  4684. [i](size_t /*offset*/, DataSink &sink) {
  4685. switch (*i) {
  4686. case 0: sink.os << "123"; break;
  4687. case 1: sink.os << "456"; break;
  4688. case 2: sink.os << "789"; break;
  4689. case 3: {
  4690. sink.done_with_trailer(
  4691. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4692. } break;
  4693. }
  4694. (*i)++;
  4695. return true;
  4696. },
  4697. [i](bool success) {
  4698. EXPECT_TRUE(success);
  4699. delete i;
  4700. });
  4701. })
  4702. .Get("/streamed-chunked2",
  4703. [&](const Request & /*req*/, Response &res) {
  4704. auto i = new int(0);
  4705. res.set_chunked_content_provider(
  4706. "text/plain",
  4707. [i](size_t /*offset*/, DataSink &sink) {
  4708. switch (*i) {
  4709. case 0: sink.os << "123"; break;
  4710. case 1: sink.os << "456"; break;
  4711. case 2: sink.os << "789"; break;
  4712. case 3: sink.done(); break;
  4713. }
  4714. (*i)++;
  4715. return true;
  4716. },
  4717. [i](bool success) {
  4718. EXPECT_TRUE(success);
  4719. delete i;
  4720. });
  4721. })
  4722. .Get("/streamed-chunked-with-trailer",
  4723. [&](const Request & /*req*/, Response &res) {
  4724. auto i = new int(0);
  4725. res.set_header("Trailer", "Dummy1, Dummy2");
  4726. res.set_chunked_content_provider(
  4727. "text/plain",
  4728. [i](size_t /*offset*/, DataSink &sink) {
  4729. switch (*i) {
  4730. case 0: sink.os << "123"; break;
  4731. case 1: sink.os << "456"; break;
  4732. case 2: sink.os << "789"; break;
  4733. case 3: {
  4734. sink.done_with_trailer(
  4735. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4736. } break;
  4737. }
  4738. (*i)++;
  4739. return true;
  4740. },
  4741. [i](bool success) {
  4742. EXPECT_TRUE(success);
  4743. delete i;
  4744. });
  4745. })
  4746. .Get("/streamed",
  4747. [&](const Request & /*req*/, Response &res) {
  4748. res.set_content_provider(
  4749. 6, "text/plain",
  4750. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4751. sink.os << (offset < 3 ? "a" : "b");
  4752. return true;
  4753. });
  4754. })
  4755. .Get("/streamed-without-length",
  4756. [&](const Request & /*req*/, Response &res) {
  4757. auto data = new std::string("abcdefg");
  4758. res.set_content_provider(
  4759. "text/plain",
  4760. [data](size_t offset, DataSink &sink) {
  4761. if (offset < data->size()) {
  4762. sink.os << data->substr(offset);
  4763. }
  4764. sink.done();
  4765. return true;
  4766. },
  4767. [data](bool success) {
  4768. EXPECT_TRUE(success);
  4769. delete data;
  4770. });
  4771. })
  4772. .Get("/streamed-with-range",
  4773. [&](const Request &req, Response &res) {
  4774. auto data = new std::string("abcdefg");
  4775. // An explicit status keeps the server from picking the 206 it
  4776. // would otherwise choose for a ranged request, so the response
  4777. // is not a partial representation.
  4778. auto status = req.get_param_value("status");
  4779. if (status == "200") {
  4780. res.status = StatusCode::OK_200;
  4781. } else if (status == "403") {
  4782. res.status = StatusCode::Forbidden_403;
  4783. }
  4784. res.set_content_provider(
  4785. data->size(), "text/plain",
  4786. [data](size_t offset, size_t length, DataSink &sink) {
  4787. size_t DATA_CHUNK_SIZE = 4;
  4788. const auto &d = *data;
  4789. auto out_len =
  4790. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4791. auto ret =
  4792. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4793. EXPECT_TRUE(ret);
  4794. return true;
  4795. },
  4796. [data, &req](bool success) {
  4797. EXPECT_EQ(success, !req.has_param("error"));
  4798. delete data;
  4799. });
  4800. })
  4801. .Get("/streamed-cancel",
  4802. [&](const Request & /*req*/, Response &res) {
  4803. res.set_content_provider(
  4804. size_t(-1), "text/plain",
  4805. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4806. sink.os << "data_chunk";
  4807. return true;
  4808. });
  4809. })
  4810. .Get("/regex-with-delimiter",
  4811. [&](const Request &req, Response & /*res*/) {
  4812. ASSERT_TRUE(req.has_param("key"));
  4813. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4814. })
  4815. .Get("/with-range",
  4816. [&](const Request & /*req*/, Response &res) {
  4817. res.set_content("abcdefg", "text/plain");
  4818. })
  4819. .Get("/test-start-time",
  4820. [&](const Request &req, Response & /*res*/) {
  4821. EXPECT_NE(req.start_time_,
  4822. std::chrono::steady_clock::time_point::min());
  4823. })
  4824. .Get("/with-range-customized-response",
  4825. [&](const Request & /*req*/, Response &res) {
  4826. res.status = StatusCode::BadRequest_400;
  4827. res.set_content(JSON_DATA, "application/json");
  4828. })
  4829. .Post("/chunked",
  4830. [&](const Request &req, Response & /*res*/) {
  4831. EXPECT_EQ(req.body, "dechunked post body");
  4832. })
  4833. .Post("/large-chunked",
  4834. [&](const Request &req, Response & /*res*/) {
  4835. std::string expected(6 * 30 * 1024u, 'a');
  4836. EXPECT_EQ(req.body, expected);
  4837. })
  4838. .Post("/multipart",
  4839. [&](const Request &req, Response & /*res*/) {
  4840. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4841. req.form.get_field_count("text2") +
  4842. req.form.get_field_count("file3") +
  4843. req.form.get_field_count("file4"));
  4844. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4845. req.form.get_file_count("file2"));
  4846. ASSERT_TRUE(!req.form.has_file("???"));
  4847. ASSERT_TRUE(!req.form.has_field("???"));
  4848. ASSERT_TRUE(req.body.empty());
  4849. {
  4850. const auto &text = req.form.get_field("text1");
  4851. EXPECT_EQ("text default", text);
  4852. }
  4853. {
  4854. const auto &text = req.form.get_field("text2");
  4855. EXPECT_EQ("aωb", text);
  4856. }
  4857. {
  4858. const auto &file = req.form.get_file("file1");
  4859. EXPECT_EQ("hello.txt", file.filename);
  4860. EXPECT_EQ("text/plain", file.content_type);
  4861. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4862. }
  4863. {
  4864. const auto &file = req.form.get_file("file2");
  4865. EXPECT_EQ("world.json", file.filename);
  4866. EXPECT_EQ("application/json", file.content_type);
  4867. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4868. }
  4869. {
  4870. const auto &text = req.form.get_field("file3");
  4871. EXPECT_EQ(0u, text.size());
  4872. }
  4873. {
  4874. const auto &text = req.form.get_field("file4");
  4875. EXPECT_EQ(0u, text.size());
  4876. }
  4877. })
  4878. .Post("/multipart/multi_file_values",
  4879. [&](const Request &req, Response & /*res*/) {
  4880. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4881. req.form.get_field_count("multi_text1"));
  4882. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4883. ASSERT_TRUE(!req.form.has_file("???"));
  4884. ASSERT_TRUE(!req.form.has_field("???"));
  4885. ASSERT_TRUE(req.body.empty());
  4886. {
  4887. const auto &text = req.form.get_field("text");
  4888. EXPECT_EQ("default text", text);
  4889. }
  4890. {
  4891. const auto &text1_values = req.form.get_fields("multi_text1");
  4892. EXPECT_EQ(2u, text1_values.size());
  4893. EXPECT_EQ("aaaaa", text1_values[0]);
  4894. EXPECT_EQ("bbbbb", text1_values[1]);
  4895. }
  4896. {
  4897. const auto &file1_values = req.form.get_files("multi_file1");
  4898. EXPECT_EQ(2u, file1_values.size());
  4899. auto file1 = file1_values[0];
  4900. EXPECT_EQ(file1.filename, "hello.txt");
  4901. EXPECT_EQ(file1.content_type, "text/plain");
  4902. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4903. auto file2 = file1_values[1];
  4904. EXPECT_EQ(file2.filename, "world.json");
  4905. EXPECT_EQ(file2.content_type, "application/json");
  4906. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4907. }
  4908. })
  4909. .Post("/empty",
  4910. [&](const Request &req, Response &res) {
  4911. EXPECT_EQ(req.body, "");
  4912. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4913. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4914. res.set_content("empty", "text/plain");
  4915. })
  4916. .Post("/empty-no-content-type",
  4917. [&](const Request &req, Response &res) {
  4918. EXPECT_EQ(req.body, "");
  4919. EXPECT_FALSE(req.has_header("Content-Type"));
  4920. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4921. res.set_content("empty-no-content-type", "text/plain");
  4922. })
  4923. .Post("/path-only",
  4924. [&](const Request &req, Response &res) {
  4925. EXPECT_EQ(req.body, "");
  4926. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4927. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4928. res.set_content("path-only", "text/plain");
  4929. })
  4930. .Post("/path-headers-only",
  4931. [&](const Request &req, Response &res) {
  4932. EXPECT_EQ(req.body, "");
  4933. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4934. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4935. EXPECT_EQ("world", req.get_header_value("hello"));
  4936. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4937. res.set_content("path-headers-only", "text/plain");
  4938. })
  4939. .Post("/post-large",
  4940. [&](const Request &req, Response &res) {
  4941. EXPECT_EQ(req.body, LARGE_DATA);
  4942. res.set_content(req.body, "text/plain");
  4943. })
  4944. .Post("/post-loopback",
  4945. [&](const Request &, Response &res,
  4946. ContentReader const &content_reader) {
  4947. std::string body;
  4948. content_reader([&](const char *data, size_t data_length) {
  4949. body.append(data, data_length);
  4950. return true;
  4951. });
  4952. res.set_content(body, "text/plain");
  4953. })
  4954. .Put("/put-loopback",
  4955. [&](const Request &, Response &res,
  4956. ContentReader const &content_reader) {
  4957. std::string body;
  4958. content_reader([&](const char *data, size_t data_length) {
  4959. body.append(data, data_length);
  4960. return true;
  4961. });
  4962. res.set_content(body, "text/plain");
  4963. })
  4964. .Patch("/patch-loopback",
  4965. [&](const Request &, Response &res,
  4966. ContentReader const &content_reader) {
  4967. std::string body;
  4968. content_reader([&](const char *data, size_t data_length) {
  4969. body.append(data, data_length);
  4970. return true;
  4971. });
  4972. res.set_content(body, "text/plain");
  4973. })
  4974. .Put("/empty-no-content-type",
  4975. [&](const Request &req, Response &res) {
  4976. EXPECT_EQ(req.body, "");
  4977. EXPECT_FALSE(req.has_header("Content-Type"));
  4978. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4979. res.set_content("empty-no-content-type", "text/plain");
  4980. })
  4981. .Put("/put",
  4982. [&](const Request &req, Response &res) {
  4983. EXPECT_EQ(req.body, "PUT");
  4984. res.set_content(req.body, "text/plain");
  4985. })
  4986. .Put("/put-large",
  4987. [&](const Request &req, Response &res) {
  4988. EXPECT_EQ(req.body, LARGE_DATA);
  4989. res.set_content(req.body, "text/plain");
  4990. })
  4991. .Patch("/patch",
  4992. [&](const Request &req, Response &res) {
  4993. EXPECT_EQ(req.body, "PATCH");
  4994. res.set_content(req.body, "text/plain");
  4995. })
  4996. .Delete("/delete",
  4997. [&](const Request & /*req*/, Response &res) {
  4998. res.set_content("DELETE", "text/plain");
  4999. })
  5000. .Delete("/delete-body",
  5001. [&](const Request &req, Response &res) {
  5002. EXPECT_EQ(req.body, "content");
  5003. res.set_content(req.body, "text/plain");
  5004. })
  5005. .Options(R"(\*)",
  5006. [&](const Request & /*req*/, Response &res) {
  5007. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5008. })
  5009. .CustomRoute("PROPFIND", "/dav/:id",
  5010. [&](const Request &req, Response &res) {
  5011. res.set_header("x-body-size",
  5012. std::to_string(req.body.size()));
  5013. res.set_header("x-matched-route", req.matched_route);
  5014. res.set_header("x-dav-id", req.path_params.at("id"));
  5015. res.status = StatusCode::MultiStatus_207;
  5016. res.set_content(req.body, "application/xml");
  5017. })
  5018. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5019. [&](const Request &req, Response &res) {
  5020. res.set_header("x-dav-match", req.matches[1]);
  5021. res.status = StatusCode::MultiStatus_207;
  5022. })
  5023. .CustomRoute("MKCOL", "/dav-mkcol",
  5024. [&](const Request &req, Response &res) {
  5025. EXPECT_TRUE(req.body.empty());
  5026. res.status = StatusCode::Created_201;
  5027. })
  5028. .CustomRoute(
  5029. "REPORT", "/dav-report",
  5030. [&](const Request & /*req*/, Response &res,
  5031. const ContentReader &content_reader) {
  5032. std::string body;
  5033. content_reader([&](const char *data, size_t data_length) {
  5034. body.append(data, data_length);
  5035. return true;
  5036. });
  5037. res.set_header("x-body-size", std::to_string(body.size()));
  5038. res.status = StatusCode::MultiStatus_207;
  5039. res.set_content(body, "application/xml");
  5040. })
  5041. .Get("/request-target",
  5042. [&](const Request &req, Response & /*res*/) {
  5043. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5044. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5045. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5046. })
  5047. .Get("/long-query-value",
  5048. [&](const Request &req, Response & /*res*/) {
  5049. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5050. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5051. })
  5052. .Get("/too-long-query-value",
  5053. [&](const Request &req, Response & /*res*/) {
  5054. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5055. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5056. })
  5057. .Get("/array-param",
  5058. [&](const Request &req, Response & /*res*/) {
  5059. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5060. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5061. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5062. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5063. })
  5064. .Get("/array-param-values",
  5065. [&](const Request &req, Response & /*res*/) {
  5066. auto values = req.get_param_values("array");
  5067. EXPECT_EQ(3u, values.size());
  5068. EXPECT_EQ("value1", values[0]);
  5069. EXPECT_EQ("value2", values[1]);
  5070. EXPECT_EQ("value3", values[2]);
  5071. auto empty = req.get_param_values("nonexistent");
  5072. EXPECT_TRUE(empty.empty());
  5073. })
  5074. .Post("/validate-no-multiple-headers",
  5075. [&](const Request &req, Response & /*res*/) {
  5076. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5077. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5078. })
  5079. .Post("/content_receiver",
  5080. [&](const Request &req, Response &res,
  5081. const ContentReader &content_reader) {
  5082. if (req.is_multipart_form_data()) {
  5083. std::vector<FormData> items;
  5084. content_reader(
  5085. [&](const FormData &file) {
  5086. items.push_back(file);
  5087. return true;
  5088. },
  5089. [&](const char *data, size_t data_length) {
  5090. items.back().content.append(data, data_length);
  5091. return true;
  5092. });
  5093. EXPECT_EQ(5u, items.size());
  5094. {
  5095. const auto &file = get_file_value(items, "text1");
  5096. EXPECT_TRUE(file.filename.empty());
  5097. EXPECT_EQ("text default", file.content);
  5098. }
  5099. {
  5100. const auto &file = get_file_value(items, "text2");
  5101. EXPECT_TRUE(file.filename.empty());
  5102. EXPECT_EQ("aωb", file.content);
  5103. }
  5104. {
  5105. const auto &file = get_file_value(items, "file1");
  5106. EXPECT_EQ("hello.txt", file.filename);
  5107. EXPECT_EQ("text/plain", file.content_type);
  5108. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5109. }
  5110. {
  5111. const auto &file = get_file_value(items, "file2");
  5112. EXPECT_EQ("world.json", file.filename);
  5113. EXPECT_EQ("application/json", file.content_type);
  5114. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5115. }
  5116. {
  5117. const auto &file = get_file_value(items, "file3");
  5118. EXPECT_TRUE(file.filename.empty());
  5119. EXPECT_EQ("application/octet-stream", file.content_type);
  5120. EXPECT_EQ(0u, file.content.size());
  5121. }
  5122. } else {
  5123. std::string body;
  5124. content_reader([&](const char *data, size_t data_length) {
  5125. EXPECT_EQ(7U, data_length);
  5126. body.append(data, data_length);
  5127. return true;
  5128. });
  5129. EXPECT_EQ(body, "content");
  5130. res.set_content(body, "text/plain");
  5131. }
  5132. })
  5133. .Put("/content_receiver",
  5134. [&](const Request & /*req*/, Response &res,
  5135. const ContentReader &content_reader) {
  5136. std::string body;
  5137. content_reader([&](const char *data, size_t data_length) {
  5138. body.append(data, data_length);
  5139. return true;
  5140. });
  5141. EXPECT_EQ(body, "content");
  5142. res.set_content(body, "text/plain");
  5143. })
  5144. .Patch("/content_receiver",
  5145. [&](const Request & /*req*/, Response &res,
  5146. const ContentReader &content_reader) {
  5147. std::string body;
  5148. content_reader([&](const char *data, size_t data_length) {
  5149. body.append(data, data_length);
  5150. return true;
  5151. });
  5152. EXPECT_EQ(body, "content");
  5153. res.set_content(body, "text/plain");
  5154. })
  5155. .Post("/query-string-and-body",
  5156. [&](const Request &req, Response & /*res*/) {
  5157. ASSERT_TRUE(req.has_param("key"));
  5158. EXPECT_EQ(req.get_param_value("key"), "value");
  5159. EXPECT_EQ(req.body, "content");
  5160. })
  5161. .Get("/last-request",
  5162. [&](const Request &req, Response & /*res*/) {
  5163. EXPECT_EQ("close", req.get_header_value("Connection"));
  5164. })
  5165. .Get(R"(/redirect/(\d+))",
  5166. [&](const Request &req, Response &res) {
  5167. auto num = std::stoi(req.matches[1]) + 1;
  5168. std::string url = "/redirect/" + std::to_string(num);
  5169. res.set_redirect(url);
  5170. })
  5171. .Post("/binary",
  5172. [&](const Request &req, Response &res) {
  5173. EXPECT_EQ(4U, req.body.size());
  5174. EXPECT_EQ("application/octet-stream",
  5175. req.get_header_value("Content-Type"));
  5176. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5177. res.set_content(req.body, "application/octet-stream");
  5178. })
  5179. .Put("/binary",
  5180. [&](const Request &req, Response &res) {
  5181. EXPECT_EQ(4U, req.body.size());
  5182. EXPECT_EQ("application/octet-stream",
  5183. req.get_header_value("Content-Type"));
  5184. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5185. res.set_content(req.body, "application/octet-stream");
  5186. })
  5187. .Patch("/binary",
  5188. [&](const Request &req, Response &res) {
  5189. EXPECT_EQ(4U, req.body.size());
  5190. EXPECT_EQ("application/octet-stream",
  5191. req.get_header_value("Content-Type"));
  5192. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5193. res.set_content(req.body, "application/octet-stream");
  5194. })
  5195. .Delete("/binary",
  5196. [&](const Request &req, Response &res) {
  5197. EXPECT_EQ(4U, req.body.size());
  5198. EXPECT_EQ("application/octet-stream",
  5199. req.get_header_value("Content-Type"));
  5200. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5201. res.set_content(req.body, "application/octet-stream");
  5202. })
  5203. .Get("/issue1772",
  5204. [&](const Request & /*req*/, Response &res) {
  5205. res.status = 401;
  5206. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5207. })
  5208. .Delete("/issue609",
  5209. [](const httplib::Request &, httplib::Response &res,
  5210. const httplib::ContentReader &) {
  5211. res.set_content("ok", "text/plain");
  5212. })
  5213. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5214. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5215. .Get("/compress",
  5216. [&](const Request & /*req*/, Response &res) {
  5217. res.set_content(
  5218. "12345678901234567890123456789012345678901234567890123456789"
  5219. "01234567890123456789012345678901234567890",
  5220. "text/plain");
  5221. })
  5222. .Get("/compress-with-charset",
  5223. [&](const Request & /*req*/, Response &res) {
  5224. res.set_content(
  5225. "12345678901234567890123456789012345678901234567890123456789"
  5226. "01234567890123456789012345678901234567890",
  5227. "application/json; charset=utf-8");
  5228. })
  5229. .Get("/nocompress",
  5230. [&](const Request & /*req*/, Response &res) {
  5231. res.set_content(
  5232. "12345678901234567890123456789012345678901234567890123456789"
  5233. "01234567890123456789012345678901234567890",
  5234. "application/octet-stream");
  5235. })
  5236. .Post("/compress-multipart",
  5237. [&](const Request &req, Response & /*res*/) {
  5238. EXPECT_EQ(2u, req.form.fields.size());
  5239. ASSERT_TRUE(!req.form.has_field("???"));
  5240. {
  5241. const auto &text = req.form.get_field("key1");
  5242. EXPECT_EQ("test", text);
  5243. }
  5244. {
  5245. const auto &text = req.form.get_field("key2");
  5246. EXPECT_EQ("--abcdefg123", text);
  5247. }
  5248. })
  5249. #endif
  5250. ;
  5251. persons_["john"] = "programmer";
  5252. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5253. svr_.wait_until_ready();
  5254. }
  5255. virtual void TearDown() {
  5256. svr_.stop();
  5257. if (!request_threads_.empty()) {
  5258. std::this_thread::sleep_for(std::chrono::seconds(1));
  5259. for (auto &t : request_threads_) {
  5260. t.join();
  5261. }
  5262. }
  5263. t_.join();
  5264. }
  5265. map<string, string> persons_;
  5266. #ifdef CPPHTTPLIB_SSL_ENABLED
  5267. SSLClient cli_;
  5268. SSLServer svr_;
  5269. #else
  5270. Client cli_;
  5271. Server svr_;
  5272. #endif
  5273. thread t_;
  5274. std::vector<thread> request_threads_;
  5275. };
  5276. TEST_F(ServerTest, GetMethod200) {
  5277. auto res = cli_.Get("/hi");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. EXPECT_EQ("HTTP/1.1", res->version);
  5280. EXPECT_EQ(StatusCode::OK_200, res->status);
  5281. EXPECT_EQ("OK", res->reason);
  5282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5283. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5284. EXPECT_EQ("Hello World!", res->body);
  5285. }
  5286. TEST_F(ServerTest, GetEmptyFile) {
  5287. auto res = cli_.Get("/empty_file");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. EXPECT_EQ(StatusCode::OK_200, res->status);
  5290. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5291. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5292. EXPECT_EQ("", res->body);
  5293. }
  5294. TEST_F(ServerTest, GetFileContent) {
  5295. auto res = cli_.Get("/file_content");
  5296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5297. EXPECT_EQ(StatusCode::OK_200, res->status);
  5298. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5299. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5300. EXPECT_EQ("test.html", res->body);
  5301. }
  5302. TEST_F(ServerTest, GetFileContentWithRange) {
  5303. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5306. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5307. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5308. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5309. EXPECT_EQ("est", res->body);
  5310. }
  5311. TEST_F(ServerTest, GetFileContentWithContentType) {
  5312. auto res = cli_.Get("/file_content_with_content_type");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5317. EXPECT_EQ("file\n", res->body);
  5318. }
  5319. TEST_F(ServerTest, GetInvalidFileContent) {
  5320. auto res = cli_.Get("/invalid_file_content");
  5321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5322. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5323. }
  5324. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5325. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. EXPECT_EQ("HTTP/1.1", res->version);
  5328. EXPECT_EQ(StatusCode::OK_200, res->status);
  5329. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5330. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5331. EXPECT_EQ("Hello World!", res->body);
  5332. }
  5333. TEST_F(ServerTest, GetMethod302) {
  5334. auto res = cli_.Get("/");
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. EXPECT_EQ(StatusCode::Found_302, res->status);
  5337. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5338. }
  5339. TEST_F(ServerTest, GetMethod302Redirect) {
  5340. cli_.set_follow_location(true);
  5341. auto res = cli_.Get("/");
  5342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5343. EXPECT_EQ(StatusCode::OK_200, res->status);
  5344. EXPECT_EQ("Hello World!", res->body);
  5345. EXPECT_EQ("/hi", res->location);
  5346. }
  5347. TEST_F(ServerTest, GetMethod404) {
  5348. auto res = cli_.Get("/invalid");
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5351. }
  5352. TEST_F(ServerTest, HeadMethod200) {
  5353. auto res = cli_.Head("/hi");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. EXPECT_EQ(StatusCode::OK_200, res->status);
  5356. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. EXPECT_TRUE(res->body.empty());
  5358. }
  5359. TEST_F(ServerTest, HeadMethod200Static) {
  5360. auto res = cli_.Head("/mount/dir/index.html");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. EXPECT_EQ(StatusCode::OK_200, res->status);
  5363. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5364. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5365. EXPECT_TRUE(res->body.empty());
  5366. }
  5367. TEST_F(ServerTest, HeadMethod404) {
  5368. auto res = cli_.Head("/invalid");
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5371. EXPECT_TRUE(res->body.empty());
  5372. }
  5373. TEST_F(ServerTest, GetMethodPersonJohn) {
  5374. auto res = cli_.Get("/person/john");
  5375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5376. EXPECT_EQ(StatusCode::OK_200, res->status);
  5377. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5378. EXPECT_EQ("programmer", res->body);
  5379. }
  5380. TEST_F(ServerTest, PostMethod1) {
  5381. auto res = cli_.Get("/person/john1");
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5384. res = cli_.Post("/person", "name=john1&note=coder",
  5385. "application/x-www-form-urlencoded");
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. res = cli_.Get("/person/john1");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. ASSERT_EQ(StatusCode::OK_200, res->status);
  5391. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5392. ASSERT_EQ("coder", res->body);
  5393. }
  5394. TEST_F(ServerTest, PostMethod2) {
  5395. auto res = cli_.Get("/person/john2");
  5396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5397. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5398. Params params;
  5399. params.emplace("name", "john2");
  5400. params.emplace("note", "coder");
  5401. res = cli_.Post("/person", params);
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. ASSERT_EQ(StatusCode::OK_200, res->status);
  5404. res = cli_.Get("/person/john2");
  5405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5406. ASSERT_EQ(StatusCode::OK_200, res->status);
  5407. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5408. ASSERT_EQ("coder", res->body);
  5409. }
  5410. TEST_F(ServerTest, PutMethod3) {
  5411. auto res = cli_.Get("/person/john3");
  5412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5413. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5414. Params params;
  5415. params.emplace("name", "john3");
  5416. params.emplace("note", "coder");
  5417. res = cli_.Put("/person", params);
  5418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5419. ASSERT_EQ(StatusCode::OK_200, res->status);
  5420. res = cli_.Get("/person/john3");
  5421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5422. ASSERT_EQ(StatusCode::OK_200, res->status);
  5423. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5424. ASSERT_EQ("coder", res->body);
  5425. }
  5426. TEST_F(ServerTest, DeleteMethod1) {
  5427. auto res = cli_.Get("/person/john4");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5430. Params params;
  5431. params.emplace("name", "john4");
  5432. params.emplace("note", "coder");
  5433. res = cli_.Post("/person", params);
  5434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5435. ASSERT_EQ(StatusCode::OK_200, res->status);
  5436. res = cli_.Get("/person/john4");
  5437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5438. ASSERT_EQ(StatusCode::OK_200, res->status);
  5439. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5440. ASSERT_EQ("coder", res->body);
  5441. Params delete_params;
  5442. delete_params.emplace("name", "john4");
  5443. res = cli_.Delete("/person", delete_params);
  5444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5445. ASSERT_EQ(StatusCode::OK_200, res->status);
  5446. ASSERT_EQ("DELETED", res->body);
  5447. res = cli_.Get("/person/john4");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5450. }
  5451. TEST_F(ServerTest, DeleteMethod2) {
  5452. auto res = cli_.Get("/person/john5");
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5455. Params params;
  5456. params.emplace("name", "john5");
  5457. params.emplace("note", "developer");
  5458. res = cli_.Post("/person", params);
  5459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5460. ASSERT_EQ(StatusCode::OK_200, res->status);
  5461. res = cli_.Get("/person/john5");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. ASSERT_EQ(StatusCode::OK_200, res->status);
  5464. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5465. ASSERT_EQ("developer", res->body);
  5466. Params delete_params;
  5467. delete_params.emplace("name", "john5");
  5468. Headers headers;
  5469. headers.emplace("Custom-Header", "test-value");
  5470. res = cli_.Delete("/person", headers, delete_params);
  5471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5472. ASSERT_EQ(StatusCode::OK_200, res->status);
  5473. ASSERT_EQ("DELETED", res->body);
  5474. res = cli_.Get("/person/john5");
  5475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5476. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5477. }
  5478. TEST_F(ServerTest, DeleteMethod3) {
  5479. auto res = cli_.Get("/person/john6");
  5480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5481. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5482. Params params;
  5483. params.emplace("name", "john6");
  5484. params.emplace("note", "tester");
  5485. res = cli_.Post("/person", params);
  5486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5487. ASSERT_EQ(StatusCode::OK_200, res->status);
  5488. res = cli_.Get("/person/john6");
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5492. ASSERT_EQ("tester", res->body);
  5493. Params delete_params;
  5494. delete_params.emplace("name", "john6");
  5495. Headers headers;
  5496. headers.emplace("Custom-Header", "test-value");
  5497. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. ASSERT_EQ(StatusCode::OK_200, res->status);
  5500. ASSERT_EQ("DELETED", res->body);
  5501. res = cli_.Get("/person/john6");
  5502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5503. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5504. }
  5505. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5506. Params params;
  5507. params.emplace("json", JSON_DATA);
  5508. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. ASSERT_EQ(StatusCode::OK_200, res->status);
  5511. ASSERT_EQ(JSON_DATA, res->body);
  5512. }
  5513. TEST_F(ServerTest, PostEmptyContent) {
  5514. auto res = cli_.Post("/empty", "", "text/plain");
  5515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5516. ASSERT_EQ(StatusCode::OK_200, res->status);
  5517. ASSERT_EQ("empty", res->body);
  5518. }
  5519. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5520. auto res = cli_.Post("/empty-no-content-type");
  5521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5522. ASSERT_EQ(StatusCode::OK_200, res->status);
  5523. ASSERT_EQ("empty-no-content-type", res->body);
  5524. }
  5525. TEST_F(ServerTest, PostPathOnly) {
  5526. auto res = cli_.Post("/path-only");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. ASSERT_EQ(StatusCode::OK_200, res->status);
  5529. ASSERT_EQ("path-only", res->body);
  5530. }
  5531. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5532. auto res = cli_.Post("/path-headers-only",
  5533. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5535. ASSERT_EQ(StatusCode::OK_200, res->status);
  5536. ASSERT_EQ("path-headers-only", res->body);
  5537. }
  5538. TEST_F(ServerTest, PostLarge) {
  5539. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. ASSERT_EQ(StatusCode::OK_200, res->status);
  5542. EXPECT_EQ(LARGE_DATA, res->body);
  5543. }
  5544. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5545. auto res = cli_.Put("/empty-no-content-type");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. ASSERT_EQ(StatusCode::OK_200, res->status);
  5548. ASSERT_EQ("empty-no-content-type", res->body);
  5549. }
  5550. TEST_F(ServerTest, GetMethodDir) {
  5551. auto res = cli_.Get("/dir/");
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::OK_200, res->status);
  5554. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5555. auto body = R"(<html>
  5556. <head>
  5557. </head>
  5558. <body>
  5559. <a href="/dir/test.html">Test</a>
  5560. <a href="/hi">hi</a>
  5561. </body>
  5562. </html>
  5563. )";
  5564. EXPECT_EQ(body, res->body);
  5565. }
  5566. TEST_F(ServerTest, GetMethodDirTest) {
  5567. auto res = cli_.Get("/dir/test.html");
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ(StatusCode::OK_200, res->status);
  5570. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5571. EXPECT_EQ("test.html", res->body);
  5572. }
  5573. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5574. auto res = cli_.Get("/dir/../dir/test.html");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::OK_200, res->status);
  5577. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5578. EXPECT_EQ("test.html", res->body);
  5579. }
  5580. TEST_F(ServerTest, GetMethodInvalidPath) {
  5581. auto res = cli_.Get("/dir/../test.html");
  5582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5583. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5584. }
  5585. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5586. auto res = cli_.Get("/../www/dir/test.html");
  5587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5589. }
  5590. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5591. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5594. }
  5595. TEST_F(ServerTest, GetMethodDirMountTest) {
  5596. auto res = cli_.Get("/mount/dir/test.html");
  5597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5598. EXPECT_EQ(StatusCode::OK_200, res->status);
  5599. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5600. EXPECT_EQ("test.html", res->body);
  5601. }
  5602. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5603. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5605. EXPECT_EQ(StatusCode::OK_200, res->status);
  5606. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5607. EXPECT_EQ("test.html", res->body);
  5608. }
  5609. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5610. auto res = cli_.Get("/mount/dir/../test.html");
  5611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5613. }
  5614. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5615. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5618. }
  5619. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5620. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5623. }
  5624. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5625. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5628. }
  5629. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5630. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5633. }
  5634. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5635. auto res = cli_.Get("/mount/dir");
  5636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5637. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5638. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5639. }
  5640. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5641. auto res = cli_.Get("//dir");
  5642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5643. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5644. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5645. }
  5646. TEST_F(ServerTest, PostMethod303) {
  5647. auto res = cli_.Post("/1", "body", "text/plain");
  5648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5649. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5650. EXPECT_EQ("/2", res->get_header_value("Location"));
  5651. }
  5652. TEST_F(ServerTest, PostMethod303Redirect) {
  5653. cli_.set_follow_location(true);
  5654. auto res = cli_.Post("/1", "body", "text/plain");
  5655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5656. EXPECT_EQ(StatusCode::OK_200, res->status);
  5657. EXPECT_EQ("redirected.", res->body);
  5658. EXPECT_EQ("/2", res->location);
  5659. }
  5660. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5661. auto res = cli_.Get("/dir/test.abcde");
  5662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5663. EXPECT_EQ(StatusCode::OK_200, res->status);
  5664. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5665. EXPECT_EQ("abcde", res->body);
  5666. }
  5667. TEST_F(ServerTest, StaticFileRange) {
  5668. auto res =
  5669. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5672. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5673. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5674. EXPECT_EQ(true, res->has_header("Content-Range"));
  5675. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5676. EXPECT_EQ(std::string("cd"), res->body);
  5677. }
  5678. TEST_F(ServerTest, StaticFileRanges) {
  5679. auto res = cli_.Get("/dir/test.abcde",
  5680. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5683. EXPECT_TRUE(
  5684. res->get_header_value("Content-Type")
  5685. .find(
  5686. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5687. 0);
  5688. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5689. }
  5690. TEST_F(ServerTest, StaticFileRangeHead) {
  5691. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5693. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5694. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5695. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5696. EXPECT_EQ(true, res->has_header("Content-Range"));
  5697. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5698. }
  5699. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5700. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5703. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5704. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5705. EXPECT_EQ(true, res->has_header("Content-Range"));
  5706. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5707. res->get_header_value("Content-Range"));
  5708. EXPECT_EQ("LAST\n", res->body);
  5709. }
  5710. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5711. auto res =
  5712. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5714. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5716. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5717. EXPECT_EQ(true, res->has_header("Content-Range"));
  5718. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5719. }
  5720. TEST_F(ServerTest, StaticFileBigFile) {
  5721. auto res = cli_.Get("/dir/1MB.txt");
  5722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5723. EXPECT_EQ(StatusCode::OK_200, res->status);
  5724. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5725. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5726. }
  5727. TEST_F(ServerTest, InvalidBaseDirMount) {
  5728. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5729. }
  5730. TEST_F(ServerTest, Binary) {
  5731. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5732. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5733. "application/octet-stream");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. ASSERT_EQ(4U, res->body.size());
  5737. res = cli_.Put("/binary", binary.data(), binary.size(),
  5738. "application/octet-stream");
  5739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5740. ASSERT_EQ(StatusCode::OK_200, res->status);
  5741. ASSERT_EQ(4U, res->body.size());
  5742. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5743. "application/octet-stream");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. ASSERT_EQ(StatusCode::OK_200, res->status);
  5746. ASSERT_EQ(4U, res->body.size());
  5747. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5748. "application/octet-stream");
  5749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5750. ASSERT_EQ(StatusCode::OK_200, res->status);
  5751. ASSERT_EQ(4U, res->body.size());
  5752. }
  5753. TEST_F(ServerTest, BinaryString) {
  5754. auto binary = std::string("\x00\x01\x02\x03", 4);
  5755. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5757. ASSERT_EQ(StatusCode::OK_200, res->status);
  5758. ASSERT_EQ(4U, res->body.size());
  5759. res = cli_.Put("/binary", binary, "application/octet-stream");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ(4U, res->body.size());
  5763. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. ASSERT_EQ(StatusCode::OK_200, res->status);
  5766. ASSERT_EQ(4U, res->body.size());
  5767. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5769. ASSERT_EQ(StatusCode::OK_200, res->status);
  5770. ASSERT_EQ(4U, res->body.size());
  5771. }
  5772. TEST_F(ServerTest, EmptyRequest) {
  5773. auto res = cli_.Get("");
  5774. ASSERT_TRUE(!res);
  5775. EXPECT_EQ(Error::Connection, res.error());
  5776. }
  5777. TEST_F(ServerTest, LongRequest) {
  5778. std::string request;
  5779. for (size_t i = 0; i < 545; i++) {
  5780. request += "/TooLongRequest";
  5781. }
  5782. request += "OK";
  5783. auto res = cli_.Get(request.c_str());
  5784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5786. }
  5787. TEST_F(ServerTest, TooLongRequest) {
  5788. std::string request;
  5789. for (size_t i = 0; i < 546; i++) {
  5790. request += "/TooLongRequest";
  5791. }
  5792. request += "_NG";
  5793. auto start = std::chrono::high_resolution_clock::now();
  5794. cli_.set_keep_alive(true);
  5795. auto res = cli_.Get(request.c_str());
  5796. auto end = std::chrono::high_resolution_clock::now();
  5797. auto elapsed =
  5798. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5799. .count();
  5800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5801. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5802. EXPECT_LE(elapsed, 1000);
  5803. EXPECT_EQ("close", res->get_header_value("Connection"));
  5804. EXPECT_FALSE(cli_.is_socket_open());
  5805. }
  5806. TEST_F(ServerTest, AlmostTooLongRequest) {
  5807. // test for #2046 - URI length check shouldn't include other content on req
  5808. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5809. // leading /, space, HTTP/1.1)
  5810. std::string request =
  5811. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5812. auto res = cli_.Get(request.c_str());
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5815. }
  5816. TEST_F(ServerTest, LongHeader) {
  5817. Request req;
  5818. req.method = "GET";
  5819. req.path = "/hi";
  5820. std::string host_and_port;
  5821. host_and_port += HOST;
  5822. host_and_port += ":";
  5823. host_and_port += std::to_string(PORT);
  5824. req.headers.emplace("Host", host_and_port.c_str());
  5825. req.headers.emplace("Accept", "*/*");
  5826. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5827. req.headers.emplace(
  5828. "Header-Name",
  5829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  5859. auto error = Error::Success;
  5860. auto ret = cli_.send(req, *res, error);
  5861. ASSERT_TRUE(ret);
  5862. EXPECT_EQ(StatusCode::OK_200, res->status);
  5863. }
  5864. TEST_F(ServerTest, LongQueryValue) {
  5865. auto start = std::chrono::high_resolution_clock::now();
  5866. cli_.set_keep_alive(true);
  5867. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5868. auto end = std::chrono::high_resolution_clock::now();
  5869. auto elapsed =
  5870. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5871. .count();
  5872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5873. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5874. EXPECT_LE(elapsed, 1000);
  5875. EXPECT_EQ("close", res->get_header_value("Connection"));
  5876. EXPECT_FALSE(cli_.is_socket_open());
  5877. }
  5878. TEST_F(ServerTest, TooLongQueryValue) {
  5879. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5880. ASSERT_FALSE(res);
  5881. EXPECT_EQ(Error::Read, res.error());
  5882. }
  5883. TEST_F(ServerTest, TooLongHeader) {
  5884. Request req;
  5885. req.method = "GET";
  5886. req.path = "/hi";
  5887. std::string host_and_port;
  5888. host_and_port += HOST;
  5889. host_and_port += ":";
  5890. host_and_port += std::to_string(PORT);
  5891. req.headers.emplace("Host", host_and_port.c_str());
  5892. req.headers.emplace("Accept", "*/*");
  5893. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5894. req.headers.emplace(
  5895. "Header-Name",
  5896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  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. auto res = std::make_shared<Response>();
  5926. auto error = Error::Success;
  5927. auto ret = cli_.send(req, *res, error);
  5928. ASSERT_TRUE(ret);
  5929. EXPECT_EQ(StatusCode::OK_200, res->status);
  5930. }
  5931. TEST_F(ServerTest, HeaderCountAtLimit) {
  5932. // Test with headers just under the 100 limit
  5933. httplib::Headers headers;
  5934. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5935. // This should keep us just under the 100 header limit
  5936. for (int i = 0; i < 95; i++) {
  5937. std::string name = "X-Test-Header-" + std::to_string(i);
  5938. std::string value = "value" + std::to_string(i);
  5939. headers.emplace(name, value);
  5940. }
  5941. // This should work fine as we're under the limit
  5942. auto res = cli_.Get("/hi", headers);
  5943. EXPECT_TRUE(res);
  5944. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5945. }
  5946. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5947. // Test with many headers to exceed the 100 limit
  5948. httplib::Headers headers;
  5949. // Add 150 headers to definitely exceed the 100 limit
  5950. for (int i = 0; i < 150; i++) {
  5951. std::string name = "X-Test-Header-" + std::to_string(i);
  5952. std::string value = "value" + std::to_string(i);
  5953. headers.emplace(name, value);
  5954. }
  5955. // This should fail due to exceeding header count limit
  5956. cli_.set_keep_alive(true);
  5957. auto res = cli_.Get("/hi", headers);
  5958. // The server should respond with 400 Bad Request
  5959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5960. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5961. EXPECT_EQ("close", res->get_header_value("Connection"));
  5962. EXPECT_FALSE(cli_.is_socket_open());
  5963. }
  5964. TEST_F(ServerTest, PercentEncoding) {
  5965. auto res = cli_.Get("/e%6edwith%");
  5966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5967. EXPECT_EQ(StatusCode::OK_200, res->status);
  5968. }
  5969. TEST_F(ServerTest, PercentEncodingUnicode) {
  5970. auto res = cli_.Get("/e%u006edwith%");
  5971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5972. EXPECT_EQ(StatusCode::OK_200, res->status);
  5973. }
  5974. TEST_F(ServerTest, InvalidPercentEncoding) {
  5975. auto res = cli_.Get("/%endwith%");
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5978. }
  5979. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5980. auto res = cli_.Get("/%uendwith%");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5983. }
  5984. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5985. auto res = cli_.Get("/hello?aaa=bbb%");
  5986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5987. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5988. }
  5989. TEST_F(ServerTest, PlusSignEncoding) {
  5990. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. EXPECT_EQ("a +b", res->body);
  5994. }
  5995. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5996. // This test simulates a potential DoS attack using many headers
  5997. // to verify our security fix prevents memory exhaustion
  5998. httplib::Headers attack_headers;
  5999. // Attempt to add many headers like an attacker would (200 headers to far
  6000. // exceed limit)
  6001. for (int i = 0; i < 200; i++) {
  6002. std::string name = "X-Attack-Header-" + std::to_string(i);
  6003. std::string value = "attack_payload_" + std::to_string(i);
  6004. attack_headers.emplace(name, value);
  6005. }
  6006. // Try to POST with excessive headers
  6007. cli_.set_keep_alive(true);
  6008. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6009. // Should either fail or return 400 Bad Request due to security limit
  6010. if (res) {
  6011. // If we get a response, it should be 400 Bad Request
  6012. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6013. EXPECT_EQ("close", res->get_header_value("Connection"));
  6014. }
  6015. EXPECT_FALSE(cli_.is_socket_open());
  6016. }
  6017. TEST_F(ServerTest, MultipartFormData) {
  6018. UploadFormDataItems items = {
  6019. {"text1", "text default", "", ""},
  6020. {"text2", "aωb", "", ""},
  6021. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6022. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6023. {"file3", "", "", "application/octet-stream"},
  6024. {"file4", "", "", " application/json tmp-string "}};
  6025. auto res = cli_.Post("/multipart", items);
  6026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6027. EXPECT_EQ(StatusCode::OK_200, res->status);
  6028. }
  6029. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6030. UploadFormDataItems items = {
  6031. {"text", "default text", "", ""},
  6032. {"multi_text1", "aaaaa", "", ""},
  6033. {"multi_text1", "bbbbb", "", ""},
  6034. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6035. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6036. "application/json"},
  6037. };
  6038. auto res = cli_.Post("/multipart/multi_file_values", items);
  6039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6040. EXPECT_EQ(StatusCode::OK_200, res->status);
  6041. }
  6042. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6043. auto res = cli_.Get("/hi");
  6044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6045. EXPECT_EQ(StatusCode::OK_200, res->status);
  6046. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6047. EXPECT_EQ("Hello World!", res->body);
  6048. }
  6049. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6050. Request req;
  6051. req.method = "POST";
  6052. req.path = "/chunked";
  6053. std::string host_and_port;
  6054. host_and_port += HOST;
  6055. host_and_port += ":";
  6056. host_and_port += std::to_string(PORT);
  6057. req.headers.emplace("Host", host_and_port.c_str());
  6058. req.headers.emplace("Accept", "*/*");
  6059. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6060. req.headers.emplace("Content-Type", "text/plain");
  6061. req.headers.emplace("Content-Length", "0");
  6062. req.headers.emplace(
  6063. "Transfer-Encoding",
  6064. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6065. // Client does not chunk, so make a chunked body manually.
  6066. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6067. auto res = std::make_shared<Response>();
  6068. auto error = Error::Success;
  6069. auto ret = cli_.send(req, *res, error);
  6070. ASSERT_TRUE(ret);
  6071. EXPECT_EQ(StatusCode::OK_200, res->status);
  6072. }
  6073. template <typename ClientT>
  6074. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6075. int expected_status) {
  6076. Request req;
  6077. req.method = "POST";
  6078. req.path = "/chunked";
  6079. std::string host_and_port;
  6080. host_and_port += HOST;
  6081. host_and_port += ":";
  6082. host_and_port += std::to_string(PORT);
  6083. req.headers.emplace("Host", host_and_port.c_str());
  6084. req.headers.emplace("Content-Length", "0");
  6085. req.headers.emplace("Transfer-Encoding", "chunked");
  6086. req.body = body;
  6087. auto res = std::make_shared<Response>();
  6088. auto error = Error::Success;
  6089. ASSERT_TRUE(cli.send(req, *res, error));
  6090. EXPECT_EQ(expected_status, res->status);
  6091. }
  6092. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6093. // rather than treat them as valid lengths.
  6094. template <typename ClientT>
  6095. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6096. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6097. }
  6098. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6099. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6100. }
  6101. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6102. expect_chunked_body_rejected(
  6103. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6104. }
  6105. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6106. // chunk-size line carries no CR, LF or other control character ahead of its
  6107. // terminator. Such a line must be refused rather than read as extension text.
  6108. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6109. expect_chunked_body_rejected(
  6110. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6111. }
  6112. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6113. expect_chunked_body_rejected(
  6114. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6115. }
  6116. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6117. expect_chunked_body_rejected(
  6118. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6119. }
  6120. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6121. // The literal stays split: a hex escape consumes every hex digit that
  6122. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6123. expect_chunked_body_rejected(
  6124. cli_, "4;a\x01"
  6125. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6126. }
  6127. TEST_F(ServerTest, AcceptsChunkExtension) {
  6128. expect_chunked_body_status(cli_,
  6129. "4;name=value\r\ndech\r\n"
  6130. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6131. "0;last\r\n\r\n",
  6132. StatusCode::OK_200);
  6133. }
  6134. TEST_F(ServerTest, GetStreamed2) {
  6135. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6137. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6138. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6139. EXPECT_EQ(true, res->has_header("Content-Range"));
  6140. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6141. EXPECT_EQ(std::string("ab"), res->body);
  6142. }
  6143. TEST_F(ServerTest, GetStreamed) {
  6144. auto res = cli_.Get("/streamed");
  6145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6146. EXPECT_EQ(StatusCode::OK_200, res->status);
  6147. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6148. EXPECT_EQ(std::string("aaabbb"), res->body);
  6149. }
  6150. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6151. auto res = cli_.Get("/streamed-without-length",
  6152. Headers{make_range_header({{0, -1}})});
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ(false, res->has_header("Content-Length"));
  6156. EXPECT_EQ(false, res->has_header("Content-Range"));
  6157. EXPECT_EQ(std::string("abcdefg"), res->body);
  6158. }
  6159. TEST_F(ServerTest, GetStreamedWithRange1) {
  6160. auto res =
  6161. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6164. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6165. EXPECT_EQ(true, res->has_header("Content-Range"));
  6166. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6167. EXPECT_EQ(std::string("def"), res->body);
  6168. }
  6169. TEST_F(ServerTest, GetStreamedWithRange2) {
  6170. auto res =
  6171. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6174. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6175. EXPECT_EQ(true, res->has_header("Content-Range"));
  6176. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6177. EXPECT_EQ(std::string("bcdefg"), res->body);
  6178. }
  6179. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6180. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6183. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6184. EXPECT_EQ(true, res->has_header("Content-Range"));
  6185. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6186. EXPECT_EQ(std::string("efg"), res->body);
  6187. }
  6188. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6189. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6190. // the entire representation.
  6191. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6192. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6194. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6195. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6196. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6197. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6198. }
  6199. }
  6200. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6201. auto res =
  6202. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6205. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6206. EXPECT_EQ(false, res->has_header("Content-Range"));
  6207. EXPECT_EQ(0U, res->body.size());
  6208. }
  6209. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6210. // Only a 206 is served as a partial representation. Under any other status
  6211. // `apply_ranges()` reported the full content length, so the body must match
  6212. // that header, and the content provider must never be asked for an offset
  6213. // outside the representation.
  6214. auto check = [&](int status, const char *range) {
  6215. auto path =
  6216. std::string("/streamed-with-range?status=") + std::to_string(status);
  6217. auto ctx = path + " Range: " + range;
  6218. auto res = cli_.Get(path, Headers{{"Range", range}});
  6219. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6220. EXPECT_EQ(status, res->status) << ctx;
  6221. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6222. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6223. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6224. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6225. };
  6226. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6227. check(403, "bytes=3-5");
  6228. // The offset is far past the representation.
  6229. check(403, "bytes=100000-100200");
  6230. // `first_pos` is still -1 here, and the bounds asserts in
  6231. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6232. check(403, "bytes=-3");
  6233. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6234. // multipart branch would have written one that is empty.
  6235. check(403, "bytes=1-2, 4-5");
  6236. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6237. // covers the whole representation.
  6238. check(200, "bytes=3-5");
  6239. check(200, "bytes=1-2, 4-5");
  6240. }
  6241. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6242. auto res =
  6243. cli_.Get("/streamed-with-range",
  6244. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6245. "92233720368547758079223372036854775807"}});
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6248. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6249. EXPECT_EQ(false, res->has_header("Content-Range"));
  6250. EXPECT_EQ(0U, res->body.size());
  6251. }
  6252. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6253. auto res = cli_.Get(
  6254. "/with-range",
  6255. Headers{{"Range",
  6256. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6257. {"Accept-Encoding", ""}});
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6260. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6261. EXPECT_EQ(true, res->has_header("Content-Range"));
  6262. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6263. EXPECT_EQ(std::string("abcdefg"), res->body);
  6264. }
  6265. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6266. auto res = cli_.Get("/with-range", Headers{
  6267. {"Range", "bytes=0-"},
  6268. {"Accept-Encoding", ""},
  6269. });
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6272. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6273. EXPECT_EQ(true, res->has_header("Content-Range"));
  6274. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6275. EXPECT_EQ(std::string("abcdefg"), res->body);
  6276. }
  6277. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6278. auto res = cli_.Get("/streamed-with-range",
  6279. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6282. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6283. EXPECT_EQ(false, res->has_header("Content-Range"));
  6284. EXPECT_EQ(267U, res->body.size());
  6285. // Check that both range contents are present
  6286. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6287. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6288. // Check that Content-Range headers are present for both ranges
  6289. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6290. std::string::npos);
  6291. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6292. std::string::npos);
  6293. }
  6294. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6295. Ranges ranges;
  6296. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6297. ranges.emplace_back(0, -1);
  6298. }
  6299. auto res = cli_.Get("/streamed-with-range?error",
  6300. Headers{{make_range_header(ranges)}});
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6303. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6304. EXPECT_EQ(false, res->has_header("Content-Range"));
  6305. EXPECT_EQ(0U, res->body.size());
  6306. }
  6307. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6308. auto res = cli_.Get("/streamed-with-range",
  6309. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6311. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6312. EXPECT_EQ(5U, res->body.size());
  6313. // Check that overlapping ranges are coalesced into a single range
  6314. EXPECT_EQ("bcdef", res->body);
  6315. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6316. // Should be single range, not multipart
  6317. EXPECT_TRUE(res->has_header("Content-Range"));
  6318. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6319. }
  6320. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6321. auto res = cli_.Get("/streamed-with-range",
  6322. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6325. EXPECT_EQ(268U, res->body.size());
  6326. // Check that both range contents are present
  6327. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6328. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6329. // Check that Content-Range headers are present for both ranges
  6330. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6331. std::string::npos);
  6332. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6333. std::string::npos);
  6334. }
  6335. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6336. auto res = cli_.Get("/streamed-with-range",
  6337. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6339. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6340. EXPECT_EQ(269U, res->body.size());
  6341. // Check that both duplicate range contents are present
  6342. size_t first_abc = res->body.find("abc\r\n");
  6343. EXPECT_TRUE(first_abc != std::string::npos);
  6344. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6345. EXPECT_TRUE(second_abc != std::string::npos);
  6346. // Check that Content-Range headers are present for both ranges
  6347. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6348. EXPECT_TRUE(first_range != std::string::npos);
  6349. size_t second_range =
  6350. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6351. EXPECT_TRUE(second_range != std::string::npos);
  6352. }
  6353. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6354. auto res =
  6355. cli_.Get("/streamed-with-range?error",
  6356. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6359. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6360. EXPECT_EQ(false, res->has_header("Content-Range"));
  6361. EXPECT_EQ(0U, res->body.size());
  6362. }
  6363. TEST_F(ServerTest, GetStreamedEndless) {
  6364. uint64_t offset = 0;
  6365. auto res = cli_.Get("/streamed-cancel",
  6366. [&](const char * /*data*/, uint64_t data_length) {
  6367. if (offset < 100) {
  6368. offset += data_length;
  6369. return true;
  6370. }
  6371. return false;
  6372. });
  6373. ASSERT_TRUE(!res);
  6374. EXPECT_EQ(Error::Canceled, res.error());
  6375. }
  6376. TEST_F(ServerTest, ClientStop) {
  6377. std::atomic_size_t count{4};
  6378. std::vector<std::thread> threads;
  6379. for (auto i = count.load(); i != 0; --i) {
  6380. threads.emplace_back([&]() {
  6381. auto res = cli_.Get("/streamed-cancel",
  6382. [&](const char *, uint64_t) { return true; });
  6383. --count;
  6384. ASSERT_TRUE(!res);
  6385. EXPECT_TRUE(res.error() == Error::Canceled ||
  6386. res.error() == Error::Read || res.error() == Error::Write);
  6387. });
  6388. }
  6389. std::this_thread::sleep_for(std::chrono::seconds(2));
  6390. while (count != 0) {
  6391. cli_.stop();
  6392. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6393. }
  6394. for (auto &t : threads) {
  6395. t.join();
  6396. }
  6397. }
  6398. TEST_F(ServerTest, GetWithRange1) {
  6399. auto res = cli_.Get("/with-range", Headers{
  6400. make_range_header({{3, 5}}),
  6401. {"Accept-Encoding", ""},
  6402. });
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6405. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6406. EXPECT_EQ(true, res->has_header("Content-Range"));
  6407. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6408. EXPECT_EQ(std::string("def"), res->body);
  6409. }
  6410. TEST_F(ServerTest, GetWithRange2) {
  6411. auto res = cli_.Get("/with-range", Headers{
  6412. make_range_header({{1, -1}}),
  6413. {"Accept-Encoding", ""},
  6414. });
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6417. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6418. EXPECT_EQ(true, res->has_header("Content-Range"));
  6419. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6420. EXPECT_EQ(std::string("bcdefg"), res->body);
  6421. }
  6422. TEST_F(ServerTest, GetWithRange3) {
  6423. auto res = cli_.Get("/with-range", Headers{
  6424. make_range_header({{0, 0}}),
  6425. {"Accept-Encoding", ""},
  6426. });
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6429. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6430. EXPECT_EQ(true, res->has_header("Content-Range"));
  6431. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6432. EXPECT_EQ(std::string("a"), res->body);
  6433. }
  6434. TEST_F(ServerTest, GetWithRange4) {
  6435. auto res = cli_.Get("/with-range", Headers{
  6436. make_range_header({{-1, 2}}),
  6437. {"Accept-Encoding", ""},
  6438. });
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6441. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6442. EXPECT_EQ(true, res->has_header("Content-Range"));
  6443. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6444. EXPECT_EQ(std::string("fg"), res->body);
  6445. }
  6446. TEST_F(ServerTest, GetWithRange5) {
  6447. auto res = cli_.Get("/with-range", Headers{
  6448. make_range_header({{0, 5}}),
  6449. {"Accept-Encoding", ""},
  6450. });
  6451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6452. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6453. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6454. EXPECT_EQ(true, res->has_header("Content-Range"));
  6455. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6456. EXPECT_EQ(std::string("abcdef"), res->body);
  6457. }
  6458. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6459. auto res =
  6460. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6463. }
  6464. TEST_F(ServerTest, GetWithRangeMultipart) {
  6465. auto res =
  6466. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6469. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6470. EXPECT_EQ(false, res->has_header("Content-Range"));
  6471. EXPECT_EQ(267U, res->body.size());
  6472. }
  6473. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6474. auto res = cli_.Get("/with-range",
  6475. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6478. }
  6479. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6480. auto res = cli_.Get("/with-range-customized-response",
  6481. Headers{{make_range_header({{1, 2}})}});
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6484. EXPECT_EQ(true, res->has_header("Content-Length"));
  6485. EXPECT_EQ(false, res->has_header("Content-Range"));
  6486. EXPECT_EQ(JSON_DATA, res->body);
  6487. }
  6488. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6489. auto res = cli_.Get("/with-range-customized-response",
  6490. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6493. EXPECT_EQ(true, res->has_header("Content-Length"));
  6494. EXPECT_EQ(false, res->has_header("Content-Range"));
  6495. EXPECT_EQ(JSON_DATA, res->body);
  6496. }
  6497. TEST_F(ServerTest, Issue1772) {
  6498. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6501. }
  6502. TEST_F(ServerTest, Issue609) {
  6503. auto res = cli_.Delete("/issue609");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::OK_200, res->status);
  6506. EXPECT_EQ(std::string("ok"), res->body);
  6507. }
  6508. TEST_F(ServerTest, GetStreamedChunked) {
  6509. auto res = cli_.Get("/streamed-chunked");
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. EXPECT_EQ(std::string("123456789"), res->body);
  6513. }
  6514. TEST_F(ServerTest, GetStreamedChunked2) {
  6515. auto res = cli_.Get("/streamed-chunked2");
  6516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6517. EXPECT_EQ(StatusCode::OK_200, res->status);
  6518. EXPECT_EQ(std::string("123456789"), res->body);
  6519. }
  6520. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6521. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6523. EXPECT_EQ(StatusCode::OK_200, res->status);
  6524. EXPECT_EQ(std::string("123456789"), res->body);
  6525. EXPECT_TRUE(res->has_header("Trailer"));
  6526. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6527. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6528. // Trailers are now stored separately from headers (security fix)
  6529. EXPECT_EQ(2U, res->trailers.size());
  6530. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6531. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6532. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6533. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6534. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6535. // Verify trailers are NOT in headers (security verification)
  6536. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6537. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6538. }
  6539. TEST_F(ServerTest, LargeChunkedPost) {
  6540. Request req;
  6541. req.method = "POST";
  6542. req.path = "/large-chunked";
  6543. std::string host_and_port;
  6544. host_and_port += HOST;
  6545. host_and_port += ":";
  6546. host_and_port += std::to_string(PORT);
  6547. req.headers.emplace("Host", host_and_port.c_str());
  6548. req.headers.emplace("Accept", "*/*");
  6549. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6550. req.headers.emplace("Content-Type", "text/plain");
  6551. req.headers.emplace("Content-Length", "0");
  6552. req.headers.emplace("Transfer-Encoding", "chunked");
  6553. std::string long_string(30 * 1024u, 'a');
  6554. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6555. // Attempt to make a large enough post to exceed OS buffers, to test that
  6556. // the server handles short reads if the full chunk data isn't available.
  6557. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6558. auto res = std::make_shared<Response>();
  6559. auto error = Error::Success;
  6560. auto ret = cli_.send(req, *res, error);
  6561. ASSERT_TRUE(ret);
  6562. EXPECT_EQ(StatusCode::OK_200, res->status);
  6563. }
  6564. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6565. auto res = cli_.Get("/remote_addr");
  6566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6567. EXPECT_EQ(StatusCode::OK_200, res->status);
  6568. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6569. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6570. }
  6571. TEST_F(ServerTest, GetMethodLocalAddr) {
  6572. auto res = cli_.Get("/local_addr");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. EXPECT_EQ(StatusCode::OK_200, res->status);
  6575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6576. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6577. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6578. }
  6579. TEST_F(ServerTest, HTTPResponseSplitting) {
  6580. auto res = cli_.Get("/http_response_splitting");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ(StatusCode::OK_200, res->status);
  6583. }
  6584. TEST_F(ServerTest, SlowRequest) {
  6585. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6587. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6588. }
  6589. #if 0
  6590. TEST_F(ServerTest, SlowPost) {
  6591. char buffer[64 * 1024];
  6592. memset(buffer, 0x42, sizeof(buffer));
  6593. auto res = cli_.Post(
  6594. "/slowpost", 64 * 1024 * 1024,
  6595. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6596. auto ret = sink.write(buffer, sizeof(buffer));
  6597. EXPECT_TRUE(ret);
  6598. return true;
  6599. },
  6600. "text/plain");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::OK_200, res->status);
  6603. }
  6604. TEST_F(ServerTest, SlowPostFail) {
  6605. char buffer[64 * 1024];
  6606. memset(buffer, 0x42, sizeof(buffer));
  6607. cli_.set_write_timeout(std::chrono::seconds(0));
  6608. auto res = cli_.Post(
  6609. "/slowpost", 64 * 1024 * 1024,
  6610. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6611. sink.write(buffer, sizeof(buffer));
  6612. return true;
  6613. },
  6614. "text/plain");
  6615. ASSERT_TRUE(!res);
  6616. EXPECT_EQ(Error::Write, res.error());
  6617. }
  6618. #endif
  6619. TEST_F(ServerTest, Put) {
  6620. auto res = cli_.Put("/put", "PUT", "text/plain");
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::OK_200, res->status);
  6623. EXPECT_EQ("PUT", res->body);
  6624. }
  6625. TEST_F(ServerTest, PutWithContentProvider) {
  6626. auto res = cli_.Put(
  6627. "/put", 3,
  6628. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6629. sink.os << "PUT";
  6630. return true;
  6631. },
  6632. "text/plain");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("PUT", res->body);
  6636. }
  6637. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6638. auto res = cli_.Post(
  6639. "/post", 42,
  6640. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6641. return false;
  6642. },
  6643. "text/plain");
  6644. ASSERT_TRUE(!res);
  6645. EXPECT_EQ(Error::Canceled, res.error());
  6646. }
  6647. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6648. auto res = cli_.Put(
  6649. "/put",
  6650. [](size_t /*offset*/, DataSink &sink) {
  6651. sink.os << "PUT";
  6652. sink.done();
  6653. return true;
  6654. },
  6655. "text/plain");
  6656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6657. EXPECT_EQ(StatusCode::OK_200, res->status);
  6658. EXPECT_EQ("PUT", res->body);
  6659. }
  6660. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6661. auto res = cli_.Post(
  6662. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6663. "text/plain");
  6664. ASSERT_TRUE(!res);
  6665. EXPECT_EQ(Error::Canceled, res.error());
  6666. }
  6667. TEST_F(ServerTest, PostLoopBack) {
  6668. std::string body;
  6669. auto res = cli_.Post(
  6670. "/post-loopback", 9,
  6671. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6672. EXPECT_EQ(9u, length);
  6673. sink.write("123", 3);
  6674. sink.write("456", 3);
  6675. sink.write("789", 3);
  6676. return true;
  6677. },
  6678. "text/plain",
  6679. [&body](const char *data, size_t data_length) {
  6680. body.append(data, data_length);
  6681. return true;
  6682. });
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::OK_200, res->status);
  6685. EXPECT_EQ("123456789", body);
  6686. }
  6687. TEST_F(ServerTest, PutLoopBack) {
  6688. std::string body;
  6689. auto res = cli_.Put(
  6690. "/put-loopback", 9,
  6691. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6692. EXPECT_EQ(9u, length);
  6693. sink.write("123", 3);
  6694. sink.write("456", 3);
  6695. sink.write("789", 3);
  6696. return true;
  6697. },
  6698. "text/plain",
  6699. [&body](const char *data, size_t data_length) {
  6700. body.append(data, data_length);
  6701. return true;
  6702. });
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::OK_200, res->status);
  6705. EXPECT_EQ("123456789", body);
  6706. }
  6707. TEST_F(ServerTest, PatchLoopBack) {
  6708. std::string body;
  6709. auto res = cli_.Patch(
  6710. "/patch-loopback", 9,
  6711. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6712. EXPECT_EQ(9u, length);
  6713. sink.write("123", 3);
  6714. sink.write("456", 3);
  6715. sink.write("789", 3);
  6716. return true;
  6717. },
  6718. "text/plain",
  6719. [&body](const char *data, size_t data_length) {
  6720. body.append(data, data_length);
  6721. return true;
  6722. });
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::OK_200, res->status);
  6725. EXPECT_EQ("123456789", body);
  6726. }
  6727. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6728. std::string body;
  6729. auto res = cli_.Post(
  6730. "/post-loopback",
  6731. [](size_t /*offset*/, DataSink &sink) {
  6732. sink.write("123", 3);
  6733. sink.write("456", 3);
  6734. sink.write("789", 3);
  6735. sink.done();
  6736. return true;
  6737. },
  6738. "text/plain",
  6739. [&body](const char *data, size_t data_length) {
  6740. body.append(data, data_length);
  6741. return true;
  6742. });
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::OK_200, res->status);
  6745. EXPECT_EQ("123456789", body);
  6746. }
  6747. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6748. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6749. cli_.set_compress(true);
  6750. auto res = cli_.Put(
  6751. "/put", 3,
  6752. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6753. sink.os << "PUT";
  6754. return true;
  6755. },
  6756. "text/plain");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::OK_200, res->status);
  6759. EXPECT_EQ("PUT", res->body);
  6760. }
  6761. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6762. cli_.set_compress(true);
  6763. auto res = cli_.Post(
  6764. "/post", 42,
  6765. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6766. return false;
  6767. },
  6768. "text/plain");
  6769. ASSERT_TRUE(!res);
  6770. EXPECT_EQ(Error::Canceled, res.error());
  6771. }
  6772. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6773. cli_.set_compress(true);
  6774. auto res = cli_.Put(
  6775. "/put",
  6776. [](size_t /*offset*/, DataSink &sink) {
  6777. sink.os << "PUT";
  6778. sink.done();
  6779. return true;
  6780. },
  6781. "text/plain");
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. EXPECT_EQ(StatusCode::OK_200, res->status);
  6784. EXPECT_EQ("PUT", res->body);
  6785. }
  6786. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6787. cli_.set_compress(true);
  6788. auto res = cli_.Post(
  6789. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6790. "text/plain");
  6791. ASSERT_TRUE(!res);
  6792. EXPECT_EQ(Error::Canceled, res.error());
  6793. }
  6794. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6795. cli_.set_compress(true);
  6796. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6798. EXPECT_EQ(StatusCode::OK_200, res->status);
  6799. EXPECT_EQ(LARGE_DATA, res->body);
  6800. }
  6801. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6802. #ifdef CPPHTTPLIB_SSL_ENABLED
  6803. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6804. Client cli(s.c_str());
  6805. cli.enable_server_certificate_verification(false);
  6806. #else
  6807. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6808. Client cli(s.c_str());
  6809. #endif
  6810. cli.set_compress(true);
  6811. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ(LARGE_DATA, res->body);
  6815. // The compressed size should be less than a 10th of the original. May vary
  6816. // depending on the zlib library.
  6817. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6818. static_cast<uint64_t>(10 * 1024 * 1024));
  6819. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6820. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6821. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6822. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6823. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6824. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6825. #endif
  6826. }
  6827. TEST_F(ServerTest, PutContentWithDeflate) {
  6828. cli_.set_compress(false);
  6829. Headers headers;
  6830. headers.emplace("Content-Encoding", "deflate");
  6831. // PUT in deflate format:
  6832. auto res = cli_.Put("/put", headers,
  6833. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::OK_200, res->status);
  6836. EXPECT_EQ("PUT", res->body);
  6837. }
  6838. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6839. Headers headers;
  6840. headers.emplace("Accept-Encoding", "gzip, deflate");
  6841. auto res = cli_.Get("/streamed-chunked", headers);
  6842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6843. EXPECT_EQ(StatusCode::OK_200, res->status);
  6844. EXPECT_EQ(std::string("123456789"), res->body);
  6845. }
  6846. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6847. Headers headers;
  6848. headers.emplace("Accept-Encoding", "gzip, deflate");
  6849. auto res = cli_.Get("/streamed-chunked2", headers);
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. EXPECT_EQ(std::string("123456789"), res->body);
  6853. }
  6854. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6855. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST(GzipDecompressor, ChunkedDecompression) {
  6860. std::string data;
  6861. for (size_t i = 0; i < 32 * 1024; ++i) {
  6862. data.push_back(static_cast<char>('a' + i % 26));
  6863. }
  6864. std::string compressed_data;
  6865. {
  6866. httplib::detail::gzip_compressor compressor;
  6867. bool result = compressor.compress(
  6868. data.data(), data.size(),
  6869. /*last=*/true,
  6870. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6871. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6872. compressed_data_size);
  6873. return true;
  6874. });
  6875. ASSERT_TRUE(result);
  6876. }
  6877. std::string decompressed_data;
  6878. {
  6879. httplib::detail::gzip_decompressor decompressor;
  6880. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6881. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6882. size_t chunk_size = 130;
  6883. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6884. chunk_begin += chunk_size) {
  6885. size_t current_chunk_size =
  6886. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6887. bool result = decompressor.decompress(
  6888. compressed_data.data() + chunk_begin, current_chunk_size,
  6889. [&](const char *decompressed_data_chunk,
  6890. size_t decompressed_data_chunk_size) {
  6891. decompressed_data.insert(decompressed_data.size(),
  6892. decompressed_data_chunk,
  6893. decompressed_data_chunk_size);
  6894. return true;
  6895. });
  6896. ASSERT_TRUE(result);
  6897. }
  6898. }
  6899. ASSERT_EQ(data, decompressed_data);
  6900. }
  6901. TEST(GzipDecompressor, DeflateDecompression) {
  6902. std::string original_text = "Raw deflate without gzip";
  6903. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6904. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6905. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6906. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6907. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6908. std::string decompressed_data;
  6909. {
  6910. httplib::detail::gzip_decompressor decompressor;
  6911. bool result = decompressor.decompress(
  6912. compressed_data.data(), compressed_data.size(),
  6913. [&](const char *decompressed_data_chunk,
  6914. size_t decompressed_data_chunk_size) {
  6915. decompressed_data.insert(decompressed_data.size(),
  6916. decompressed_data_chunk,
  6917. decompressed_data_chunk_size);
  6918. return true;
  6919. });
  6920. ASSERT_TRUE(result);
  6921. }
  6922. ASSERT_EQ(original_text, decompressed_data);
  6923. }
  6924. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6925. std::string original_text = "Raw deflate without gzip";
  6926. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6927. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6928. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6929. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6930. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6931. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6932. std::string decompressed_data;
  6933. {
  6934. httplib::detail::gzip_decompressor decompressor;
  6935. bool result = decompressor.decompress(
  6936. compressed_data.data(), compressed_data.size(),
  6937. [&](const char *decompressed_data_chunk,
  6938. size_t decompressed_data_chunk_size) {
  6939. decompressed_data.insert(decompressed_data.size(),
  6940. decompressed_data_chunk,
  6941. decompressed_data_chunk_size);
  6942. return true;
  6943. });
  6944. ASSERT_TRUE(result);
  6945. }
  6946. ASSERT_EQ(original_text, decompressed_data);
  6947. }
  6948. #endif
  6949. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6950. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6951. Headers headers;
  6952. headers.emplace("Accept-Encoding", "br");
  6953. auto res = cli_.Get("/streamed-chunked", headers);
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. EXPECT_EQ(std::string("123456789"), res->body);
  6957. }
  6958. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6959. Headers headers;
  6960. headers.emplace("Accept-Encoding", "br");
  6961. auto res = cli_.Get("/streamed-chunked2", headers);
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. EXPECT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ(std::string("123456789"), res->body);
  6965. }
  6966. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6967. cli_.set_compress(true);
  6968. auto res = cli_.Put(
  6969. "/put", 3,
  6970. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6971. sink.os << "PUT";
  6972. return true;
  6973. },
  6974. "text/plain");
  6975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6976. EXPECT_EQ(StatusCode::OK_200, res->status);
  6977. EXPECT_EQ("PUT", res->body);
  6978. }
  6979. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6980. cli_.set_compress(true);
  6981. auto res = cli_.Put(
  6982. "/put",
  6983. [](size_t /*offset*/, DataSink &sink) {
  6984. sink.os << "PUT";
  6985. sink.done();
  6986. return true;
  6987. },
  6988. "text/plain");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. EXPECT_EQ(StatusCode::OK_200, res->status);
  6991. EXPECT_EQ("PUT", res->body);
  6992. }
  6993. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. EXPECT_EQ(StatusCode::OK_200, res->status);
  6998. EXPECT_EQ(LARGE_DATA, res->body);
  6999. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7000. }
  7001. #endif
  7002. TEST_F(ServerTest, Patch) {
  7003. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7005. EXPECT_EQ(StatusCode::OK_200, res->status);
  7006. EXPECT_EQ("PATCH", res->body);
  7007. }
  7008. TEST_F(ServerTest, Delete) {
  7009. auto res = cli_.Delete("/delete");
  7010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7011. EXPECT_EQ(StatusCode::OK_200, res->status);
  7012. EXPECT_EQ("DELETE", res->body);
  7013. }
  7014. TEST_F(ServerTest, DeleteContentReceiver) {
  7015. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7017. EXPECT_EQ(StatusCode::OK_200, res->status);
  7018. EXPECT_EQ("content", res->body);
  7019. }
  7020. TEST_F(ServerTest, Options) {
  7021. auto res = cli_.Options("*");
  7022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7023. EXPECT_EQ(StatusCode::OK_200, res->status);
  7024. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7025. EXPECT_TRUE(res->body.empty());
  7026. }
  7027. TEST_F(ServerTest, URL) {
  7028. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::OK_200, res->status);
  7031. }
  7032. TEST_F(ServerTest, ArrayParam) {
  7033. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, ArrayParamValues) {
  7038. auto res =
  7039. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. EXPECT_EQ(StatusCode::OK_200, res->status);
  7042. }
  7043. TEST_F(ServerTest, NoMultipleHeaders) {
  7044. Headers headers = {{"Content-Length", "5"}};
  7045. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7046. "text/plain");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. }
  7050. TEST_F(ServerTest, PostContentReceiver) {
  7051. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("content", res->body);
  7055. }
  7056. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7057. UploadFormDataItems items = {
  7058. {"text1", "text default", "", ""},
  7059. {"text2", "aωb", "", ""},
  7060. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7061. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7062. {"file3", "", "", "application/octet-stream"},
  7063. };
  7064. auto res = cli_.Post("/content_receiver", items);
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. }
  7068. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7069. UploadFormDataItems items = {
  7070. {"text1", "text default", "", ""},
  7071. {"text2", "aωb", "", ""},
  7072. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7073. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7074. {"file3", "", "", "application/octet-stream"},
  7075. };
  7076. auto boundary = std::string("+++++");
  7077. std::string body;
  7078. for (const auto &item : items) {
  7079. body += "--" + boundary + "\r\n";
  7080. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7081. if (!item.filename.empty()) {
  7082. body += "; filename=\"" + item.filename + "\"";
  7083. }
  7084. body += "\r\n";
  7085. if (!item.content_type.empty()) {
  7086. body += "Content-Type: " + item.content_type + "\r\n";
  7087. }
  7088. body += "\r\n";
  7089. body += item.content + "\r\n";
  7090. }
  7091. body += "--" + boundary + "--\r\n";
  7092. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7093. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. }
  7097. TEST(MultipartFormDataTest, FieldEscaping) {
  7098. Server svr;
  7099. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7100. const ContentReader &content_reader) {
  7101. ASSERT_TRUE(req.is_multipart_form_data());
  7102. std::vector<FormData> received;
  7103. content_reader(
  7104. [&](const FormData &file) {
  7105. received.push_back(file);
  7106. return true;
  7107. },
  7108. [&](const char *data, size_t data_length) {
  7109. received.back().content.append(data, data_length);
  7110. return true;
  7111. });
  7112. // '"', CR and LF in names and filenames are escaped following the
  7113. // WHATWG HTML standard, so each part still parses as a single part
  7114. // with no injected headers. Content types get CR/LF escaped too,
  7115. // while '"' (legal there, e.g. quoted charset) is preserved.
  7116. ASSERT_EQ(4U, received.size());
  7117. EXPECT_EQ("na%22me", received[0].name);
  7118. EXPECT_EQ("quoted name", received[0].content);
  7119. EXPECT_EQ("file", received[1].name);
  7120. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7121. received[1].filename);
  7122. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7123. EXPECT_EQ("injected", received[1].content);
  7124. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7125. EXPECT_EQ("my%22file.txt", received[2].filename);
  7126. EXPECT_EQ("cr lf name", received[2].content);
  7127. EXPECT_EQ("typed", received[3].name);
  7128. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7129. received[3].content_type);
  7130. EXPECT_EQ("typed content", received[3].content);
  7131. });
  7132. auto port = svr.bind_to_any_port("localhost");
  7133. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7134. auto se = detail::scope_exit([&] {
  7135. svr.stop();
  7136. t.join();
  7137. ASSERT_FALSE(svr.is_running());
  7138. });
  7139. svr.wait_until_ready();
  7140. Client cli("localhost", port);
  7141. UploadFormDataItems items = {
  7142. {"na\"me", "quoted name", "", ""},
  7143. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7144. "application/octet-stream"},
  7145. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7146. {"typed", "typed content", "",
  7147. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7148. };
  7149. auto res = cli.Post("/post", items);
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. }
  7153. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7154. const UploadFormDataItems items = {
  7155. {"name1", "Content 1", "", ""},
  7156. {"name2", "Content 2", "file2.txt", "text/plain"},
  7157. };
  7158. Server svr;
  7159. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7160. const ContentReader &content_reader) {
  7161. ASSERT_TRUE(req.is_multipart_form_data());
  7162. std::vector<FormData> received;
  7163. content_reader(
  7164. [&](const FormData &file) {
  7165. received.push_back(file);
  7166. return true;
  7167. },
  7168. [&](const char *data, size_t data_length) {
  7169. received.back().content.append(data, data_length);
  7170. return true;
  7171. });
  7172. ASSERT_EQ(2U, received.size());
  7173. EXPECT_EQ("name1", received[0].name);
  7174. EXPECT_EQ("Content 1", received[0].content);
  7175. EXPECT_EQ("name2", received[1].name);
  7176. EXPECT_EQ("Content 2", received[1].content);
  7177. EXPECT_EQ("file2.txt", received[1].filename);
  7178. EXPECT_EQ("text/plain", received[1].content_type);
  7179. });
  7180. auto port = svr.bind_to_any_port("localhost");
  7181. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7182. auto se = detail::scope_exit([&] {
  7183. svr.stop();
  7184. t.join();
  7185. ASSERT_FALSE(svr.is_running());
  7186. });
  7187. svr.wait_until_ready();
  7188. Client cli("localhost", port);
  7189. // Whole-body serialization with a generated boundary
  7190. {
  7191. MultipartFormDataWriter writer;
  7192. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7193. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7194. writer.content_type());
  7195. auto body = writer.serialize(items);
  7196. EXPECT_EQ(body.size(), writer.content_length(items));
  7197. auto res = cli.Post("/post", body, writer.content_type());
  7198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7199. EXPECT_EQ(StatusCode::OK_200, res->status);
  7200. }
  7201. // Per-part framing with a custom boundary via a content provider
  7202. {
  7203. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7204. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7205. MultipartFormDataWriter writer("custom-boundary_123");
  7206. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7207. std::string body;
  7208. for (const auto &item : items) {
  7209. body += writer.item_begin(item);
  7210. body += item.content;
  7211. body += MultipartFormDataWriter::item_end();
  7212. }
  7213. body += writer.finish();
  7214. EXPECT_EQ(body.size(), writer.content_length(items));
  7215. auto res = cli.Post(
  7216. "/post", body.size(),
  7217. [&](size_t offset, size_t length, DataSink &sink) {
  7218. sink.write(body.data() + offset, length);
  7219. return true;
  7220. },
  7221. writer.content_type());
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::OK_200, res->status);
  7224. }
  7225. }
  7226. TEST_F(ServerTest, PostContentReceiverGzip) {
  7227. cli_.set_compress(true);
  7228. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. ASSERT_EQ(StatusCode::OK_200, res->status);
  7231. ASSERT_EQ("content", res->body);
  7232. }
  7233. TEST_F(ServerTest, PutContentReceiver) {
  7234. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. ASSERT_EQ(StatusCode::OK_200, res->status);
  7237. ASSERT_EQ("content", res->body);
  7238. }
  7239. TEST_F(ServerTest, PatchContentReceiver) {
  7240. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. ASSERT_EQ(StatusCode::OK_200, res->status);
  7243. ASSERT_EQ("content", res->body);
  7244. }
  7245. template <typename ClientType>
  7246. void TestWithHeadersAndContentReceiver(
  7247. ClientType &cli,
  7248. std::function<Result(ClientType &, const std::string &, const Headers &,
  7249. const std::string &, const std::string &,
  7250. ContentReceiver, DownloadProgress)>
  7251. request_func) {
  7252. Headers headers;
  7253. headers.emplace("X-Custom-Header", "test-value");
  7254. std::string received_body;
  7255. auto res = request_func(
  7256. cli, "/content_receiver", headers, "content", "application/json",
  7257. [&](const char *data, size_t data_length) {
  7258. received_body.append(data, data_length);
  7259. return true;
  7260. },
  7261. nullptr);
  7262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7263. EXPECT_EQ(StatusCode::OK_200, res->status);
  7264. EXPECT_EQ("content", received_body);
  7265. }
  7266. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7267. #ifdef CPPHTTPLIB_SSL_ENABLED
  7268. using ClientT = SSLClient;
  7269. #else
  7270. using ClientT = Client;
  7271. #endif
  7272. TestWithHeadersAndContentReceiver<ClientT>(
  7273. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7274. const std::string &body, const std::string &content_type,
  7275. ContentReceiver receiver, DownloadProgress progress) {
  7276. return cli.Post(path, headers, body, content_type, receiver, progress);
  7277. });
  7278. }
  7279. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7280. #ifdef CPPHTTPLIB_SSL_ENABLED
  7281. using ClientT = SSLClient;
  7282. #else
  7283. using ClientT = Client;
  7284. #endif
  7285. TestWithHeadersAndContentReceiver<ClientT>(
  7286. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7287. const std::string &body, const std::string &content_type,
  7288. ContentReceiver receiver, DownloadProgress progress) {
  7289. return cli.Put(path, headers, body, content_type, receiver, progress);
  7290. });
  7291. }
  7292. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7293. #ifdef CPPHTTPLIB_SSL_ENABLED
  7294. using ClientT = SSLClient;
  7295. #else
  7296. using ClientT = Client;
  7297. #endif
  7298. TestWithHeadersAndContentReceiver<ClientT>(
  7299. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7300. const std::string &body, const std::string &content_type,
  7301. ContentReceiver receiver, DownloadProgress progress) {
  7302. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7303. });
  7304. }
  7305. template <typename ClientType>
  7306. void TestWithHeadersAndContentReceiverWithProgress(
  7307. ClientType &cli,
  7308. std::function<Result(ClientType &, const std::string &, const Headers &,
  7309. const std::string &, const std::string &,
  7310. ContentReceiver, DownloadProgress)>
  7311. request_func) {
  7312. Headers headers;
  7313. headers.emplace("X-Test-Header", "progress-test");
  7314. std::string received_body;
  7315. auto progress_called = false;
  7316. auto res = request_func(
  7317. cli, "/content_receiver", headers, "content", "text/plain",
  7318. [&](const char *data, size_t data_length) {
  7319. received_body.append(data, data_length);
  7320. return true;
  7321. },
  7322. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7323. progress_called = true;
  7324. return true;
  7325. });
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::OK_200, res->status);
  7328. EXPECT_EQ("content", received_body);
  7329. EXPECT_TRUE(progress_called);
  7330. }
  7331. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7332. #ifdef CPPHTTPLIB_SSL_ENABLED
  7333. using ClientT = SSLClient;
  7334. #else
  7335. using ClientT = Client;
  7336. #endif
  7337. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7338. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7339. const std::string &body, const std::string &content_type,
  7340. ContentReceiver receiver, DownloadProgress progress) {
  7341. return cli.Post(path, headers, body, content_type, receiver, progress);
  7342. });
  7343. }
  7344. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7345. #ifdef CPPHTTPLIB_SSL_ENABLED
  7346. using ClientT = SSLClient;
  7347. #else
  7348. using ClientT = Client;
  7349. #endif
  7350. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7351. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7352. const std::string &body, const std::string &content_type,
  7353. ContentReceiver receiver, DownloadProgress progress) {
  7354. return cli.Put(path, headers, body, content_type, receiver, progress);
  7355. });
  7356. }
  7357. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7358. #ifdef CPPHTTPLIB_SSL_ENABLED
  7359. using ClientT = SSLClient;
  7360. #else
  7361. using ClientT = Client;
  7362. #endif
  7363. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7364. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7365. const std::string &body, const std::string &content_type,
  7366. ContentReceiver receiver, DownloadProgress progress) {
  7367. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7368. });
  7369. }
  7370. template <typename ClientType>
  7371. void TestWithHeadersAndContentReceiverError(
  7372. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7373. const Headers &, const std::string &,
  7374. const std::string &, ContentReceiver)>
  7375. request_func) {
  7376. Headers headers;
  7377. headers.emplace("X-Error-Test", "true");
  7378. std::string received_body;
  7379. auto receiver_failed = false;
  7380. auto res =
  7381. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7382. [&](const char *data, size_t data_length) {
  7383. received_body.append(data, data_length);
  7384. receiver_failed = true;
  7385. return false;
  7386. });
  7387. ASSERT_FALSE(res);
  7388. EXPECT_TRUE(receiver_failed);
  7389. }
  7390. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7391. #ifdef CPPHTTPLIB_SSL_ENABLED
  7392. using ClientT = SSLClient;
  7393. #else
  7394. using ClientT = Client;
  7395. #endif
  7396. TestWithHeadersAndContentReceiverError<ClientT>(
  7397. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7398. const std::string &body, const std::string &content_type,
  7399. ContentReceiver receiver) {
  7400. return cli.Post(path, headers, body, content_type, receiver);
  7401. });
  7402. }
  7403. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7404. #ifdef CPPHTTPLIB_SSL_ENABLED
  7405. using ClientT = SSLClient;
  7406. #else
  7407. using ClientT = Client;
  7408. #endif
  7409. TestWithHeadersAndContentReceiverError<ClientT>(
  7410. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7411. const std::string &body, const std::string &content_type,
  7412. ContentReceiver receiver) {
  7413. return cli.Put(path, headers, body, content_type, receiver);
  7414. });
  7415. }
  7416. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7417. #ifdef CPPHTTPLIB_SSL_ENABLED
  7418. using ClientT = SSLClient;
  7419. #else
  7420. using ClientT = Client;
  7421. #endif
  7422. TestWithHeadersAndContentReceiverError<ClientT>(
  7423. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7424. const std::string &body, const std::string &content_type,
  7425. ContentReceiver receiver) {
  7426. return cli.Patch(path, headers, body, content_type, receiver);
  7427. });
  7428. }
  7429. TEST_F(ServerTest, PostQueryStringAndBody) {
  7430. auto res =
  7431. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. ASSERT_EQ(StatusCode::OK_200, res->status);
  7434. }
  7435. TEST_F(ServerTest, HTTP2Magic) {
  7436. Request req;
  7437. req.method = "PRI";
  7438. req.path = "*";
  7439. req.body = "SM";
  7440. auto res = std::make_shared<Response>();
  7441. auto error = Error::Success;
  7442. auto ret = cli_.send(req, *res, error);
  7443. ASSERT_TRUE(ret);
  7444. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7445. }
  7446. TEST_F(ServerTest, KeepAlive) {
  7447. auto res = cli_.Get("/hi");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7451. EXPECT_EQ("Hello World!", res->body);
  7452. res = cli_.Get("/hi");
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::OK_200, res->status);
  7455. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7456. EXPECT_EQ("Hello World!", res->body);
  7457. res = cli_.Get("/hi");
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::OK_200, res->status);
  7460. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7461. EXPECT_EQ("Hello World!", res->body);
  7462. res = cli_.Get("/not-exist");
  7463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7465. res = cli_.Post("/empty", "", "text/plain");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7469. EXPECT_EQ("empty", res->body);
  7470. EXPECT_EQ("close", res->get_header_value("Connection"));
  7471. res = cli_.Post(
  7472. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7473. "text/plain");
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::OK_200, res->status);
  7476. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7477. EXPECT_EQ("empty", res->body);
  7478. cli_.set_keep_alive(false);
  7479. res = cli_.Get("/last-request");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::OK_200, res->status);
  7482. EXPECT_EQ("close", res->get_header_value("Connection"));
  7483. }
  7484. TEST_F(ServerTest, TooManyRedirect) {
  7485. cli_.set_follow_location(true);
  7486. auto res = cli_.Get("/redirect/0");
  7487. ASSERT_TRUE(!res);
  7488. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7489. }
  7490. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7491. Request req;
  7492. req.method = "FOOBAR";
  7493. req.path = "/hi";
  7494. cli_.set_keep_alive(true);
  7495. auto res = cli_.send(req);
  7496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7497. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7498. EXPECT_EQ("close", res->get_header_value("Connection"));
  7499. EXPECT_FALSE(cli_.is_socket_open());
  7500. }
  7501. TEST_F(ServerTest, CustomRouteReadsBody) {
  7502. const std::string xml =
  7503. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7504. Request req;
  7505. req.method = "PROPFIND";
  7506. req.path = "/dav/dir";
  7507. req.set_header("Depth", "1");
  7508. req.body = xml;
  7509. auto res = cli_.send(req);
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7512. EXPECT_EQ(xml, res->body);
  7513. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7514. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7515. }
  7516. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7517. Request req;
  7518. req.method = "PROPFIND";
  7519. req.path = "/dav/42";
  7520. auto res = cli_.send(req);
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7523. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7524. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7525. }
  7526. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7527. Request req;
  7528. req.method = "PROPFIND";
  7529. req.path = "/dav-re/123";
  7530. auto res = cli_.send(req);
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7533. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7534. }
  7535. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7536. Request req;
  7537. req.method = "MKCOL";
  7538. req.path = "/dav-mkcol";
  7539. auto res = cli_.send(req);
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::Created_201, res->status);
  7542. }
  7543. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7544. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7545. Request req;
  7546. req.method = "REPORT";
  7547. req.path = "/dav-report";
  7548. req.body = xml;
  7549. auto res = cli_.send(req);
  7550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7551. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7552. EXPECT_EQ(xml, res->body);
  7553. }
  7554. // A content reader route must fire even when the request carries no body,
  7555. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7556. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7557. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7558. Request req;
  7559. req.method = "REPORT";
  7560. req.path = "/dav-report";
  7561. auto res = cli_.send(req);
  7562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7563. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7564. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7565. }
  7566. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7567. Request req;
  7568. req.method = "PROPFIND";
  7569. req.path = "/not-dav";
  7570. auto res = cli_.send(req);
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7573. }
  7574. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7575. Request req;
  7576. req.method = "UNLOCK";
  7577. req.path = "/dav/dir";
  7578. cli_.set_keep_alive(true);
  7579. auto res = cli_.send(req);
  7580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7581. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7582. EXPECT_EQ("close", res->get_header_value("Connection"));
  7583. EXPECT_FALSE(cli_.is_socket_open());
  7584. }
  7585. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7586. // The mount point serves this path, but only for GET and HEAD.
  7587. auto get_res = cli_.Get("/dir/index.html");
  7588. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7589. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7590. Request req;
  7591. req.method = "PROPFIND";
  7592. req.path = "/dir/index.html";
  7593. auto res = cli_.send(req);
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7596. }
  7597. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7598. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7599. cli_.set_keep_alive(true);
  7600. for (auto i = 0; i < 2; i++) {
  7601. Request req;
  7602. req.method = "PROPFIND";
  7603. req.path = "/dav/dir";
  7604. req.body = xml;
  7605. auto res = cli_.send(req);
  7606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7607. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7608. EXPECT_EQ(xml, res->body);
  7609. EXPECT_TRUE(cli_.is_socket_open());
  7610. }
  7611. // A built-in method must still be served on the same connection.
  7612. cli_.set_keep_alive(false);
  7613. auto res = cli_.Get("/hi");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("close", res->get_header_value("Connection"));
  7617. }
  7618. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7619. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7620. Request req;
  7621. req.method = "PROPFIND";
  7622. req.path = "/dav/dir";
  7623. req.set_header("Expect", "100-continue");
  7624. req.body = xml;
  7625. auto res = cli_.send(req);
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7628. EXPECT_EQ(xml, res->body);
  7629. }
  7630. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7631. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7632. TEST_F(ServerTest, Gzip) {
  7633. Headers headers;
  7634. headers.emplace("Accept-Encoding", "gzip, deflate");
  7635. auto res = cli_.Get("/compress", headers);
  7636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7637. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7638. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7639. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7640. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7641. "7890123456789012345678901234567890",
  7642. res->body);
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. }
  7645. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7646. Headers headers;
  7647. headers.emplace("Accept-Encoding", "gzip, deflate");
  7648. auto res = cli_.Get("/compress-with-charset", headers);
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7651. EXPECT_EQ("application/json; charset=utf-8",
  7652. res->get_header_value("Content-Type"));
  7653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7654. "7890123456789012345678901234567890",
  7655. res->body);
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. }
  7658. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7659. Headers headers;
  7660. headers.emplace("Accept-Encoding", "");
  7661. auto res = cli_.Get("/compress", headers);
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7664. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7665. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7667. "7890123456789012345678901234567890",
  7668. res->body);
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. }
  7671. TEST_F(ServerTest, GzipWithContentReceiver) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "gzip, deflate");
  7674. std::string body;
  7675. auto res = cli_.Get("/compress", headers,
  7676. [&](const char *data, uint64_t data_length) {
  7677. EXPECT_EQ(100U, data_length);
  7678. body.append(data, data_length);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7684. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7686. "7890123456789012345678901234567890",
  7687. body);
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. }
  7690. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7691. Headers headers;
  7692. headers.emplace("Accept-Encoding", "gzip, deflate");
  7693. cli_.set_decompress(false);
  7694. auto res = cli_.Get("/compress", headers);
  7695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7696. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7697. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7698. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7699. EXPECT_EQ(33U, res->body.size());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. }
  7702. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7703. Headers headers;
  7704. headers.emplace("Accept-Encoding", "");
  7705. std::string body;
  7706. auto res = cli_.Get("/compress", headers,
  7707. [&](const char *data, uint64_t data_length) {
  7708. EXPECT_EQ(100U, data_length);
  7709. body.append(data, data_length);
  7710. return true;
  7711. });
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7714. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7715. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7716. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7717. "7890123456789012345678901234567890",
  7718. body);
  7719. EXPECT_EQ(StatusCode::OK_200, res->status);
  7720. }
  7721. TEST_F(ServerTest, NoGzip) {
  7722. Headers headers;
  7723. headers.emplace("Accept-Encoding", "gzip, deflate");
  7724. auto res = cli_.Get("/nocompress", headers);
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7727. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7728. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7729. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7730. "7890123456789012345678901234567890",
  7731. res->body);
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. }
  7734. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7735. Headers headers;
  7736. headers.emplace("Accept-Encoding", "gzip, deflate");
  7737. std::string body;
  7738. auto res = cli_.Get("/nocompress", headers,
  7739. [&](const char *data, uint64_t data_length) {
  7740. EXPECT_EQ(100U, data_length);
  7741. body.append(data, data_length);
  7742. return true;
  7743. });
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7746. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7747. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7748. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7749. "7890123456789012345678901234567890",
  7750. body);
  7751. EXPECT_EQ(StatusCode::OK_200, res->status);
  7752. }
  7753. TEST_F(ServerTest, MultipartFormDataGzip) {
  7754. UploadFormDataItems items = {
  7755. {"key1", "test", "", ""},
  7756. {"key2", "--abcdefg123", "", ""},
  7757. };
  7758. cli_.set_compress(true);
  7759. auto res = cli_.Post("/compress-multipart", items);
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. }
  7763. #endif
  7764. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7765. // Static file compression is opt-in, so these run their own server rather than
  7766. // flipping it on for the shared ServerTest fixture, which would silently
  7767. // rewrite what every other static file test is asserting.
  7768. class StaticFileCompressionTest : public ::testing::Test {
  7769. protected:
  7770. void TearDown() override {
  7771. if (t_.joinable()) {
  7772. svr_.stop();
  7773. t_.join();
  7774. }
  7775. }
  7776. int start(const std::function<void(Server &)> &configure = nullptr) {
  7777. // Serves the same tree as a directory of build-time compressed assets
  7778. // would be served: the mount point names the coding the files are already
  7779. // stored in. Registered before "/" so it is the one that matches.
  7780. svr_.set_mount_point("/pre-encoded", "./www",
  7781. {{"Content-Encoding", "gzip"}});
  7782. svr_.set_mount_point("/", "./www");
  7783. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7784. res.set_file_content("./www/dir/index.html", "text/html");
  7785. });
  7786. svr_.Get("/pre-encoded-file-content",
  7787. [](const Request & /*req*/, Response &res) {
  7788. res.set_header("Content-Encoding", "gzip");
  7789. res.set_file_content("./www/dir/index.html", "text/html");
  7790. });
  7791. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7792. res.set_content_provider(
  7793. 6, "text/plain",
  7794. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7795. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7796. return true;
  7797. });
  7798. });
  7799. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7800. res.set_content_provider(
  7801. 1000, "text/plain",
  7802. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7803. if (offset < 100) {
  7804. std::string data(100, 'A');
  7805. sink.write(data.data(), data.size());
  7806. return true;
  7807. }
  7808. std::this_thread::sleep_for(std::chrono::seconds(2));
  7809. std::string data(900, 'B');
  7810. sink.write(data.data(), data.size());
  7811. return true;
  7812. });
  7813. });
  7814. if (configure) { configure(svr_); }
  7815. auto port = svr_.bind_to_any_port(HOST);
  7816. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7817. svr_.wait_until_ready();
  7818. return port;
  7819. }
  7820. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7821. // Every file under ./www except 1MB.txt is smaller than the default
  7822. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7823. // it out of the way.
  7824. static void enable_without_floor(Server &svr) {
  7825. svr.set_static_file_compression(true);
  7826. svr.set_static_file_compression_min_length(0);
  7827. }
  7828. Server svr_;
  7829. std::thread t_;
  7830. };
  7831. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7832. auto port = start();
  7833. Client cli(HOST, port);
  7834. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::OK_200, res->status);
  7837. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7838. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ(1048576U, res->body.size());
  7840. }
  7841. TEST_F(StaticFileCompressionTest, MountPoint) {
  7842. auto port = start(enable);
  7843. Client cli(HOST, port);
  7844. cli.set_decompress(false);
  7845. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7847. EXPECT_EQ(StatusCode::OK_200, res->status);
  7848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7849. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7850. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7851. // The response stays self-delimiting: a length, not a chunked body.
  7852. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7853. EXPECT_EQ(std::to_string(res->body.size()),
  7854. res->get_header_value("Content-Length"));
  7855. EXPECT_LT(res->body.size(), 1048576U);
  7856. EXPECT_FALSE(res->body.empty());
  7857. }
  7858. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7859. auto port = start(enable);
  7860. Client cli(HOST, port);
  7861. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7865. EXPECT_EQ(1048576U, res->body.size());
  7866. }
  7867. TEST_F(StaticFileCompressionTest, FileContent) {
  7868. auto port = start(enable_without_floor);
  7869. Client cli(HOST, port);
  7870. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::OK_200, res->status);
  7873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7874. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7875. EXPECT_EQ(104U, res->body.size());
  7876. }
  7877. // A handler that serves an already-encoded file names the coding itself. The
  7878. // file-backed path decided its coding from Accept-Encoding and the content
  7879. // type alone, so it compressed the stored bytes a second time and appended a
  7880. // second Content-Encoding field line.
  7881. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7882. auto port = start(enable_without_floor);
  7883. Client cli(HOST, port);
  7884. cli.set_decompress(false);
  7885. auto res = cli.Get("/pre-encoded-file-content",
  7886. Headers{{"Accept-Encoding", "gzip"}});
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7890. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7891. // Vary belongs to a coding the server chose, and it chose none here.
  7892. EXPECT_FALSE(res->has_header("Vary"));
  7893. // The file travels exactly as it is stored on disk.
  7894. EXPECT_EQ(104U, res->body.size());
  7895. }
  7896. // The 1MB file clears the default floor, so this one runs the configuration a
  7897. // deployment would actually have.
  7898. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7899. auto port = start(enable);
  7900. Client cli(HOST, port);
  7901. cli.set_decompress(false);
  7902. auto res =
  7903. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. EXPECT_EQ(StatusCode::OK_200, res->status);
  7906. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7907. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7908. EXPECT_FALSE(res->has_header("Vary"));
  7909. EXPECT_EQ(1048576U, res->body.size());
  7910. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7911. }
  7912. TEST_F(StaticFileCompressionTest, Head) {
  7913. auto port = start(enable);
  7914. Client cli(HOST, port);
  7915. cli.set_decompress(false);
  7916. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7917. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7918. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7920. EXPECT_EQ(StatusCode::OK_200, res->status);
  7921. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7922. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7923. // HEAD still reports the size a GET would return.
  7924. EXPECT_EQ(get->get_header_value("Content-Length"),
  7925. res->get_header_value("Content-Length"));
  7926. EXPECT_TRUE(res->body.empty());
  7927. }
  7928. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7929. auto port = start(enable);
  7930. Client cli(HOST, port);
  7931. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7932. {"Accept-Encoding", "gzip"}});
  7933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7934. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7935. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7936. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7937. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7938. EXPECT_EQ("cd", res->body);
  7939. }
  7940. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7941. auto port = start(enable);
  7942. Client cli(HOST, port);
  7943. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7947. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7948. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7949. }
  7950. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7951. auto port = start(enable);
  7952. Client cli(HOST, port);
  7953. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7957. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7958. EXPECT_TRUE(res->body.empty());
  7959. }
  7960. TEST_F(StaticFileCompressionTest, MinLength) {
  7961. auto port = start(enable);
  7962. Client cli(HOST, port);
  7963. // 104 bytes, well under the default floor. Compressing it would add the
  7964. // gzip header and trailer to a body that already fits in one packet.
  7965. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ(StatusCode::OK_200, res->status);
  7968. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7969. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7970. }
  7971. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7972. auto port = start([](Server &svr) {
  7973. svr.set_static_file_compression(true);
  7974. svr.set_static_file_compression_min_length(1);
  7975. });
  7976. Client cli(HOST, port);
  7977. cli.set_decompress(false);
  7978. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7980. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7981. // A 9-byte file comes back larger than it went in, because gzip's header and
  7982. // trailer outweigh anything deflate can save. That is the end of the range
  7983. // the floor exists to keep out.
  7984. EXPECT_GT(res->body.size(), 9U);
  7985. }
  7986. TEST_F(StaticFileCompressionTest, MaxLength) {
  7987. auto port = start([](Server &svr) {
  7988. svr.set_static_file_compression(true);
  7989. svr.set_static_file_compression_min_length(0);
  7990. svr.set_static_file_compression_max_length(1024);
  7991. });
  7992. Client cli(HOST, port);
  7993. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7994. // defines `small` as a macro on Windows.
  7995. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7996. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7997. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7998. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7999. // Under it: compressed.
  8000. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8001. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8002. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8003. }
  8004. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8005. auto port = start(enable_without_floor);
  8006. Client cli(HOST, port);
  8007. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8008. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8009. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8010. auto identity_etag = identity->get_header_value("ETag");
  8011. ASSERT_FALSE(identity_etag.empty());
  8012. auto gzipped =
  8013. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8014. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8015. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8016. auto gzip_etag = gzipped->get_header_value("ETag");
  8017. ASSERT_FALSE(gzip_etag.empty());
  8018. // Two representations, two validators.
  8019. EXPECT_NE(identity_etag, gzip_etag);
  8020. // Each one revalidates against the request that would produce it...
  8021. auto fresh =
  8022. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8023. {"If-None-Match", gzip_etag}});
  8024. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8025. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8026. auto fresh_identity =
  8027. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8028. {"If-None-Match", identity_etag}});
  8029. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8030. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8031. // ...and not against the other representation.
  8032. auto crossed =
  8033. cli.Get("/dir/index.html",
  8034. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8035. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8036. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8037. }
  8038. // The opt-in covers responses the server reads off disk itself. A caller's own
  8039. // known-length provider keeps its Content-Length and, more importantly, keeps
  8040. // delivering incrementally: routing it through a compressor would hold every
  8041. // write back until zlib's window filled.
  8042. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8043. auto port = start(enable);
  8044. Client cli(HOST, port);
  8045. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::OK_200, res->status);
  8048. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8049. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8050. EXPECT_EQ("aaabbb", res->body);
  8051. }
  8052. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8053. auto port = start(enable);
  8054. Client cli(HOST, port);
  8055. cli.set_read_timeout(1, 0);
  8056. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8057. Headers{{"Accept-Encoding", "gzip"}});
  8058. ASSERT_TRUE(handle.is_valid());
  8059. // The provider writes 100 bytes and then stalls for longer than the read
  8060. // timeout. Those first bytes have to arrive anyway: run the response through
  8061. // a compressor and zlib holds them until its window fills, so the read would
  8062. // come back empty instead.
  8063. char buf[256];
  8064. auto n = handle.read(buf, sizeof(buf));
  8065. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8066. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8067. }
  8068. #endif
  8069. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8070. TEST_F(ServerTest, Brotli) {
  8071. Headers headers;
  8072. headers.emplace("Accept-Encoding", "br");
  8073. auto res = cli_.Get("/compress", headers);
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8076. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8077. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8078. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8079. "7890123456789012345678901234567890",
  8080. res->body);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. #endif
  8084. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8085. TEST_F(ServerTest, Zstd) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "zstd");
  8088. auto res = cli_.Get("/compress", headers);
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8091. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8092. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8093. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8094. "7890123456789012345678901234567890",
  8095. res->body);
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. }
  8098. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8099. Headers headers;
  8100. headers.emplace("Accept-Encoding", "");
  8101. auto res = cli_.Get("/compress", headers);
  8102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8103. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8105. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8107. "7890123456789012345678901234567890",
  8108. res->body);
  8109. EXPECT_EQ(StatusCode::OK_200, res->status);
  8110. }
  8111. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8112. Headers headers;
  8113. headers.emplace("Accept-Encoding", "zstd");
  8114. std::string body;
  8115. auto res = cli_.Get("/compress", headers,
  8116. [&](const char *data, uint64_t data_length) {
  8117. EXPECT_EQ(100U, data_length);
  8118. body.append(data, data_length);
  8119. return true;
  8120. });
  8121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8122. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8123. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8124. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8125. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8126. "7890123456789012345678901234567890",
  8127. body);
  8128. EXPECT_EQ(StatusCode::OK_200, res->status);
  8129. }
  8130. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8131. Headers headers;
  8132. headers.emplace("Accept-Encoding", "zstd");
  8133. cli_.set_decompress(false);
  8134. auto res = cli_.Get("/compress", headers);
  8135. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8136. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8137. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8138. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8141. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8142. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8143. EXPECT_EQ(StatusCode::OK_200, res->status);
  8144. ASSERT_EQ(26U, res->body.size());
  8145. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8146. 0);
  8147. }
  8148. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8149. Headers headers;
  8150. headers.emplace("Accept-Encoding", "");
  8151. std::string body;
  8152. auto res = cli_.Get("/compress", headers,
  8153. [&](const char *data, uint64_t data_length) {
  8154. EXPECT_EQ(100U, data_length);
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8159. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8160. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8161. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8162. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8163. "7890123456789012345678901234567890",
  8164. body);
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. }
  8167. TEST_F(ServerTest, NoZstd) {
  8168. Headers headers;
  8169. headers.emplace("Accept-Encoding", "zstd");
  8170. auto res = cli_.Get("/nocompress", headers);
  8171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8172. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8173. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8174. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8175. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8176. "7890123456789012345678901234567890",
  8177. res->body);
  8178. EXPECT_EQ(StatusCode::OK_200, res->status);
  8179. }
  8180. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8181. Headers headers;
  8182. headers.emplace("Accept-Encoding", "zstd");
  8183. std::string body;
  8184. auto res = cli_.Get("/nocompress", headers,
  8185. [&](const char *data, uint64_t data_length) {
  8186. EXPECT_EQ(100U, data_length);
  8187. body.append(data, data_length);
  8188. return true;
  8189. });
  8190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8191. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8192. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8193. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8194. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8195. "7890123456789012345678901234567890",
  8196. body);
  8197. EXPECT_EQ(StatusCode::OK_200, res->status);
  8198. }
  8199. // TODO: How to enable zstd ??
  8200. TEST_F(ServerTest, MultipartFormDataZstd) {
  8201. UploadFormDataItems items = {
  8202. {"key1", "test", "", ""},
  8203. {"key2", "--abcdefg123", "", ""},
  8204. };
  8205. Headers headers;
  8206. headers.emplace("Accept-Encoding", "zstd");
  8207. cli_.set_compress(true);
  8208. auto res = cli_.Post("/compress-multipart", headers, items);
  8209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8210. EXPECT_EQ(StatusCode::OK_200, res->status);
  8211. }
  8212. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8213. Headers headers;
  8214. headers.emplace("Accept-Encoding", "zstd");
  8215. cli_.set_compress(true);
  8216. auto res = cli_.Put(
  8217. "/put", headers, 3,
  8218. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8219. sink.os << "PUT";
  8220. return true;
  8221. },
  8222. "text/plain");
  8223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8224. EXPECT_EQ(StatusCode::OK_200, res->status);
  8225. EXPECT_EQ("PUT", res->body);
  8226. }
  8227. // Pre-compression logging tests
  8228. TEST_F(ServerTest, PreCompressionLogging) {
  8229. // Test data for compression (matches the actual /compress endpoint content)
  8230. const std::string test_content =
  8231. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8232. "3456789012345678901234567890";
  8233. // Variables to capture logging data
  8234. std::string pre_compression_body;
  8235. std::string pre_compression_content_type;
  8236. std::string pre_compression_content_encoding;
  8237. std::string post_compression_body;
  8238. std::string post_compression_content_type;
  8239. std::string post_compression_content_encoding;
  8240. // Set up pre-compression logger
  8241. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8242. const Response &res) {
  8243. pre_compression_body = res.body;
  8244. pre_compression_content_type = res.get_header_value("Content-Type");
  8245. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8246. });
  8247. // Set up post-compression logger
  8248. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8249. post_compression_body = res.body;
  8250. post_compression_content_type = res.get_header_value("Content-Type");
  8251. post_compression_content_encoding =
  8252. res.get_header_value("Content-Encoding");
  8253. });
  8254. // Test with gzip compression
  8255. Headers headers;
  8256. headers.emplace("Accept-Encoding", "gzip");
  8257. auto res = cli_.Get("/compress", headers);
  8258. // Verify response was compressed
  8259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8260. EXPECT_EQ(StatusCode::OK_200, res->status);
  8261. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8262. // Verify pre-compression logger captured uncompressed content
  8263. EXPECT_EQ(test_content, pre_compression_body);
  8264. EXPECT_EQ("text/plain", pre_compression_content_type);
  8265. EXPECT_TRUE(pre_compression_content_encoding
  8266. .empty()); // No encoding header before compression
  8267. // Verify post-compression logger captured compressed content
  8268. EXPECT_NE(test_content,
  8269. post_compression_body); // Should be different after compression
  8270. EXPECT_EQ("text/plain", post_compression_content_type);
  8271. EXPECT_EQ("gzip", post_compression_content_encoding);
  8272. // Verify compressed content is smaller
  8273. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8274. }
  8275. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8276. const std::string test_content =
  8277. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8278. "3456789012345678901234567890";
  8279. std::string pre_compression_body;
  8280. std::string post_compression_body;
  8281. svr_.set_pre_compression_logger(
  8282. [&](const Request & /*req*/, const Response &res) {
  8283. pre_compression_body = res.body;
  8284. });
  8285. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8286. post_compression_body = res.body;
  8287. });
  8288. Headers headers;
  8289. headers.emplace("Accept-Encoding", "br");
  8290. auto res = cli_.Get("/compress", headers);
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8294. // Verify pre-compression content is uncompressed
  8295. EXPECT_EQ(test_content, pre_compression_body);
  8296. // Verify post-compression content is compressed
  8297. EXPECT_NE(test_content, post_compression_body);
  8298. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8299. }
  8300. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8301. const std::string test_content =
  8302. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8303. "3456789012345678901234567890";
  8304. std::string pre_compression_body;
  8305. std::string post_compression_body;
  8306. svr_.set_pre_compression_logger(
  8307. [&](const Request & /*req*/, const Response &res) {
  8308. pre_compression_body = res.body;
  8309. });
  8310. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8311. post_compression_body = res.body;
  8312. });
  8313. // Request without compression (use /nocompress endpoint)
  8314. Headers headers;
  8315. auto res = cli_.Get("/nocompress", headers);
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8319. // Pre-compression logger should not be called when no compression is applied
  8320. EXPECT_TRUE(
  8321. pre_compression_body.empty()); // Pre-compression logger not called
  8322. EXPECT_EQ(
  8323. test_content,
  8324. post_compression_body); // Post-compression logger captures final content
  8325. }
  8326. TEST_F(ServerTest, LoggerSeesContentLength) {
  8327. size_t logged_content_length = 0;
  8328. std::string logged_content_length_header;
  8329. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8330. logged_content_length = res.content_length_;
  8331. logged_content_length_header = res.get_header_value("Content-Length");
  8332. });
  8333. auto res = cli_.Get("/nocompress");
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ(StatusCode::OK_200, res->status);
  8336. EXPECT_EQ(res->body.size(), logged_content_length);
  8337. EXPECT_EQ(std::to_string(logged_content_length),
  8338. logged_content_length_header);
  8339. }
  8340. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8341. const std::string test_content =
  8342. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8343. "3456789012345678901234567890";
  8344. std::string pre_compression_body;
  8345. bool pre_logger_called = false;
  8346. // Set only pre-compression logger
  8347. svr_.set_pre_compression_logger(
  8348. [&](const Request & /*req*/, const Response &res) {
  8349. pre_compression_body = res.body;
  8350. pre_logger_called = true;
  8351. });
  8352. Headers headers;
  8353. headers.emplace("Accept-Encoding", "gzip");
  8354. auto res = cli_.Get("/compress", headers);
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8358. // Verify pre-compression logger was called
  8359. EXPECT_TRUE(pre_logger_called);
  8360. EXPECT_EQ(test_content, pre_compression_body);
  8361. }
  8362. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8363. {
  8364. // Test with Expect: 100-continue header - success case
  8365. // Server returns 100 Continue, client sends body, server returns 200 OK
  8366. Request req;
  8367. req.method = "POST";
  8368. req.path = "/post-large";
  8369. req.set_header("Expect", "100-continue");
  8370. req.body = LARGE_DATA;
  8371. Response res;
  8372. auto error = Error::Success;
  8373. cli_.set_keep_alive(true);
  8374. auto ret = cli_.send(req, res, error);
  8375. EXPECT_TRUE(ret);
  8376. EXPECT_EQ(StatusCode::OK_200, res.status);
  8377. EXPECT_EQ(LARGE_DATA, res.body);
  8378. }
  8379. {
  8380. // Test with Expect: 100-continue header - error case
  8381. // Client should not send the body when server returns an error
  8382. Request req;
  8383. req.method = "POST";
  8384. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8385. req.set_header("Expect", "100-continue");
  8386. req.body = LARGE_DATA;
  8387. Response res;
  8388. auto error = Error::Success;
  8389. auto start = std::chrono::high_resolution_clock::now();
  8390. cli_.set_keep_alive(true);
  8391. auto ret = cli_.send(req, res, error);
  8392. auto end = std::chrono::high_resolution_clock::now();
  8393. auto elapsed =
  8394. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8395. .count();
  8396. // With Expect: 100-continue, request completes successfully but with error
  8397. EXPECT_TRUE(ret);
  8398. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8399. EXPECT_EQ("close", res.get_header_value("Connection"));
  8400. EXPECT_FALSE(cli_.is_socket_open());
  8401. EXPECT_LE(elapsed, 2000);
  8402. }
  8403. {
  8404. // Send an extra GET request to ensure error recovery without hanging
  8405. Request req;
  8406. req.method = "GET";
  8407. req.path = "/hi";
  8408. auto start = std::chrono::high_resolution_clock::now();
  8409. auto res = cli_.send(req);
  8410. auto end = std::chrono::high_resolution_clock::now();
  8411. auto elapsed =
  8412. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8413. .count();
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::OK_200, res->status);
  8416. EXPECT_EQ("Hello World!", res->body);
  8417. EXPECT_LE(elapsed, 500);
  8418. }
  8419. }
  8420. TEST(ZstdDecompressor, ChunkedDecompression) {
  8421. std::string data;
  8422. for (size_t i = 0; i < 32 * 1024; ++i) {
  8423. data.push_back(static_cast<char>('a' + i % 26));
  8424. }
  8425. std::string compressed_data;
  8426. {
  8427. httplib::detail::zstd_compressor compressor;
  8428. bool result = compressor.compress(
  8429. data.data(), data.size(),
  8430. /*last=*/true,
  8431. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8432. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8433. compressed_data_size);
  8434. return true;
  8435. });
  8436. ASSERT_TRUE(result);
  8437. }
  8438. std::string decompressed_data;
  8439. {
  8440. httplib::detail::zstd_decompressor decompressor;
  8441. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8442. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8443. size_t chunk_size = 130;
  8444. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8445. chunk_begin += chunk_size) {
  8446. size_t current_chunk_size =
  8447. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8448. bool result = decompressor.decompress(
  8449. compressed_data.data() + chunk_begin, current_chunk_size,
  8450. [&](const char *decompressed_data_chunk,
  8451. size_t decompressed_data_chunk_size) {
  8452. decompressed_data.insert(decompressed_data.size(),
  8453. decompressed_data_chunk,
  8454. decompressed_data_chunk_size);
  8455. return true;
  8456. });
  8457. ASSERT_TRUE(result);
  8458. }
  8459. }
  8460. ASSERT_EQ(data, decompressed_data);
  8461. }
  8462. TEST(ZstdDecompressor, Decompress) {
  8463. std::string original_text = "Compressed with ZSTD";
  8464. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8465. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8466. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8467. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8468. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8469. std::string decompressed_data;
  8470. {
  8471. httplib::detail::zstd_decompressor decompressor;
  8472. bool result = decompressor.decompress(
  8473. compressed_data.data(), compressed_data.size(),
  8474. [&](const char *decompressed_data_chunk,
  8475. size_t decompressed_data_chunk_size) {
  8476. decompressed_data.insert(decompressed_data.size(),
  8477. decompressed_data_chunk,
  8478. decompressed_data_chunk_size);
  8479. return true;
  8480. });
  8481. ASSERT_TRUE(result);
  8482. }
  8483. ASSERT_EQ(original_text, decompressed_data);
  8484. }
  8485. #endif
  8486. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8487. // separate chunks so that the server sees each part in its own read(). Used to
  8488. // place a read boundary at a specific offset of a request body.
  8489. static bool send_request_in_parts(time_t read_timeout_sec,
  8490. const std::vector<std::string> &parts,
  8491. std::string *resp = nullptr,
  8492. int port = PORT) {
  8493. auto error = Error::Success;
  8494. auto client_sock = detail::create_client_socket(
  8495. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8496. /*connection_timeout_sec=*/5, 0,
  8497. /*read_timeout_sec=*/5, 0,
  8498. /*write_timeout_sec=*/5, 0, std::string(), error);
  8499. if (client_sock == INVALID_SOCKET) { return false; }
  8500. auto ret = detail::process_client_socket(
  8501. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8502. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8503. for (size_t i = 0; i < parts.size(); i++) {
  8504. const auto &part = parts[i];
  8505. if (part.size() !=
  8506. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8507. return false;
  8508. }
  8509. if (i + 1 < parts.size()) {
  8510. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8511. }
  8512. }
  8513. char buf[512];
  8514. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8515. while (line_reader.getline()) {
  8516. if (resp) { *resp += line_reader.ptr(); }
  8517. }
  8518. return true;
  8519. });
  8520. detail::close_socket(client_sock);
  8521. return ret;
  8522. }
  8523. // Sends a raw request to a server listening at HOST:PORT.
  8524. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8525. std::string *resp = nullptr, int port = PORT) {
  8526. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8527. }
  8528. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8529. Server svr;
  8530. std::string header_value;
  8531. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8532. header_value = req.get_header_value("foo");
  8533. res.set_content("ok", "text/plain");
  8534. });
  8535. thread t = thread([&] { svr.listen(HOST, PORT); });
  8536. auto se = detail::scope_exit([&] {
  8537. svr.stop();
  8538. t.join();
  8539. ASSERT_FALSE(svr.is_running());
  8540. });
  8541. svr.wait_until_ready();
  8542. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8543. // like characters are not treated the same - use vertical tab and escape.
  8544. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8545. "foo: \t \v bar \x1B\t \r\n"
  8546. "Connection: close\r\n"
  8547. "\r\n";
  8548. std::string res;
  8549. ASSERT_TRUE(send_request(5, req, &res));
  8550. EXPECT_EQ(header_value, "");
  8551. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8552. }
  8553. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8554. Server svr;
  8555. std::string received;
  8556. svr.Get("/order", [&](const Request &req, Response &res) {
  8557. received = entries_to_string(req.headers);
  8558. res.set_content("ok", "text/plain");
  8559. });
  8560. auto port = svr.bind_to_any_port(HOST);
  8561. thread t = thread([&] { svr.listen_after_bind(); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. t.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. const std::string req = "GET /order HTTP/1.1\r\n"
  8569. "X-First: 1\r\n"
  8570. "X-Dup: a\r\n"
  8571. "X-Second: 2\r\n"
  8572. "X-Dup: b\r\n"
  8573. "Connection: close\r\n"
  8574. "\r\n";
  8575. std::string res;
  8576. ASSERT_TRUE(send_request(5, req, &res, port));
  8577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8578. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8579. }
  8580. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8581. Server svr;
  8582. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8583. res.set_header("Set-Cookie", "first=1");
  8584. res.set_header("X-Between", "y");
  8585. res.set_header("Set-Cookie", "second=2");
  8586. res.set_content("ok", "text/plain");
  8587. });
  8588. auto port = svr.bind_to_any_port(HOST);
  8589. thread t = thread([&] { svr.listen_after_bind(); });
  8590. auto se = detail::scope_exit([&] {
  8591. svr.stop();
  8592. t.join();
  8593. ASSERT_FALSE(svr.is_running());
  8594. });
  8595. svr.wait_until_ready();
  8596. Client cli(HOST, port);
  8597. auto res = cli.Get("/cookies");
  8598. ASSERT_TRUE(res);
  8599. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8600. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8601. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8602. }
  8603. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8604. Server svr;
  8605. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8606. auto i = new int(0);
  8607. res.set_header("Trailer", "X-Safe, X-Reflected");
  8608. res.set_chunked_content_provider(
  8609. "text/plain",
  8610. [i](size_t /*offset*/, DataSink &sink) {
  8611. if (*i == 0) {
  8612. sink.os << "body";
  8613. } else {
  8614. Headers trailer;
  8615. // A valid trailer that must survive.
  8616. trailer.emplace("X-Safe", "safe");
  8617. // Attacker-controlled value carrying CR/LF (response splitting).
  8618. trailer.emplace("X-Reflected",
  8619. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8620. // Attacker-controlled name carrying CR/LF.
  8621. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8622. sink.done_with_trailer(trailer);
  8623. }
  8624. (*i)++;
  8625. return true;
  8626. },
  8627. [i](bool /*success*/) { delete i; });
  8628. });
  8629. thread t = thread([&] { svr.listen(HOST, PORT); });
  8630. auto se = detail::scope_exit([&] {
  8631. svr.stop();
  8632. t.join();
  8633. ASSERT_FALSE(svr.is_running());
  8634. });
  8635. svr.wait_until_ready();
  8636. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8637. "Host: " + HOST +
  8638. "\r\n"
  8639. "Connection: close\r\n"
  8640. "\r\n";
  8641. std::string res;
  8642. ASSERT_TRUE(send_request(5, req, &res));
  8643. // The injected fields must not appear anywhere in the raw response.
  8644. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8645. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8646. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8647. // Invalid trailers are dropped entirely, matching set_header().
  8648. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8649. // The valid trailer still passes through.
  8650. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8651. }
  8652. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8653. Server svr;
  8654. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8655. // res.headers is a public field an application can populate directly,
  8656. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8657. // A valid header that must survive.
  8658. res.headers.emplace("X-Safe", "safe");
  8659. // Attacker-controlled value carrying CR/LF (response splitting).
  8660. res.headers.emplace("X-Reflected",
  8661. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8662. // Attacker-controlled name carrying CR/LF.
  8663. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8664. res.set_content("body", "text/plain");
  8665. });
  8666. thread t = thread([&] { svr.listen(HOST, PORT); });
  8667. auto se = detail::scope_exit([&] {
  8668. svr.stop();
  8669. t.join();
  8670. ASSERT_FALSE(svr.is_running());
  8671. });
  8672. svr.wait_until_ready();
  8673. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8674. "Host: " + HOST +
  8675. "\r\n"
  8676. "Connection: close\r\n"
  8677. "\r\n";
  8678. std::string res;
  8679. ASSERT_TRUE(send_request(5, req, &res));
  8680. // The injected fields must not appear anywhere in the raw response.
  8681. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8682. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8683. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8684. // Invalid headers are dropped entirely, matching set_header().
  8685. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8686. // The valid header still passes through.
  8687. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8688. }
  8689. // Forward declaration: in split builds split.py strips `inline` and moves the
  8690. // definition into httplib.cc, so detail::write_request_line is not visible from
  8691. // the public httplib.h. Re-declaring it here lets the tests link against the
  8692. // symbol in both header-only and split builds.
  8693. namespace httplib {
  8694. namespace detail {
  8695. ssize_t write_request_line(Stream &strm, const std::string &method,
  8696. const std::string &path);
  8697. } // namespace detail
  8698. } // namespace httplib
  8699. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8700. // A well-formed target is written verbatim.
  8701. {
  8702. detail::BufferStream strm;
  8703. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8704. EXPECT_GT(n, 0);
  8705. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8706. }
  8707. // A target carrying CR/LF, SP or other control octets must be rejected
  8708. // before anything reaches the wire, otherwise it splits the request line and
  8709. // injects a header or a whole request.
  8710. const std::string evil_targets[] = {
  8711. "/a\r\nInjected: pwned",
  8712. "/a\rInjected",
  8713. "/a\nInjected",
  8714. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8715. "/a b",
  8716. "/a\tb",
  8717. "/a\x7f",
  8718. };
  8719. for (const auto &evil : evil_targets) {
  8720. detail::BufferStream strm;
  8721. auto n = detail::write_request_line(strm, "GET", evil);
  8722. EXPECT_LT(n, 0);
  8723. EXPECT_TRUE(strm.get_buffer().empty());
  8724. }
  8725. }
  8726. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8727. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8728. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8729. // target reaches write_request. The client must fail cleanly with
  8730. // Error::Write instead of putting a request-line-less, header-injecting
  8731. // request on the wire.
  8732. Server svr;
  8733. svr.Get("/a", [](const Request &, Response &res) {
  8734. res.set_content("ok", "text/plain");
  8735. });
  8736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8737. auto se = detail::scope_exit([&] {
  8738. svr.stop();
  8739. thread.join();
  8740. ASSERT_FALSE(svr.is_running());
  8741. });
  8742. svr.wait_until_ready();
  8743. {
  8744. Client cli(HOST, PORT);
  8745. cli.set_path_encode(false);
  8746. // The request is rejected before anything is written, so the connection
  8747. // stays silent and the subsequent response read would otherwise block for
  8748. // the full default read timeout. Shorten it -- the assertion is on the
  8749. // error, not the timeout.
  8750. cli.set_read_timeout(1, 0);
  8751. auto res = cli.Get("/a\r\nInjected: pwned");
  8752. EXPECT_FALSE(res);
  8753. EXPECT_EQ(Error::Write, res.error());
  8754. }
  8755. }
  8756. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8757. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8758. // including extension methods.
  8759. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8760. for (const auto &method : good_methods) {
  8761. detail::BufferStream strm;
  8762. auto n = detail::write_request_line(strm, method, "/");
  8763. EXPECT_GT(n, 0);
  8764. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8765. }
  8766. // A method carrying CR/LF would split the request line and smuggle a whole
  8767. // request ahead of the real one. A space or an empty method corrupts the
  8768. // request line. All must be rejected before anything reaches the wire.
  8769. const std::string evil_methods[] = {
  8770. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8771. "GET\r\nInjected: pwned",
  8772. "GET\r",
  8773. "GET\n",
  8774. "GE T",
  8775. "",
  8776. };
  8777. for (const auto &evil : evil_methods) {
  8778. detail::BufferStream strm;
  8779. auto n = detail::write_request_line(strm, evil, "/");
  8780. EXPECT_LT(n, 0);
  8781. EXPECT_TRUE(strm.get_buffer().empty());
  8782. }
  8783. }
  8784. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8785. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8786. // through Client::send must fail with Error::Write and no request, neither
  8787. // the smuggled one nor the real one, may reach the server.
  8788. Server svr;
  8789. std::atomic<int> request_count(0);
  8790. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8791. request_count++;
  8792. res.status = StatusCode::OK_200;
  8793. return Server::HandlerResponse::Handled;
  8794. });
  8795. auto port = svr.bind_to_any_port(HOST);
  8796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8797. auto se = detail::scope_exit([&] {
  8798. svr.stop();
  8799. thread.join();
  8800. ASSERT_FALSE(svr.is_running());
  8801. });
  8802. svr.wait_until_ready();
  8803. {
  8804. Client cli(HOST, port);
  8805. const std::string evil_methods[] = {
  8806. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8807. "GE T",
  8808. "",
  8809. };
  8810. for (const auto &evil : evil_methods) {
  8811. Request req;
  8812. req.method = evil;
  8813. req.path = "/";
  8814. auto res = cli.send(req);
  8815. EXPECT_FALSE(res);
  8816. EXPECT_EQ(Error::Write, res.error());
  8817. }
  8818. auto handle =
  8819. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8820. EXPECT_FALSE(handle.is_valid());
  8821. EXPECT_EQ(Error::Write, handle.error);
  8822. // A valid request on the same client still goes through.
  8823. auto res = cli.Get("/");
  8824. ASSERT_TRUE(res);
  8825. EXPECT_EQ(StatusCode::OK_200, res->status);
  8826. }
  8827. EXPECT_EQ(1, request_count.load());
  8828. }
  8829. // Sends a raw request and verifies that there isn't a crash or exception.
  8830. static void test_raw_request(const std::string &req,
  8831. std::string *out = nullptr) {
  8832. Server svr;
  8833. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8834. res.set_content("ok", "text/plain");
  8835. });
  8836. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8837. res.set_content("ok", "text/plain");
  8838. });
  8839. svr.Get("/header_field_value_check",
  8840. [&](const Request & /*req*/, Response &res) {
  8841. res.set_content("ok", "text/plain");
  8842. });
  8843. svr.CustomRoute("PROPFIND", "/dav",
  8844. [&](const Request & /*req*/, Response &res) {
  8845. res.status = StatusCode::MultiStatus_207;
  8846. });
  8847. // Server read timeout must be longer than the client read timeout for the
  8848. // bug to reproduce, probably to force the server to process a request
  8849. // without a trailing blank line.
  8850. const time_t client_read_timeout_sec = 1;
  8851. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8852. bool listen_thread_ok = false;
  8853. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8854. auto se = detail::scope_exit([&] {
  8855. svr.stop();
  8856. t.join();
  8857. ASSERT_FALSE(svr.is_running());
  8858. EXPECT_TRUE(listen_thread_ok);
  8859. });
  8860. svr.wait_until_ready();
  8861. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8862. }
  8863. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8864. // A certain header line causes an exception if the header property is parsed
  8865. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8866. test_raw_request(
  8867. "GET /hi HTTP/1.1\r\n"
  8868. " : "
  8869. " "
  8870. " ");
  8871. }
  8872. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8873. // A certain header line causes an exception if the header property *name* is
  8874. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8875. // greedy matcher and requires backtracking when there are a lot of ":"
  8876. // characters.
  8877. // This occurs with libc++ but not libstdc++.
  8878. test_raw_request(
  8879. "GET /hi HTTP/1.1\r\n"
  8880. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8881. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8882. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8883. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8884. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8885. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8886. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8887. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8888. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8889. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8890. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8891. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8892. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8893. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8894. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8895. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8896. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8897. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8898. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8899. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8900. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8901. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8902. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8903. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8904. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8905. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8906. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8907. "&&&%%%");
  8908. }
  8909. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8910. // Make sure this doesn't crash the server.
  8911. // In a previous version of the header line regex, the "\r" rendered the line
  8912. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8913. // a new position where the leading white space ended and the field value
  8914. // began.
  8915. // The crash occurs with libc++ but not libstdc++.
  8916. test_raw_request("GET /hi HTTP/1.1\r\n"
  8917. "a:" +
  8918. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8919. "\r\n"
  8920. "\r\n");
  8921. }
  8922. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8923. std::string out;
  8924. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8925. "Content-Type: text/plain\r\n"
  8926. "Transfer-Encoding: chunked\r\n"
  8927. "\r\n"
  8928. "nothex\r\n",
  8929. &out);
  8930. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8931. }
  8932. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8933. std::string out;
  8934. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8935. "Content-Type: text/plain\r\n"
  8936. "Transfer-Encoding: chunked\r\n"
  8937. "\r\n"
  8938. "3\r\n"
  8939. "xyz\r\n"
  8940. "NaN\r\n",
  8941. &out);
  8942. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8943. }
  8944. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8945. std::string out;
  8946. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8947. "Content-Type: text/plain\r\n"
  8948. "Transfer-Encoding: chunked\r\n"
  8949. "\r\n"
  8950. // Length is too large for 64 bits.
  8951. "1ffffffffffffffff\r\n"
  8952. "xyz\r\n",
  8953. &out);
  8954. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8955. }
  8956. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8957. test_raw_request("GET /hi HTTP/1.1\r\n"
  8958. "Content-Type: text/plain\r\n\r");
  8959. }
  8960. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8961. std::string out;
  8962. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8963. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8964. }
  8965. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8966. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8967. std::string out;
  8968. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8969. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8970. }
  8971. }
  8972. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8973. std::string out;
  8974. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8975. "Connection: close\r\n\r\n",
  8976. &out);
  8977. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8978. }
  8979. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8980. Server svr;
  8981. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8982. EXPECT_TRUE(!req.remote_addr.empty());
  8983. });
  8984. thread t = thread([&] { svr.listen(HOST, PORT); });
  8985. auto se = detail::scope_exit([&] {
  8986. svr.stop();
  8987. t.join();
  8988. ASSERT_FALSE(svr.is_running());
  8989. });
  8990. svr.wait_until_ready();
  8991. // Send an invalid request line to trigger Bad Request
  8992. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8993. std::string out;
  8994. ASSERT_TRUE(send_request(5, bad_req, &out));
  8995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8996. }
  8997. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8998. // answered right away rather than blocking on a read that waits for EOF.
  8999. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9000. std::string out;
  9001. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9002. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9003. }
  9004. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9005. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9006. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9007. for (const auto *method : methods) {
  9008. Server svr;
  9009. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9010. EXPECT_FALSE(svr.is_valid()) << method;
  9011. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9012. }
  9013. }
  9014. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9015. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9016. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9017. for (const auto *method : methods) {
  9018. Server svr;
  9019. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9020. EXPECT_FALSE(svr.is_valid()) << method;
  9021. }
  9022. }
  9023. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9024. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9025. "COPY", "MOVE", "LOCK",
  9026. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9027. Server svr;
  9028. for (const auto *method : methods) {
  9029. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9030. }
  9031. EXPECT_TRUE(svr.is_valid());
  9032. }
  9033. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9034. Server svr;
  9035. svr.CustomRoute("POST", "/x",
  9036. [](const Request &, Response &, const ContentReader &) {});
  9037. EXPECT_FALSE(svr.is_valid());
  9038. }
  9039. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9040. Server svr;
  9041. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9042. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9043. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9044. EXPECT_FALSE(svr.is_valid());
  9045. }
  9046. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9047. Server svr;
  9048. auto captured = Error::Success;
  9049. svr.set_error_logger(
  9050. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9051. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9052. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9053. }
  9054. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9055. std::string out;
  9056. std::string request(
  9057. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9058. test_raw_request(request, &out);
  9059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9060. }
  9061. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9062. std::string out;
  9063. std::string request(
  9064. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9065. test_raw_request(request, &out);
  9066. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9067. }
  9068. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9069. std::string out;
  9070. std::string request(
  9071. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9072. test_raw_request(request, &out);
  9073. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9074. }
  9075. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9076. std::string out;
  9077. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9078. "Test: \r\n\r\n",
  9079. &out);
  9080. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9081. }
  9082. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9083. Server svr;
  9084. std::string x_custom;
  9085. std::string cookie;
  9086. std::string xff;
  9087. std::string x_unicode;
  9088. std::string x_iis;
  9089. svr.Get("/check", [&](const Request &req, Response &res) {
  9090. x_custom = req.get_header_value("X-Custom");
  9091. cookie = req.get_header_value("Cookie");
  9092. xff = req.get_header_value("X-Forwarded-For");
  9093. x_unicode = req.get_header_value("X-Unicode");
  9094. x_iis = req.get_header_value("X-IIS");
  9095. res.set_content("ok", "text/plain");
  9096. });
  9097. thread t = thread([&] { svr.listen(HOST, PORT); });
  9098. auto se = detail::scope_exit([&] {
  9099. svr.stop();
  9100. t.join();
  9101. ASSERT_FALSE(svr.is_running());
  9102. });
  9103. svr.wait_until_ready();
  9104. const std::string req = "GET /check HTTP/1.1\r\n"
  9105. "Host: localhost\r\n"
  9106. "X-Custom: a%0D%0AInjected: b\r\n"
  9107. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9108. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9109. "X-Unicode: %E3%81%82\r\n"
  9110. "X-IIS: %u00E9\r\n"
  9111. "Connection: close\r\n"
  9112. "\r\n";
  9113. std::string res;
  9114. ASSERT_TRUE(send_request(5, req, &res));
  9115. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9116. // Every value must be returned verbatim (wire form), with no decoding.
  9117. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9118. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9119. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9120. EXPECT_EQ("%E3%81%82", x_unicode);
  9121. EXPECT_EQ("%u00E9", x_iis);
  9122. }
  9123. // Applications that previously relied on automatic percent-decoding can
  9124. // reproduce the old behavior by explicitly calling decode_path_component()
  9125. // or, for RFC 3986 conformance, decode_uri_component().
  9126. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9127. Server svr;
  9128. std::string decoded;
  9129. svr.Get("/check", [&](const Request &req, Response &res) {
  9130. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9131. res.set_content("ok", "text/plain");
  9132. });
  9133. thread t = thread([&] { svr.listen(HOST, PORT); });
  9134. auto se = detail::scope_exit([&] {
  9135. svr.stop();
  9136. t.join();
  9137. ASSERT_FALSE(svr.is_running());
  9138. });
  9139. svr.wait_until_ready();
  9140. const std::string req = "GET /check HTTP/1.1\r\n"
  9141. "Host: localhost\r\n"
  9142. "X-Custom: hello%20world\r\n"
  9143. "Connection: close\r\n"
  9144. "\r\n";
  9145. std::string res;
  9146. ASSERT_TRUE(send_request(5, req, &res));
  9147. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9148. EXPECT_EQ("hello world", decoded);
  9149. }
  9150. // Regression test for #2033. Browsers send Referer values that include
  9151. // percent-encoded characters such as %0A inside the URL. Decoding the
  9152. // header value would either trip the post-decode CR/LF/NUL guard (the
  9153. // original bug, returning 400) or, after that guard was relaxed, silently
  9154. // store a literal LF — both unacceptable. The wire form must round-trip.
  9155. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9156. Server svr;
  9157. std::string referer;
  9158. svr.Get("/check", [&](const Request &req, Response &res) {
  9159. referer = req.get_header_value("Referer");
  9160. res.set_content("ok", "text/plain");
  9161. });
  9162. thread t = thread([&] { svr.listen(HOST, PORT); });
  9163. auto se = detail::scope_exit([&] {
  9164. svr.stop();
  9165. t.join();
  9166. ASSERT_FALSE(svr.is_running());
  9167. });
  9168. svr.wait_until_ready();
  9169. const std::string req = "GET /check HTTP/1.1\r\n"
  9170. "Host: localhost\r\n"
  9171. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9172. "Connection: close\r\n"
  9173. "\r\n";
  9174. std::string res;
  9175. ASSERT_TRUE(send_request(5, req, &res));
  9176. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9177. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9178. }
  9179. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9180. Server svr;
  9181. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9182. res.set_header("Cache-Control", "no-cache");
  9183. res.set_chunked_content_provider(
  9184. "text/event-stream", [](size_t offset, DataSink &sink) {
  9185. std::string s = "data:";
  9186. s += std::to_string(offset);
  9187. s += "\n\n";
  9188. auto ret = sink.write(s.data(), s.size());
  9189. EXPECT_TRUE(ret);
  9190. std::this_thread::sleep_for(std::chrono::seconds(1));
  9191. return true;
  9192. });
  9193. });
  9194. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9195. svr.wait_until_ready();
  9196. Client client(HOST, PORT);
  9197. const Headers headers = {{"Accept", "text/event-stream"}};
  9198. auto get_thread = std::thread([&client, &headers]() {
  9199. auto res = client.Get(
  9200. "/events", headers,
  9201. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9202. });
  9203. auto se = detail::scope_exit([&] {
  9204. svr.stop();
  9205. get_thread.join();
  9206. listen_thread.join();
  9207. ASSERT_FALSE(svr.is_running());
  9208. });
  9209. // Give GET time to get a few messages.
  9210. std::this_thread::sleep_for(std::chrono::seconds(2));
  9211. }
  9212. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9213. httplib::Server svr;
  9214. svr.Post("/hi",
  9215. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9216. res.status = StatusCode::OK_200;
  9217. });
  9218. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9219. svr.wait_until_ready();
  9220. Client cli(HOST, PORT);
  9221. auto res = cli.Post("/hi", "data", "text/plain");
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. svr.stop();
  9225. thread.join();
  9226. ASSERT_FALSE(svr.is_running());
  9227. res = cli.Post("/hi", "data", "text/plain");
  9228. ASSERT_FALSE(res);
  9229. }
  9230. TEST(ServerStopTest, ListenFailure) {
  9231. Server svr;
  9232. auto t = thread([&]() {
  9233. auto ret = svr.listen("????", PORT);
  9234. EXPECT_FALSE(ret);
  9235. });
  9236. svr.wait_until_ready();
  9237. svr.stop();
  9238. t.join();
  9239. }
  9240. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9241. TEST(ServerStopTest, Decommision) {
  9242. Server svr;
  9243. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9244. for (int i = 0; i < 4; i++) {
  9245. auto is_even = !(i % 2);
  9246. std::thread t{[&] {
  9247. try {
  9248. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9249. if (is_even) {
  9250. throw std::runtime_error("Some thing that happens to go wrong.");
  9251. }
  9252. svr.listen(HOST, PORT);
  9253. } catch (...) { svr.decommission(); }
  9254. }};
  9255. svr.wait_until_ready();
  9256. // Server is up
  9257. {
  9258. Client cli(HOST, PORT);
  9259. auto res = cli.Get("/hi");
  9260. if (is_even) {
  9261. EXPECT_FALSE(res);
  9262. } else {
  9263. EXPECT_TRUE(res);
  9264. EXPECT_EQ("hi...", res->body);
  9265. }
  9266. }
  9267. svr.stop();
  9268. t.join();
  9269. // Server is down...
  9270. {
  9271. Client cli(HOST, PORT);
  9272. auto res = cli.Get("/hi");
  9273. EXPECT_FALSE(res);
  9274. }
  9275. }
  9276. }
  9277. #endif
  9278. // Helper function for string body upload progress tests
  9279. template <typename SetupHandler, typename ClientCall>
  9280. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9281. ClientCall &&client_call,
  9282. const string &body) {
  9283. Server svr;
  9284. setup_handler(svr);
  9285. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9286. auto se = detail::scope_exit([&] {
  9287. svr.stop();
  9288. t.join();
  9289. });
  9290. svr.wait_until_ready();
  9291. Client cli(HOST, PORT);
  9292. vector<uint64_t> progress_values;
  9293. bool progress_called = false;
  9294. auto res =
  9295. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9296. progress_values.push_back(current);
  9297. progress_called = true;
  9298. return true;
  9299. });
  9300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9301. EXPECT_EQ(200, res->status);
  9302. EXPECT_TRUE(progress_called);
  9303. }
  9304. TEST(UploadProgressTest, PostStringBodyBasic) {
  9305. TestStringBodyUploadProgress(
  9306. [](Server &svr) {
  9307. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9308. res.set_content("received", "text/plain");
  9309. });
  9310. },
  9311. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9312. return cli.Post("/test", body, "text/plain", progress_callback);
  9313. },
  9314. "test data for upload progress");
  9315. }
  9316. TEST(UploadProgressTest, PutStringBodyBasic) {
  9317. TestStringBodyUploadProgress(
  9318. [](Server &svr) {
  9319. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9320. res.set_content("put received", "text/plain");
  9321. });
  9322. },
  9323. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9324. return cli.Put("/test", body, "text/plain", progress_callback);
  9325. },
  9326. "put test data for upload progress");
  9327. }
  9328. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9329. TestStringBodyUploadProgress(
  9330. [](Server &svr) {
  9331. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9332. res.set_content("patch received", "text/plain");
  9333. });
  9334. },
  9335. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9336. return cli.Patch("/test", body, "text/plain", progress_callback);
  9337. },
  9338. "patch test data for upload progress");
  9339. }
  9340. // Helper function for content provider upload progress tests
  9341. template <typename SetupHandler, typename ClientCall>
  9342. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9343. ClientCall &&client_call) {
  9344. Server svr;
  9345. setup_handler(svr);
  9346. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9347. auto se = detail::scope_exit([&] {
  9348. svr.stop();
  9349. t.join();
  9350. });
  9351. svr.wait_until_ready();
  9352. Client cli(HOST, PORT);
  9353. vector<uint64_t> progress_values;
  9354. auto res =
  9355. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9356. progress_values.push_back(current);
  9357. return true;
  9358. });
  9359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9360. EXPECT_EQ(200, res->status);
  9361. EXPECT_FALSE(progress_values.empty());
  9362. }
  9363. TEST(UploadProgressTest, PostContentProviderProgress) {
  9364. TestContentProviderUploadProgress(
  9365. [](Server &svr) {
  9366. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9367. res.set_content("provider received", "text/plain");
  9368. });
  9369. },
  9370. [](Client &cli, UploadProgress progress_callback) {
  9371. return cli.Post(
  9372. "/test", 10,
  9373. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9374. sink.os << "test data";
  9375. return true;
  9376. },
  9377. "text/plain", progress_callback);
  9378. });
  9379. }
  9380. // Helper function for multipart upload progress tests
  9381. template <typename SetupHandler, typename ClientCall>
  9382. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9383. ClientCall &&client_call,
  9384. const string &endpoint) {
  9385. Server svr;
  9386. setup_handler(svr);
  9387. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9388. auto se = detail::scope_exit([&] {
  9389. svr.stop();
  9390. t.join();
  9391. });
  9392. svr.wait_until_ready();
  9393. Client cli(HOST, PORT);
  9394. vector<uint64_t> progress_values;
  9395. UploadFormDataItems items = {
  9396. {"field1", "value1", "", ""},
  9397. {"field2", "longer value for progress tracking test", "", ""},
  9398. {"file1", "file content data for upload progress", "test.txt",
  9399. "text/plain"}};
  9400. auto res = client_call(cli, endpoint, items,
  9401. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9402. progress_values.push_back(current);
  9403. return true;
  9404. });
  9405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9406. EXPECT_EQ(200, res->status);
  9407. EXPECT_FALSE(progress_values.empty());
  9408. }
  9409. TEST(UploadProgressTest, PostMultipartProgress) {
  9410. TestMultipartUploadProgress(
  9411. [](Server &svr) {
  9412. svr.Post("/multipart", [](const Request &req, Response &res) {
  9413. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9414. res.set_content("multipart received", "text/plain");
  9415. });
  9416. },
  9417. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9418. UploadProgress progress_callback) {
  9419. return cli.Post(endpoint, items, progress_callback);
  9420. },
  9421. "/multipart");
  9422. }
  9423. // Helper function for basic download progress tests
  9424. template <typename SetupHandler, typename ClientCall>
  9425. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9426. ClientCall &&client_call, const string &endpoint,
  9427. size_t expected_content_size) {
  9428. Server svr;
  9429. setup_handler(svr);
  9430. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9431. auto se = detail::scope_exit([&] {
  9432. svr.stop();
  9433. t.join();
  9434. });
  9435. svr.wait_until_ready();
  9436. Client cli(HOST, PORT);
  9437. vector<uint64_t> progress_values;
  9438. auto res = client_call(cli, endpoint,
  9439. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9440. progress_values.push_back(current);
  9441. return true;
  9442. });
  9443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9444. EXPECT_EQ(200, res->status);
  9445. EXPECT_FALSE(progress_values.empty());
  9446. EXPECT_EQ(expected_content_size, res->body.size());
  9447. }
  9448. TEST(DownloadProgressTest, GetBasic) {
  9449. TestBasicDownloadProgress(
  9450. [](Server &svr) {
  9451. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9452. string content(1000, 'D');
  9453. res.set_content(content, "text/plain");
  9454. });
  9455. },
  9456. [](Client &cli, const string &endpoint,
  9457. DownloadProgress progress_callback) {
  9458. return cli.Get(endpoint, progress_callback);
  9459. },
  9460. "/download", 1000u);
  9461. }
  9462. // Helper function for content receiver download progress tests
  9463. template <typename SetupHandler, typename ClientCall>
  9464. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9465. ClientCall &&client_call,
  9466. const string &endpoint,
  9467. size_t expected_content_size) {
  9468. Server svr;
  9469. setup_handler(svr);
  9470. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9471. auto se = detail::scope_exit([&] {
  9472. svr.stop();
  9473. t.join();
  9474. });
  9475. svr.wait_until_ready();
  9476. Client cli(HOST, PORT);
  9477. vector<uint64_t> progress_values;
  9478. string received_body;
  9479. auto res = client_call(
  9480. cli, endpoint,
  9481. [&](const char *data, size_t data_length) -> bool {
  9482. received_body.append(data, data_length);
  9483. return true;
  9484. },
  9485. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9486. progress_values.push_back(current);
  9487. return true;
  9488. });
  9489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9490. EXPECT_EQ(200, res->status);
  9491. EXPECT_FALSE(progress_values.empty());
  9492. EXPECT_EQ(expected_content_size, received_body.size());
  9493. EXPECT_TRUE(res->body.empty());
  9494. }
  9495. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9496. TestContentReceiverDownloadProgress(
  9497. [](Server &svr) {
  9498. svr.Get("/download-receiver",
  9499. [](const Request & /*req*/, Response &res) {
  9500. string content(2000, 'R');
  9501. res.set_content(content, "text/plain");
  9502. });
  9503. },
  9504. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9505. DownloadProgress progress_callback) {
  9506. return cli.Get(endpoint, content_receiver, progress_callback);
  9507. },
  9508. "/download-receiver", 2000u);
  9509. }
  9510. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9511. // A provider reaching a pass with nothing to hand over - an empty buffer
  9512. // popped off a queue, say - must not be taken to mean the body is finished.
  9513. // It used to end the loop with the terminating chunk unwritten while the
  9514. // server still considered the response complete, so the peer waited for an
  9515. // end that never arrived.
  9516. Server svr;
  9517. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9518. auto step = std::make_shared<int>(0);
  9519. res.set_chunked_content_provider("text/plain",
  9520. [step](size_t /*offset*/, DataSink &sink) {
  9521. switch ((*step)++) {
  9522. case 0: sink.write("", 0); break;
  9523. case 1: sink.write("hello", 5); break;
  9524. default: sink.done(); break;
  9525. }
  9526. return true;
  9527. });
  9528. });
  9529. auto port = svr.bind_to_any_port(HOST);
  9530. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9531. auto listen_se = detail::scope_exit([&] {
  9532. svr.stop();
  9533. listen_thread.join();
  9534. ASSERT_FALSE(svr.is_running());
  9535. });
  9536. svr.wait_until_ready();
  9537. Client cli(HOST, port);
  9538. // Without the fix the body is never terminated, so bound the wait rather
  9539. // than letting the test hang on the default read timeout.
  9540. cli.set_read_timeout(5, 0);
  9541. auto res = cli.Get("/stream");
  9542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9543. EXPECT_EQ(StatusCode::OK_200, res->status);
  9544. EXPECT_EQ("hello", res->body);
  9545. }
  9546. TEST(StreamingTest, NoContentLengthStreaming) {
  9547. Server svr;
  9548. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9549. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9550. if (offset < 6) {
  9551. sink.os << (offset < 3 ? "a" : "b");
  9552. } else {
  9553. sink.done();
  9554. }
  9555. return true;
  9556. });
  9557. });
  9558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9559. auto listen_se = detail::scope_exit([&] {
  9560. svr.stop();
  9561. listen_thread.join();
  9562. ASSERT_FALSE(svr.is_running());
  9563. });
  9564. svr.wait_until_ready();
  9565. Client client(HOST, PORT);
  9566. auto get_thread = std::thread([&client]() {
  9567. std::string s;
  9568. auto res =
  9569. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9570. s += std::string(data, len);
  9571. return true;
  9572. });
  9573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9574. EXPECT_EQ(StatusCode::OK_200, res->status);
  9575. EXPECT_EQ("aaabbb", s);
  9576. });
  9577. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9578. // Give GET time to get a few messages.
  9579. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9580. }
  9581. TEST(MountTest, Unmount) {
  9582. Server svr;
  9583. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9584. auto se = detail::scope_exit([&] {
  9585. svr.stop();
  9586. listen_thread.join();
  9587. ASSERT_FALSE(svr.is_running());
  9588. });
  9589. svr.wait_until_ready();
  9590. Client cli("localhost", PORT);
  9591. svr.set_mount_point("/mount2", "./www2");
  9592. auto res = cli.Get("/");
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9595. res = cli.Get("/mount2/dir/test.html");
  9596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9597. EXPECT_EQ(StatusCode::OK_200, res->status);
  9598. svr.set_mount_point("/", "./www");
  9599. res = cli.Get("/dir/");
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. EXPECT_EQ(StatusCode::OK_200, res->status);
  9602. svr.remove_mount_point("/");
  9603. res = cli.Get("/dir/");
  9604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9605. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9606. svr.remove_mount_point("/mount2");
  9607. res = cli.Get("/mount2/dir/test.html");
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9610. }
  9611. TEST(MountTest, PathSegmentBoundary) {
  9612. Server svr;
  9613. svr.set_mount_point("/mount2", "./www2");
  9614. svr.set_mount_point("/", "./www");
  9615. auto port = svr.bind_to_any_port(HOST);
  9616. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9617. auto se = detail::scope_exit([&] {
  9618. svr.stop();
  9619. listen_thread.join();
  9620. ASSERT_FALSE(svr.is_running());
  9621. });
  9622. svr.wait_until_ready();
  9623. Client cli(HOST, port);
  9624. auto res = cli.Get("/mount2/dir/test.html");
  9625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9626. EXPECT_EQ(StatusCode::OK_200, res->status);
  9627. // "/mount2" must not match part-way through a path segment.
  9628. res = cli.Get("/mount2dir/test.html");
  9629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9630. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9631. // A mount point ending in '/' keeps matching every path below it.
  9632. res = cli.Get("/dir/test.html");
  9633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9634. EXPECT_EQ(StatusCode::OK_200, res->status);
  9635. }
  9636. TEST(MountTest, Redicect) {
  9637. Server svr;
  9638. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9639. auto se = detail::scope_exit([&] {
  9640. svr.stop();
  9641. listen_thread.join();
  9642. ASSERT_FALSE(svr.is_running());
  9643. });
  9644. svr.set_mount_point("/", "./www");
  9645. svr.wait_until_ready();
  9646. Client cli("localhost", PORT);
  9647. auto res = cli.Get("/dir/");
  9648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9649. EXPECT_EQ(StatusCode::OK_200, res->status);
  9650. res = cli.Get("/dir");
  9651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9652. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9653. res = cli.Get("/file");
  9654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9655. EXPECT_EQ(StatusCode::OK_200, res->status);
  9656. res = cli.Get("/file/");
  9657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9659. cli.set_follow_location(true);
  9660. res = cli.Get("/dir");
  9661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9662. EXPECT_EQ(StatusCode::OK_200, res->status);
  9663. }
  9664. TEST(MountTest, MultibytesPathName) {
  9665. Server svr;
  9666. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9667. auto se = detail::scope_exit([&] {
  9668. svr.stop();
  9669. listen_thread.join();
  9670. ASSERT_FALSE(svr.is_running());
  9671. });
  9672. svr.set_mount_point("/", "./www");
  9673. svr.wait_until_ready();
  9674. Client cli("localhost", PORT);
  9675. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9677. EXPECT_EQ(StatusCode::OK_200, res->status);
  9678. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9679. }
  9680. #ifdef _WIN32
  9681. // Issue #2435: mmap::open() must succeed even when another handle holds
  9682. // the file open for writing (e.g. an active log file).
  9683. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9684. const char *path = "mmap_concurrent_writer_test.txt";
  9685. const char *content = "hello";
  9686. {
  9687. std::ofstream f(path, std::ios::binary);
  9688. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9689. }
  9690. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9691. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9692. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9693. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9694. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9695. detail::mmap m(path);
  9696. ASSERT_TRUE(m.is_open());
  9697. EXPECT_EQ(strlen(content), m.size());
  9698. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9699. }
  9700. #endif
  9701. #ifndef _WIN32
  9702. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9703. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9704. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9705. TEST(MmapTest, FailedMappingIsNotOpen) {
  9706. const char *path = "./mmap_failed_mapping_test_dir";
  9707. ASSERT_EQ(0, ::mkdir(path, 0755));
  9708. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9709. detail::mmap m(path);
  9710. EXPECT_FALSE(m.is_open());
  9711. EXPECT_EQ(0U, m.size());
  9712. EXPECT_NE(static_cast<const void *>(m.data()),
  9713. static_cast<const void *>(MAP_FAILED));
  9714. }
  9715. #endif
  9716. TEST(KeepAliveTest, ReadTimeout) {
  9717. Server svr;
  9718. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9719. std::this_thread::sleep_for(std::chrono::seconds(2));
  9720. res.set_content("a", "text/plain");
  9721. });
  9722. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9723. res.set_content("b", "text/plain");
  9724. });
  9725. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9726. auto se = detail::scope_exit([&] {
  9727. svr.stop();
  9728. listen_thread.join();
  9729. ASSERT_FALSE(svr.is_running());
  9730. });
  9731. svr.wait_until_ready();
  9732. Client cli("localhost", PORT);
  9733. cli.set_keep_alive(true);
  9734. cli.set_read_timeout(std::chrono::seconds(1));
  9735. auto resa = cli.Get("/a");
  9736. ASSERT_FALSE(resa);
  9737. EXPECT_EQ(Error::Read, resa.error());
  9738. auto resb = cli.Get("/b");
  9739. ASSERT_TRUE(resb);
  9740. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9741. EXPECT_EQ("b", resb->body);
  9742. }
  9743. TEST(KeepAliveTest, MaxCount) {
  9744. size_t keep_alive_max_count = 3;
  9745. Server svr;
  9746. svr.set_keep_alive_max_count(keep_alive_max_count);
  9747. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9748. res.set_content("Hello World!", "text/plain");
  9749. });
  9750. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9751. auto se = detail::scope_exit([&] {
  9752. svr.stop();
  9753. listen_thread.join();
  9754. ASSERT_FALSE(svr.is_running());
  9755. });
  9756. svr.wait_until_ready();
  9757. Client cli(HOST, PORT);
  9758. cli.set_keep_alive(true);
  9759. for (size_t i = 0; i < 5; i++) {
  9760. auto result = cli.Get("/hi");
  9761. ASSERT_TRUE(result);
  9762. EXPECT_EQ(StatusCode::OK_200, result->status);
  9763. if (i == keep_alive_max_count - 1) {
  9764. EXPECT_EQ("close", result->get_header_value("Connection"));
  9765. } else {
  9766. EXPECT_FALSE(result->has_header("Connection"));
  9767. }
  9768. }
  9769. }
  9770. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9771. // can pull the next one into the server's buffer. The server must serve it
  9772. // without waiting for the socket to become readable again. The keep-alive
  9773. // timeout outlasts the client's read timeout, so a request left waiting for it
  9774. // shows up as a missing response.
  9775. static void serve_pipelining_routes(Server &svr,
  9776. const std::function<void(int)> &client) {
  9777. svr.set_keep_alive_timeout(5);
  9778. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9779. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9780. });
  9781. svr.Post("/echo", [](const Request &req, Response &res) {
  9782. res.set_content("echo " + req.body, "text/plain");
  9783. });
  9784. auto port = svr.bind_to_any_port(HOST);
  9785. thread t = thread([&] { svr.listen_after_bind(); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. t.join();
  9789. });
  9790. svr.wait_until_ready();
  9791. client(port);
  9792. }
  9793. static std::string
  9794. send_pipelined_requests(const std::vector<std::string> &parts) {
  9795. Server svr;
  9796. std::string res;
  9797. serve_pipelining_routes(svr, [&](int port) {
  9798. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9799. });
  9800. return res;
  9801. }
  9802. static void expect_in_order(const std::string &res,
  9803. const std::vector<std::string> &bodies) {
  9804. size_t pos = 0;
  9805. for (const auto &body : bodies) {
  9806. pos = res.find(body, pos);
  9807. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9808. pos += body.size();
  9809. }
  9810. }
  9811. TEST(KeepAliveTest, PipelinedRequests) {
  9812. auto res = send_pipelined_requests(
  9813. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9814. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9815. "Content-Length: 4\r\n\r\nbody"
  9816. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9817. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9818. }
  9819. // The second request starts in the server's buffer and ends on the socket.
  9820. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9821. auto res =
  9822. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9823. "GET /hi/2 HTTP/1.1\r\nHo",
  9824. "st: localhost\r\nConnection: close\r\n\r\n"});
  9825. expect_in_order(res, {"hi 1", "hi 2"});
  9826. }
  9827. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9828. // CRLF after a body does not turn into a 400 for the next request.
  9829. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9830. auto res = send_pipelined_requests(
  9831. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9832. "Content-Length: 4\r\n\r\nbody\r\n"
  9833. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9834. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9835. expect_in_order(res, {"echo body", "hi 2"});
  9836. }
  9837. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9838. // must not be served as the next request.
  9839. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9840. auto res = send_pipelined_requests(
  9841. {"INVALID REQUEST LINE\r\n\r\n"
  9842. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9843. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9844. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9845. }
  9846. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9847. // Over TLS, the next request is held by the TLS library as already decrypted
  9848. // data rather than on the socket.
  9849. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9851. std::string res;
  9852. serve_pipelining_routes(svr, [&](int port) {
  9853. auto error = Error::Success;
  9854. auto sock = detail::create_client_socket(
  9855. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9856. /*connection_timeout_sec=*/5, 0,
  9857. /*read_timeout_sec=*/2, 0,
  9858. /*write_timeout_sec=*/5, 0, std::string(), error);
  9859. ASSERT_NE(INVALID_SOCKET, sock);
  9860. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9861. auto ctx = SSL_CTX_new(TLS_client_method());
  9862. auto ssl = SSL_new(ctx);
  9863. auto ssl_se = detail::scope_exit([&] {
  9864. SSL_free(ssl);
  9865. SSL_CTX_free(ctx);
  9866. });
  9867. SSL_set_fd(ssl, static_cast<int>(sock));
  9868. ASSERT_EQ(1, SSL_connect(ssl));
  9869. // One write, so all three requests arrive in one TLS record
  9870. const std::string req =
  9871. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9872. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9873. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9874. ASSERT_EQ(static_cast<int>(req.size()),
  9875. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9876. char buf[512];
  9877. int n;
  9878. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9879. res.append(buf, static_cast<size_t>(n));
  9880. }
  9881. });
  9882. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9883. }
  9884. #endif
  9885. TEST(KeepAliveTest, Issue1041) {
  9886. Server svr;
  9887. svr.set_keep_alive_timeout(3);
  9888. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9889. res.set_content("Hello World!", "text/plain");
  9890. });
  9891. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9892. auto se = detail::scope_exit([&] {
  9893. svr.stop();
  9894. listen_thread.join();
  9895. ASSERT_FALSE(svr.is_running());
  9896. });
  9897. svr.wait_until_ready();
  9898. Client cli(HOST, PORT);
  9899. cli.set_keep_alive(true);
  9900. auto result = cli.Get("/hi");
  9901. ASSERT_TRUE(result);
  9902. EXPECT_EQ(StatusCode::OK_200, result->status);
  9903. std::this_thread::sleep_for(std::chrono::seconds(5));
  9904. result = cli.Get("/hi");
  9905. ASSERT_TRUE(result);
  9906. EXPECT_EQ(StatusCode::OK_200, result->status);
  9907. }
  9908. TEST(KeepAliveTest, Issue1959) {
  9909. Server svr;
  9910. svr.set_keep_alive_timeout(5);
  9911. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9912. res.set_content("a", "text/plain");
  9913. });
  9914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9915. auto se = detail::scope_exit([&] {
  9916. if (!svr.is_running()) return;
  9917. svr.stop();
  9918. listen_thread.join();
  9919. ASSERT_FALSE(svr.is_running());
  9920. });
  9921. svr.wait_until_ready();
  9922. Client cli("localhost", PORT);
  9923. cli.set_keep_alive(true);
  9924. using namespace std::chrono;
  9925. auto start = steady_clock::now();
  9926. cli.Get("/a");
  9927. svr.stop();
  9928. listen_thread.join();
  9929. auto end = steady_clock::now();
  9930. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9931. EXPECT_LT(elapsed, 5000);
  9932. }
  9933. #ifdef CPPHTTPLIB_SSL_ENABLED
  9934. TEST(KeepAliveTest, SSLClientReconnection) {
  9935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9936. ASSERT_TRUE(svr.is_valid());
  9937. svr.set_keep_alive_timeout(1);
  9938. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9939. res.set_content("Hello World!", "text/plain");
  9940. });
  9941. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9942. auto se = detail::scope_exit([&] {
  9943. svr.stop();
  9944. listen_thread.join();
  9945. ASSERT_FALSE(svr.is_running());
  9946. });
  9947. svr.wait_until_ready();
  9948. SSLClient cli(HOST, PORT);
  9949. cli.enable_server_certificate_verification(false);
  9950. cli.set_keep_alive(true);
  9951. auto result = cli.Get("/hi");
  9952. ASSERT_TRUE(result);
  9953. EXPECT_EQ(StatusCode::OK_200, result->status);
  9954. result = cli.Get("/hi");
  9955. ASSERT_TRUE(result);
  9956. EXPECT_EQ(StatusCode::OK_200, result->status);
  9957. std::this_thread::sleep_for(std::chrono::seconds(2));
  9958. // Recoonect
  9959. result = cli.Get("/hi");
  9960. ASSERT_TRUE(result);
  9961. EXPECT_EQ(StatusCode::OK_200, result->status);
  9962. result = cli.Get("/hi");
  9963. ASSERT_TRUE(result);
  9964. EXPECT_EQ(StatusCode::OK_200, result->status);
  9965. }
  9966. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9968. ASSERT_TRUE(svr.is_valid());
  9969. svr.set_keep_alive_timeout(1);
  9970. std::string content = "reconnect";
  9971. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9972. res.set_content("Hello World!", "text/plain");
  9973. });
  9974. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. listen_thread.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. SSLClient cli(HOST, PORT);
  9982. cli.enable_server_certificate_verification(false);
  9983. cli.set_keep_alive(true);
  9984. auto result = cli.Post(
  9985. "/hi", content.size(),
  9986. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9987. sink.write(content.c_str(), content.size());
  9988. return true;
  9989. },
  9990. "text/plain");
  9991. ASSERT_TRUE(result);
  9992. EXPECT_EQ(200, result->status);
  9993. std::this_thread::sleep_for(std::chrono::seconds(2));
  9994. // Recoonect
  9995. result = cli.Post(
  9996. "/hi", content.size(),
  9997. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9998. sink.write(content.c_str(), content.size());
  9999. return true;
  10000. },
  10001. "text/plain");
  10002. ASSERT_TRUE(result);
  10003. EXPECT_EQ(200, result->status);
  10004. result = cli.Post(
  10005. "/hi", content.size(),
  10006. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10007. sink.write(content.c_str(), content.size());
  10008. return true;
  10009. },
  10010. "text/plain");
  10011. ASSERT_TRUE(result);
  10012. EXPECT_EQ(200, result->status);
  10013. }
  10014. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10015. using namespace httplib::tls;
  10016. {
  10017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10018. ASSERT_TRUE(svr.is_valid());
  10019. svr.Get("/sni", [&](const Request &req, Response &res) {
  10020. std::string expected = req.sni();
  10021. EXPECT_EQ(expected, req.get_param_value("expected"));
  10022. res.set_content("ok", "text/plain");
  10023. });
  10024. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10025. auto se = detail::scope_exit([&] {
  10026. svr.stop();
  10027. listen_thread.join();
  10028. ASSERT_FALSE(svr.is_running());
  10029. });
  10030. svr.wait_until_ready();
  10031. {
  10032. SSLClient cli("localhost", PORT);
  10033. cli.enable_server_certificate_verification(false);
  10034. auto res = cli.Get("/sni?expected=localhost");
  10035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10036. }
  10037. {
  10038. SSLClient cli("::1", PORT);
  10039. cli.enable_server_certificate_verification(false);
  10040. auto res = cli.Get("/sni?expected=");
  10041. // NOTE: This may fail if the server is listening on IPv4 only
  10042. // (e.g., when localhost resolves to 127.0.0.1 only)
  10043. if (res) {
  10044. EXPECT_EQ(StatusCode::OK_200, res->status);
  10045. } else {
  10046. EXPECT_EQ(Error::Connection, res.error());
  10047. }
  10048. }
  10049. }
  10050. }
  10051. #endif
  10052. TEST(ClientProblemDetectionTest, ContentProvider) {
  10053. Server svr;
  10054. size_t content_length = 1024 * 1024;
  10055. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10056. res.set_content_provider(
  10057. content_length, "text/plain",
  10058. [&](size_t offset, size_t length, DataSink &sink) {
  10059. auto out_len = std::min(length, static_cast<size_t>(1024));
  10060. std::string out(out_len, '@');
  10061. sink.write(out.data(), out_len);
  10062. return offset < 4096;
  10063. },
  10064. [](bool success) { ASSERT_FALSE(success); });
  10065. });
  10066. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10067. res.set_content_provider(
  10068. 0, "text/plain",
  10069. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10070. EXPECT_TRUE(false);
  10071. return true;
  10072. },
  10073. [](bool success) { ASSERT_FALSE(success); });
  10074. });
  10075. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10076. auto se = detail::scope_exit([&] {
  10077. svr.stop();
  10078. listen_thread.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. svr.wait_until_ready();
  10082. Client cli("localhost", PORT);
  10083. {
  10084. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10085. size_t /*data_length*/) { return false; });
  10086. ASSERT_FALSE(res);
  10087. }
  10088. {
  10089. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10090. size_t /*data_length*/) { return false; });
  10091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10092. }
  10093. }
  10094. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10095. // A provider that reports success without writing anything and without
  10096. // calling done() used to be handed the same offset and length again on every
  10097. // pass, so it spun for as long as the peer stayed connected.
  10098. Server svr;
  10099. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10100. res.set_content("ok", "text/plain");
  10101. });
  10102. auto port = svr.bind_to_any_port(HOST);
  10103. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10104. auto se = detail::scope_exit([&] {
  10105. svr.stop();
  10106. listen_thread.join();
  10107. ASSERT_FALSE(svr.is_running());
  10108. });
  10109. svr.wait_until_ready();
  10110. std::atomic<int> call_count{0};
  10111. Client cli(HOST, port);
  10112. auto res = cli.Post(
  10113. "/", 1024,
  10114. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10115. // Give up after enough passes to show the spin, so that losing the
  10116. // check below fails this test instead of hanging it.
  10117. return ++call_count < 100;
  10118. },
  10119. "text/plain");
  10120. ASSERT_FALSE(res);
  10121. EXPECT_EQ(Error::Write, res.error());
  10122. EXPECT_EQ(1, call_count.load());
  10123. }
  10124. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10125. // A writer only has to assign `write`. The other three used to be left as
  10126. // empty std::functions, so a provider calling one threw
  10127. // std::bad_function_call out of the thread running it and took the whole
  10128. // process down.
  10129. DataSink sink;
  10130. std::string written;
  10131. sink.write = [&](const char *data, size_t data_len) {
  10132. written.append(data, data_len);
  10133. return true;
  10134. };
  10135. EXPECT_TRUE(sink.is_writable());
  10136. sink.done();
  10137. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10138. EXPECT_TRUE(written.empty());
  10139. }
  10140. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10141. // A sink that cannot carry trailers still has to finish.
  10142. DataSink sink;
  10143. auto done_count = 0;
  10144. sink.done = [&]() { done_count++; };
  10145. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10146. EXPECT_EQ(1, done_count);
  10147. }
  10148. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10149. Server svr;
  10150. const std::string body(4096, 'x');
  10151. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10152. res.set_content_provider(body.size(), "text/plain",
  10153. [&](size_t offset, size_t length, DataSink &sink) {
  10154. sink.write(body.data() + offset, length);
  10155. sink.done();
  10156. return true;
  10157. });
  10158. });
  10159. auto port = svr.bind_to_any_port(HOST);
  10160. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10161. auto se = detail::scope_exit([&] {
  10162. svr.stop();
  10163. listen_thread.join();
  10164. ASSERT_FALSE(svr.is_running());
  10165. });
  10166. svr.wait_until_ready();
  10167. Client cli(HOST, port);
  10168. auto res = cli.Get("/");
  10169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10170. EXPECT_EQ(StatusCode::OK_200, res->status);
  10171. EXPECT_EQ(body, res->body);
  10172. }
  10173. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10174. Server svr;
  10175. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10176. res.set_content_provider(
  10177. 1024, "text/plain",
  10178. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10179. sink.write("hello", 5);
  10180. sink.done(); // short of the 1024 bytes the response promised
  10181. return true;
  10182. });
  10183. });
  10184. auto port = svr.bind_to_any_port(HOST);
  10185. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10186. auto se = detail::scope_exit([&] {
  10187. svr.stop();
  10188. listen_thread.join();
  10189. ASSERT_FALSE(svr.is_running());
  10190. });
  10191. svr.wait_until_ready();
  10192. Client cli(HOST, port);
  10193. cli.set_read_timeout(5, 0);
  10194. // The response is short of its Content-Length, so the client cannot read a
  10195. // complete body. What matters is that this returns at all: a no-op done()
  10196. // would leave the writer looping over a provider that never makes progress.
  10197. auto res = cli.Get("/");
  10198. EXPECT_FALSE(res);
  10199. }
  10200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10201. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10202. // The compressed path builds the whole body before connecting, so this
  10203. // fails client-side and never reaches a server.
  10204. Client cli(HOST, PORT);
  10205. cli.set_compress(true);
  10206. auto res = cli.Post(
  10207. "/", 1024,
  10208. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10209. sink.write("hello", 5);
  10210. sink.done(); // short of the 1024 bytes the request announced
  10211. return true;
  10212. },
  10213. "text/plain");
  10214. ASSERT_FALSE(res);
  10215. EXPECT_EQ(Error::Write, res.error());
  10216. }
  10217. #endif
  10218. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10219. Server svr;
  10220. svr.set_error_handler([](Request const &, Response &res) -> void {
  10221. res.set_chunked_content_provider(
  10222. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10223. sink.os << "hello";
  10224. sink.os << "world";
  10225. sink.done();
  10226. return true;
  10227. });
  10228. });
  10229. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10230. auto se = detail::scope_exit([&] {
  10231. svr.stop();
  10232. listen_thread.join();
  10233. ASSERT_FALSE(svr.is_running());
  10234. });
  10235. svr.wait_until_ready();
  10236. Client cli("localhost", PORT);
  10237. auto res = cli.Get("/");
  10238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10239. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10240. EXPECT_EQ("helloworld", res->body);
  10241. }
  10242. // A body set after a content provider must replace it, not be sent through it.
  10243. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10244. Server svr;
  10245. svr.set_mount_point("/", "./www");
  10246. svr.set_file_request_handler([](const Request &req, Response &res) {
  10247. if (req.path == "/dir/test.html") {
  10248. res.status = StatusCode::Forbidden_403;
  10249. res.set_content(std::string(5000, 'D'), "text/plain");
  10250. } else if (req.path == "/file") {
  10251. res.status = StatusCode::Forbidden_403;
  10252. res.body = "Denied";
  10253. }
  10254. });
  10255. auto port = svr.bind_to_any_port(HOST);
  10256. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10257. auto se = detail::scope_exit([&] {
  10258. svr.stop();
  10259. t.join();
  10260. ASSERT_FALSE(svr.is_running());
  10261. });
  10262. svr.wait_until_ready();
  10263. Client cli(HOST, port);
  10264. {
  10265. auto res = cli.Get("/dir/test.html");
  10266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10267. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10268. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10269. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10270. }
  10271. {
  10272. auto res = cli.Get("/file");
  10273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10274. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10275. EXPECT_EQ("Denied", res->body);
  10276. }
  10277. {
  10278. auto res = cli.Get("/dir/index.html");
  10279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10280. EXPECT_EQ(StatusCode::OK_200, res->status);
  10281. EXPECT_EQ(0U, res->body.find("<html>"));
  10282. }
  10283. }
  10284. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10285. Server svr;
  10286. std::vector<bool> released;
  10287. std::mutex released_mutex;
  10288. auto releaser = [&](bool success) {
  10289. std::lock_guard<std::mutex> guard(released_mutex);
  10290. released.push_back(success);
  10291. };
  10292. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10293. return sink.write(&"hello"[offset], length);
  10294. };
  10295. svr.Get("/sized", [&](const Request &, Response &res) {
  10296. res.status = StatusCode::NotFound_404;
  10297. res.set_content_provider(5, "text/plain", provider, releaser);
  10298. });
  10299. svr.Get("/chunked", [&](const Request &, Response &res) {
  10300. res.status = StatusCode::ServiceUnavailable_503;
  10301. res.set_chunked_content_provider(
  10302. "text/plain",
  10303. [](size_t, DataSink &sink) {
  10304. sink.os << "chunk";
  10305. sink.done();
  10306. return true;
  10307. },
  10308. releaser);
  10309. });
  10310. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10311. res.set_content_provider(5, "text/plain", provider, releaser);
  10312. throw std::runtime_error("after the provider");
  10313. });
  10314. svr.set_error_handler([](const Request &req, Response &res) {
  10315. // Leave the exception handler's content to it.
  10316. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10317. res.set_content(std::string(1000, 'E'), "text/html");
  10318. return Server::HandlerResponse::Handled;
  10319. });
  10320. svr.set_exception_handler(
  10321. [](const Request &, Response &res, std::exception_ptr) {
  10322. res.status = StatusCode::InternalServerError_500;
  10323. res.set_content(std::string(1000, 'X'), "text/html");
  10324. });
  10325. auto port = svr.bind_to_any_port(HOST);
  10326. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10327. auto se = detail::scope_exit([&] {
  10328. svr.stop();
  10329. t.join();
  10330. ASSERT_FALSE(svr.is_running());
  10331. });
  10332. svr.wait_until_ready();
  10333. Client cli(HOST, port);
  10334. {
  10335. auto res = cli.Get("/sized");
  10336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10338. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10339. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10340. }
  10341. {
  10342. auto res = cli.Get("/chunked");
  10343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10344. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10345. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10346. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10347. }
  10348. {
  10349. auto res = cli.Get("/throw");
  10350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10351. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10352. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10353. }
  10354. std::lock_guard<std::mutex> guard(released_mutex);
  10355. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10356. }
  10357. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10358. Server svr;
  10359. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10360. return sink.write(&"abc"[offset], length);
  10361. };
  10362. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10363. res.set_file_content("./www/dir/test.html");
  10364. res.set_content("body", "text/plain");
  10365. });
  10366. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10367. res.set_content(std::string(100, 'B'), "text/plain");
  10368. res.set_file_content("./www/dir/test.html");
  10369. });
  10370. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10371. res.set_content(std::string(100, 'B'), "text/plain");
  10372. res.set_content_provider(3, "text/plain", abc);
  10373. });
  10374. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10375. res.set_content_provider(3, "text/plain", abc);
  10376. res.set_content(std::string(100, 'B'), "text/plain");
  10377. });
  10378. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10379. res.set_content_provider(3, "text/plain", abc);
  10380. res.body = "direct";
  10381. });
  10382. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10383. res.set_file_content("./www/dir/test.html");
  10384. res.body = "direct";
  10385. });
  10386. auto port = svr.bind_to_any_port(HOST);
  10387. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10388. auto se = detail::scope_exit([&] {
  10389. svr.stop();
  10390. t.join();
  10391. ASSERT_FALSE(svr.is_running());
  10392. });
  10393. svr.wait_until_ready();
  10394. Client cli(HOST, port);
  10395. auto expect_body = [&](const char *path, const std::string &body) {
  10396. // Uncompressed, so Content-Length can be compared with the body.
  10397. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10398. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10399. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10400. EXPECT_EQ(body, res->body) << path;
  10401. EXPECT_EQ(std::to_string(body.size()),
  10402. res->get_header_value("Content-Length"))
  10403. << path;
  10404. };
  10405. expect_body("/file-then-body", "body");
  10406. expect_body("/body-then-file", "test.html");
  10407. expect_body("/body-then-provider", "abc");
  10408. expect_body("/provider-then-body", std::string(100, 'B'));
  10409. expect_body("/provider-then-direct-body", "direct");
  10410. expect_body("/file-then-direct-body", "direct");
  10411. // Ranges are checked against the body, not the dropped provider.
  10412. {
  10413. auto res = cli.Get("/provider-then-direct-body",
  10414. Headers{{make_range_header({{1, 2}})}});
  10415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10416. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10417. EXPECT_EQ("ir", res->body);
  10418. }
  10419. {
  10420. auto res = cli.Get("/file-then-direct-body",
  10421. Headers{{make_range_header({{7, 8}})}});
  10422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10423. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10424. }
  10425. }
  10426. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10427. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10428. ASSERT_TRUE(mm->is_open());
  10429. Response res;
  10430. detail::set_file_content_provider(res, mm, "text/html",
  10431. detail::EncodingType::None);
  10432. std::string out;
  10433. DataSink sink;
  10434. sink.write = [&](const char *d, size_t l) {
  10435. out.append(d, l);
  10436. return true;
  10437. };
  10438. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10439. EXPECT_EQ("test.html", out);
  10440. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10441. EXPECT_EQ("test.html", out);
  10442. }
  10443. TEST(LongPollingTest, ClientCloseDetection) {
  10444. Server svr;
  10445. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10446. res.set_chunked_content_provider(
  10447. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10448. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10449. sink.os << "hello";
  10450. auto count = 10;
  10451. while (count > 0 && sink.is_writable()) {
  10452. this_thread::sleep_for(chrono::milliseconds(10));
  10453. count--;
  10454. }
  10455. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10456. return true;
  10457. });
  10458. });
  10459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10460. auto se = detail::scope_exit([&] {
  10461. svr.stop();
  10462. listen_thread.join();
  10463. ASSERT_FALSE(svr.is_running());
  10464. });
  10465. svr.wait_until_ready();
  10466. Client cli("localhost", PORT);
  10467. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10468. EXPECT_EQ("hello", string(data, data_length));
  10469. return false; // close the socket immediately.
  10470. });
  10471. ASSERT_FALSE(res);
  10472. }
  10473. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10474. Server svr;
  10475. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10476. res.set_chunked_content_provider(
  10477. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10478. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10479. sink.os << "hello";
  10480. EXPECT_TRUE(sink.os.good());
  10481. // Wait for the client to close the connection
  10482. auto count = 10;
  10483. while (count > 0 && sink.is_writable()) {
  10484. this_thread::sleep_for(chrono::milliseconds(10));
  10485. count--;
  10486. }
  10487. // After client disconnect, write repeatedly until the socket
  10488. // write actually fails (small writes may be absorbed by the
  10489. // kernel buffer)
  10490. std::string chunk(1024, 'x');
  10491. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10492. sink.os << chunk;
  10493. }
  10494. EXPECT_TRUE(sink.os.fail());
  10495. return true;
  10496. });
  10497. });
  10498. auto port = svr.bind_to_any_port("localhost");
  10499. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10500. auto se = detail::scope_exit([&] {
  10501. svr.stop();
  10502. listen_thread.join();
  10503. ASSERT_FALSE(svr.is_running());
  10504. });
  10505. svr.wait_until_ready();
  10506. Client cli("localhost", port);
  10507. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10508. EXPECT_EQ("hello", string(data, data_length));
  10509. return false; // close the socket immediately.
  10510. });
  10511. ASSERT_FALSE(res);
  10512. }
  10513. TEST(GetWithParametersTest, GetWithParameters) {
  10514. Server svr;
  10515. svr.Get("/", [&](const Request &req, Response &) {
  10516. EXPECT_EQ("world", req.get_param_value("hello"));
  10517. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10518. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10519. });
  10520. svr.Get("/params", [&](const Request &req, Response &) {
  10521. EXPECT_EQ("world", req.get_param_value("hello"));
  10522. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10523. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10524. });
  10525. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10526. EXPECT_EQ("resource-id", req.matches[1]);
  10527. EXPECT_EQ("foo", req.get_param_value("param1"));
  10528. EXPECT_EQ("bar", req.get_param_value("param2"));
  10529. });
  10530. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10531. EXPECT_EQ("user-id", req.path_params.at("id"));
  10532. EXPECT_EQ("foo", req.get_param_value("param1"));
  10533. EXPECT_EQ("bar", req.get_param_value("param2"));
  10534. });
  10535. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10536. auto se = detail::scope_exit([&] {
  10537. svr.stop();
  10538. listen_thread.join();
  10539. ASSERT_FALSE(svr.is_running());
  10540. });
  10541. svr.wait_until_ready();
  10542. {
  10543. Client cli(HOST, PORT);
  10544. Params params;
  10545. params.emplace("hello", "world");
  10546. params.emplace("hello2", "world2");
  10547. params.emplace("hello3", "world3");
  10548. auto res = cli.Get("/", params, Headers{});
  10549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10550. EXPECT_EQ(StatusCode::OK_200, res->status);
  10551. }
  10552. {
  10553. Client cli(HOST, PORT);
  10554. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10556. EXPECT_EQ(StatusCode::OK_200, res->status);
  10557. }
  10558. {
  10559. Client cli(HOST, PORT);
  10560. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10562. EXPECT_EQ(StatusCode::OK_200, res->status);
  10563. }
  10564. {
  10565. Client cli(HOST, PORT);
  10566. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::OK_200, res->status);
  10569. }
  10570. }
  10571. TEST(GetWithParametersTest, GetWithParameters2) {
  10572. Server svr;
  10573. svr.Get("/", [&](const Request &req, Response &res) {
  10574. auto text = req.get_param_value("hello");
  10575. res.set_content(text, "text/plain");
  10576. });
  10577. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10578. auto se = detail::scope_exit([&] {
  10579. svr.stop();
  10580. listen_thread.join();
  10581. ASSERT_FALSE(svr.is_running());
  10582. });
  10583. svr.wait_until_ready();
  10584. Client cli("localhost", PORT);
  10585. Params params;
  10586. params.emplace("hello", "world");
  10587. std::string body;
  10588. auto res = cli.Get("/", params, Headers{},
  10589. [&](const char *data, size_t data_length) {
  10590. body.append(data, data_length);
  10591. return true;
  10592. });
  10593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10594. EXPECT_EQ(StatusCode::OK_200, res->status);
  10595. EXPECT_EQ("world", body);
  10596. }
  10597. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10598. Server svr;
  10599. svr.Get("/search", [&](const Request &req, Response &res) {
  10600. auto q = req.get_param_value("q");
  10601. res.set_content(q, "text/plain");
  10602. });
  10603. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10604. auto se = detail::scope_exit([&] {
  10605. svr.stop();
  10606. listen_thread.join();
  10607. ASSERT_FALSE(svr.is_running());
  10608. });
  10609. svr.wait_until_ready();
  10610. Client cli("localhost", PORT);
  10611. // Verify that Get(path, params) works without requiring Headers argument
  10612. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10614. EXPECT_EQ(StatusCode::OK_200, res->status);
  10615. EXPECT_EQ("cpp-httplib", res->body);
  10616. }
  10617. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10618. auto host = "httpbingo.org";
  10619. auto path = std::string{"/range/32"};
  10620. #ifdef CPPHTTPLIB_SSL_ENABLED
  10621. SSLClient cli(host);
  10622. #else
  10623. Client cli(host);
  10624. #endif
  10625. cli.set_default_headers({make_range_header({{1, 10}})});
  10626. cli.set_connection_timeout(5);
  10627. {
  10628. auto res = cli.Get(path);
  10629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10630. EXPECT_EQ("bcdefghijk", res->body);
  10631. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10632. }
  10633. {
  10634. auto res = cli.Get(path);
  10635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10636. EXPECT_EQ("bcdefghijk", res->body);
  10637. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10638. }
  10639. }
  10640. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10641. Server svr;
  10642. svr.set_default_headers({{"Hello", "World"}});
  10643. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10644. res.set_content("ok", "text/plain");
  10645. });
  10646. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10647. auto se = detail::scope_exit([&] {
  10648. svr.stop();
  10649. listen_thread.join();
  10650. ASSERT_FALSE(svr.is_running());
  10651. });
  10652. svr.wait_until_ready();
  10653. Client cli("localhost", PORT);
  10654. auto res = cli.Get("/");
  10655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10656. EXPECT_EQ(StatusCode::OK_200, res->status);
  10657. EXPECT_EQ("ok", res->body);
  10658. EXPECT_EQ("World", res->get_header_value("Hello"));
  10659. }
  10660. #ifdef CPPHTTPLIB_SSL_ENABLED
  10661. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10663. ASSERT_TRUE(svr.is_valid());
  10664. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10665. std::this_thread::sleep_for(std::chrono::seconds(2));
  10666. res.set_content("a", "text/plain");
  10667. });
  10668. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10669. res.set_content("b", "text/plain");
  10670. });
  10671. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10672. auto se = detail::scope_exit([&] {
  10673. svr.stop();
  10674. listen_thread.join();
  10675. ASSERT_FALSE(svr.is_running());
  10676. });
  10677. svr.wait_until_ready();
  10678. SSLClient cli("localhost", PORT);
  10679. cli.enable_server_certificate_verification(false);
  10680. cli.set_keep_alive(true);
  10681. cli.set_read_timeout(std::chrono::seconds(1));
  10682. auto resa = cli.Get("/a");
  10683. ASSERT_TRUE(!resa);
  10684. EXPECT_EQ(Error::Read, resa.error());
  10685. auto resb = cli.Get("/b");
  10686. ASSERT_TRUE(resb);
  10687. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10688. EXPECT_EQ("b", resb->body);
  10689. }
  10690. // Closing an idle keep-alive connection sends close_notify and returns. The
  10691. // server must not wait for the client's close_notify: an idle client never
  10692. // sends one, so the worker would be held until the read timeout expires, and
  10693. // stop() would wait for it.
  10694. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10696. ASSERT_TRUE(svr.is_valid());
  10697. svr.set_keep_alive_timeout(1);
  10698. svr.set_read_timeout(10, 0);
  10699. svr.Get("/", [](const Request &, Response &res) {
  10700. res.set_content("ok", "text/plain");
  10701. });
  10702. auto port = svr.bind_to_any_port(HOST);
  10703. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10704. auto se = detail::scope_exit([&] {
  10705. if (listen_thread.joinable()) {
  10706. svr.stop();
  10707. listen_thread.join();
  10708. }
  10709. });
  10710. svr.wait_until_ready();
  10711. SSLClient cli(HOST, port);
  10712. cli.enable_server_certificate_verification(false);
  10713. cli.set_keep_alive(true);
  10714. auto res = cli.Get("/");
  10715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10716. EXPECT_EQ(StatusCode::OK_200, res->status);
  10717. // Stay idle past the keep-alive timeout so the server closes the connection.
  10718. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10719. auto start = std::chrono::steady_clock::now();
  10720. svr.stop();
  10721. listen_thread.join();
  10722. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10723. std::chrono::steady_clock::now() - start)
  10724. .count();
  10725. EXPECT_LT(elapsed, 3000);
  10726. }
  10727. #endif
  10728. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10729. protected:
  10730. ServerTestWithAI_PASSIVE()
  10731. : cli_(HOST, PORT)
  10732. #ifdef CPPHTTPLIB_SSL_ENABLED
  10733. ,
  10734. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10735. #endif
  10736. {
  10737. #ifdef CPPHTTPLIB_SSL_ENABLED
  10738. cli_.enable_server_certificate_verification(false);
  10739. #endif
  10740. }
  10741. virtual void SetUp() {
  10742. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10743. res.set_content("Hello World!", "text/plain");
  10744. });
  10745. t_ = thread(
  10746. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10747. svr_.wait_until_ready();
  10748. }
  10749. virtual void TearDown() {
  10750. svr_.stop();
  10751. t_.join();
  10752. }
  10753. #ifdef CPPHTTPLIB_SSL_ENABLED
  10754. SSLClient cli_;
  10755. SSLServer svr_;
  10756. #else
  10757. Client cli_;
  10758. Server svr_;
  10759. #endif
  10760. thread t_;
  10761. };
  10762. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10763. auto res = cli_.Get("/hi");
  10764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10765. EXPECT_EQ(StatusCode::OK_200, res->status);
  10766. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10767. EXPECT_EQ("Hello World!", res->body);
  10768. }
  10769. class ServerUpDownTest : public ::testing::Test {
  10770. protected:
  10771. ServerUpDownTest() : cli_(HOST, PORT) {}
  10772. virtual void SetUp() {
  10773. t_ = thread([&]() {
  10774. svr_.bind_to_any_port(HOST);
  10775. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10776. ASSERT_TRUE(svr_.listen_after_bind());
  10777. });
  10778. svr_.wait_until_ready();
  10779. }
  10780. virtual void TearDown() {
  10781. svr_.stop();
  10782. t_.join();
  10783. }
  10784. Client cli_;
  10785. Server svr_;
  10786. thread t_;
  10787. };
  10788. TEST_F(ServerUpDownTest, QuickStartStop) {
  10789. // Should not crash, especially when run with
  10790. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10791. }
  10792. class PayloadMaxLengthTest : public ::testing::Test {
  10793. protected:
  10794. PayloadMaxLengthTest()
  10795. : cli_(HOST, PORT)
  10796. #ifdef CPPHTTPLIB_SSL_ENABLED
  10797. ,
  10798. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10799. #endif
  10800. {
  10801. #ifdef CPPHTTPLIB_SSL_ENABLED
  10802. cli_.enable_server_certificate_verification(false);
  10803. #endif
  10804. }
  10805. virtual void SetUp() {
  10806. svr_.set_payload_max_length(8);
  10807. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10808. res.set_content("test", "text/plain");
  10809. });
  10810. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10811. svr_.wait_until_ready();
  10812. }
  10813. virtual void TearDown() {
  10814. svr_.stop();
  10815. t_.join();
  10816. }
  10817. #ifdef CPPHTTPLIB_SSL_ENABLED
  10818. SSLClient cli_;
  10819. SSLServer svr_;
  10820. #else
  10821. Client cli_;
  10822. Server svr_;
  10823. #endif
  10824. thread t_;
  10825. };
  10826. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10827. auto res = cli_.Post("/test", "123456789", "text/plain");
  10828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10829. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10830. res = cli_.Post("/test", "12345678", "text/plain");
  10831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10832. EXPECT_EQ(StatusCode::OK_200, res->status);
  10833. }
  10834. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10835. // Test chunked encoding with payload exceeding the 8-byte limit
  10836. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10837. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10839. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10840. }
  10841. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10842. // Test chunked encoding with payload within the 8-byte limit
  10843. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10844. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10846. EXPECT_EQ(StatusCode::OK_200, res->status);
  10847. }
  10848. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10849. // Test using send_request to send chunked data exceeding payload limit
  10850. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10851. "Host: " +
  10852. std::string(HOST) + ":" + std::to_string(PORT) +
  10853. "\r\n"
  10854. "Transfer-Encoding: chunked\r\n"
  10855. "Connection: close\r\n"
  10856. "\r\n"
  10857. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10858. "0123456789\r\n"
  10859. "0\r\n" // End chunk
  10860. "\r\n";
  10861. std::string response;
  10862. bool result = send_request(1, chunked_request, &response);
  10863. if (!result) {
  10864. // If send_request fails, it might be because the server closed the
  10865. // connection due to payload limit enforcement, which is acceptable
  10866. SUCCEED()
  10867. << "Server rejected oversized chunked request (connection closed)";
  10868. } else {
  10869. // If we got a response, check if it's an error response or connection was
  10870. // closed early Short response length indicates connection was closed due to
  10871. // payload limit
  10872. if (response.length() <= 10) {
  10873. SUCCEED() << "Server closed connection for oversized chunked request";
  10874. } else {
  10875. // Check for error status codes
  10876. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10877. response.find("Payload Too Large") != std::string::npos ||
  10878. response.find("400") != std::string::npos);
  10879. }
  10880. }
  10881. }
  10882. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10883. // Test request without Content-Length header exceeding payload limit
  10884. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10885. "Host: " +
  10886. std::string(HOST) + ":" +
  10887. std::to_string(PORT) +
  10888. "\r\n"
  10889. "Connection: close\r\n"
  10890. "\r\n";
  10891. // Add payload exceeding the 8-byte limit
  10892. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10893. request_without_content_length += large_payload;
  10894. std::string response;
  10895. bool result = send_request(1, request_without_content_length, &response);
  10896. if (!result) {
  10897. // If send_request fails, server likely closed connection due to payload
  10898. // limit
  10899. SUCCEED() << "Server rejected oversized request without Content-Length "
  10900. "(connection closed)";
  10901. } else {
  10902. // Check if server responded with error or closed connection early
  10903. if (response.length() <= 10) {
  10904. SUCCEED() << "Server closed connection for oversized request without "
  10905. "Content-Length";
  10906. } else {
  10907. // Check for error status codes
  10908. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10909. response.find("Payload Too Large") != std::string::npos ||
  10910. response.find("400") != std::string::npos);
  10911. }
  10912. }
  10913. }
  10914. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10915. // Test request without Content-Length header within payload limit
  10916. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10917. "Host: " +
  10918. std::string(HOST) + ":" +
  10919. std::to_string(PORT) +
  10920. "\r\n"
  10921. "Connection: close\r\n"
  10922. "\r\n";
  10923. // Add payload within the 8-byte limit
  10924. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10925. request_without_content_length += small_payload;
  10926. std::string response;
  10927. bool result = send_request(1, request_without_content_length, &response);
  10928. // For requests without Content-Length, the server may have different behavior
  10929. // The key is that it should not reject due to payload limit for small
  10930. // payloads
  10931. if (result) {
  10932. // Check for any HTTP response (success or error, but not connection closed)
  10933. if (response.length() > 10) {
  10934. SUCCEED()
  10935. << "Server processed request without Content-Length within limit";
  10936. } else {
  10937. // Short response might indicate connection closed, which is acceptable
  10938. SUCCEED() << "Server closed connection for request without "
  10939. "Content-Length (acceptable behavior)";
  10940. }
  10941. } else {
  10942. // Connection failure might be due to protocol requirements
  10943. SUCCEED() << "Connection issue with request without Content-Length "
  10944. "(environment-specific)";
  10945. }
  10946. }
  10947. class LargePayloadMaxLengthTest : public ::testing::Test {
  10948. protected:
  10949. LargePayloadMaxLengthTest()
  10950. : cli_(HOST, PORT)
  10951. #ifdef CPPHTTPLIB_SSL_ENABLED
  10952. ,
  10953. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10954. #endif
  10955. {
  10956. #ifdef CPPHTTPLIB_SSL_ENABLED
  10957. cli_.enable_server_certificate_verification(false);
  10958. #endif
  10959. }
  10960. virtual void SetUp() {
  10961. // Set 10MB payload limit
  10962. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10963. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10964. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10965. res.set_content("Large payload test", "text/plain");
  10966. });
  10967. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10968. svr_.wait_until_ready();
  10969. }
  10970. virtual void TearDown() {
  10971. svr_.stop();
  10972. t_.join();
  10973. }
  10974. #ifdef CPPHTTPLIB_SSL_ENABLED
  10975. SSLClient cli_;
  10976. SSLServer svr_;
  10977. #else
  10978. Client cli_;
  10979. Server svr_;
  10980. #endif
  10981. thread t_;
  10982. };
  10983. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10984. // Test chunked encoding with payload within 10MB limit
  10985. std::string medium_payload(5 * 1024 * 1024,
  10986. 'A'); // 5MB payload, within 10MB limit
  10987. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10989. EXPECT_EQ(StatusCode::OK_200, res->status);
  10990. }
  10991. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10992. // Test chunked encoding with payload exceeding 10MB limit
  10993. std::string large_payload(12 * 1024 * 1024,
  10994. 'B'); // 12MB payload, exceeds 10MB limit
  10995. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10996. // Server may either return 413 or close the connection
  10997. if (res) {
  10998. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10999. } else {
  11000. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11001. }
  11002. }
  11003. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11004. // Test request without Content-Length header within 10MB limit
  11005. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11006. "Host: " +
  11007. std::string(HOST) + ":" +
  11008. std::to_string(PORT) +
  11009. "\r\n"
  11010. "Connection: close\r\n"
  11011. "\r\n";
  11012. // Add 1MB payload (within 10MB limit)
  11013. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11014. request_without_content_length += medium_payload;
  11015. std::string response;
  11016. bool result = send_request(5, request_without_content_length, &response);
  11017. if (result) {
  11018. // Should get a proper HTTP response for payloads within limit
  11019. if (response.length() > 10) {
  11020. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11021. "10MB limit";
  11022. } else {
  11023. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11024. "Content-Length)";
  11025. }
  11026. } else {
  11027. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11028. }
  11029. }
  11030. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11031. // Test request without Content-Length header exceeding 10MB limit
  11032. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11033. "Host: " +
  11034. std::string(HOST) + ":" +
  11035. std::to_string(PORT) +
  11036. "\r\n"
  11037. "Connection: close\r\n"
  11038. "\r\n";
  11039. // Add 12MB payload (exceeds 10MB limit)
  11040. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11041. request_without_content_length += large_payload;
  11042. std::string response;
  11043. bool result = send_request(10, request_without_content_length, &response);
  11044. if (!result) {
  11045. // Server should close connection due to payload limit
  11046. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11047. "(connection closed)";
  11048. } else {
  11049. // Check for error response
  11050. if (response.length() <= 10) {
  11051. SUCCEED()
  11052. << "Server closed connection for 12MB request exceeding 10MB limit";
  11053. } else {
  11054. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11055. response.find("Payload Too Large") != std::string::npos ||
  11056. response.find("400") != std::string::npos);
  11057. }
  11058. }
  11059. }
  11060. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11061. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11062. // path.
  11063. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11064. Server svr;
  11065. const size_t LIMIT = 64 * 1024; // 64KB
  11066. svr.set_payload_max_length(LIMIT);
  11067. size_t total = 0;
  11068. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11069. const ContentReader &content_reader) {
  11070. content_reader([&](const char * /*data*/, size_t len) {
  11071. total += len;
  11072. return true;
  11073. });
  11074. res.status = 200;
  11075. res.set_content("stream_ok", "text/plain");
  11076. });
  11077. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11078. auto se = detail::scope_exit([&] {
  11079. svr.stop();
  11080. thread.join();
  11081. ASSERT_FALSE(svr.is_running());
  11082. });
  11083. svr.wait_until_ready();
  11084. // Prepare 256KB raw data and gzip-compress it
  11085. std::string raw(256 * 1024, 'A');
  11086. std::string gz;
  11087. {
  11088. z_stream zs{};
  11089. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11090. Z_DEFAULT_STRATEGY);
  11091. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11092. zs.avail_in = static_cast<uInt>(raw.size());
  11093. char outbuf[4096];
  11094. int ret;
  11095. do {
  11096. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11097. zs.avail_out = sizeof(outbuf);
  11098. ret = deflate(&zs, Z_FINISH);
  11099. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11100. } while (ret != Z_STREAM_END);
  11101. deflateEnd(&zs);
  11102. }
  11103. Client cli(HOST, PORT);
  11104. cli.set_connection_timeout(std::chrono::seconds(5));
  11105. Headers headers = {{"Content-Encoding", "gzip"}};
  11106. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11107. "application/octet-stream");
  11108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11109. // Server must reject oversized decompressed payloads with 413.
  11110. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11111. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11112. EXPECT_LE(total, LIMIT);
  11113. }
  11114. #ifndef CPPHTTPLIB_SSL_ENABLED
  11115. // For a request with neither Content-Length nor Transfer-Encoding, the
  11116. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11117. // compressed wire bytes straight to the ContentReader without ever routing
  11118. // them through the decompressor, so payload_max_length_ only bounded the
  11119. // compressed size on the wire, not the decompressed size.
  11120. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11121. Server svr;
  11122. const size_t LIMIT = 64 * 1024; // 64KB
  11123. svr.set_payload_max_length(LIMIT);
  11124. size_t total = 0;
  11125. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11126. const ContentReader &content_reader) {
  11127. content_reader([&](const char * /*data*/, size_t len) {
  11128. total += len;
  11129. return true;
  11130. });
  11131. res.status = 200;
  11132. res.set_content("stream_ok", "text/plain");
  11133. });
  11134. auto port = svr.bind_to_any_port(HOST);
  11135. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11143. // StreamingGzipDecompression test above.
  11144. std::string raw(256 * 1024, 'A');
  11145. std::string gz;
  11146. {
  11147. httplib::detail::gzip_compressor compressor;
  11148. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11149. [&](const char *chunk, size_t len) {
  11150. gz.append(chunk, len);
  11151. return true;
  11152. });
  11153. ASSERT_TRUE(result);
  11154. }
  11155. // Send the gzip body over raw TCP with neither Content-Length nor
  11156. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11157. // kicks in.
  11158. std::string req = "POST /stream HTTP/1.1\r\n"
  11159. "Host: " +
  11160. std::string(HOST) + ":" + std::to_string(port) +
  11161. "\r\n"
  11162. "Content-Encoding: gzip\r\n"
  11163. "Connection: close\r\n"
  11164. "\r\n" +
  11165. gz;
  11166. std::string response;
  11167. ASSERT_TRUE(send_request(5, req, &response, port));
  11168. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11169. EXPECT_LE(total, LIMIT);
  11170. }
  11171. #endif
  11172. #endif
  11173. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11174. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11175. // the payload must be passed through untouched instead of being rejected.
  11176. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11177. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11178. Server svr;
  11179. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11180. res.set_content(body, "image/jpeg");
  11181. res.set_header("Content-Encoding", "UTF-8");
  11182. });
  11183. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11184. res.set_content(body, "image/jpeg");
  11185. res.set_header("Content-Encoding", "identity");
  11186. });
  11187. svr.Post("/echo", [](const Request &req, Response &res) {
  11188. res.set_content(req.body, "image/jpeg");
  11189. });
  11190. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. t.join();
  11194. ASSERT_FALSE(svr.is_running());
  11195. });
  11196. svr.wait_until_ready();
  11197. Client cli(HOST, PORT);
  11198. {
  11199. auto res = cli.Get("/image");
  11200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11201. EXPECT_EQ(StatusCode::OK_200, res->status);
  11202. EXPECT_EQ(body, res->body);
  11203. }
  11204. {
  11205. auto res = cli.Get("/identity");
  11206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11207. EXPECT_EQ(StatusCode::OK_200, res->status);
  11208. EXPECT_EQ(body, res->body);
  11209. }
  11210. {
  11211. // The same applies to a request body reaching the server.
  11212. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11213. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11215. EXPECT_EQ(StatusCode::OK_200, res->status);
  11216. EXPECT_EQ(body, res->body);
  11217. }
  11218. }
  11219. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11220. // gzip-encoded response even when the build has no zlib support.
  11221. static const char GZIPPED_HELLO_WORLD[] = {
  11222. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11223. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11224. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11225. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11226. // A content coding is a whole token, not something the field value merely
  11227. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11228. // as "fibre" look like Brotli, and turned a multi-coding value like
  11229. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11230. // it was never meant to see.
  11231. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11232. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11233. Server svr;
  11234. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11235. res.set_content(body, "image/jpeg");
  11236. res.set_header("Content-Encoding", "fibre");
  11237. });
  11238. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11239. res.set_content(body, "image/jpeg");
  11240. res.set_header("Content-Encoding", "gzip, br");
  11241. });
  11242. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11243. res.set_content(body, "image/jpeg");
  11244. res.set_header("Content-Encoding", "x-zstd-ish");
  11245. });
  11246. auto port = svr.bind_to_any_port(HOST);
  11247. thread t = thread([&]() { svr.listen_after_bind(); });
  11248. auto se = detail::scope_exit([&] {
  11249. svr.stop();
  11250. t.join();
  11251. ASSERT_FALSE(svr.is_running());
  11252. });
  11253. svr.wait_until_ready();
  11254. Client cli(HOST, port);
  11255. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11256. auto res = cli.Get(path);
  11257. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11258. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11259. // Not a coding we recognize, so the payload comes back untouched
  11260. EXPECT_EQ(body, res->body) << path;
  11261. }
  11262. }
  11263. // A content coding cpp-httplib recognizes but was not built with must be
  11264. // reported as such. Handing the still-compressed payload back to the caller
  11265. // would silently corrupt it.
  11266. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11267. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11268. Server svr;
  11269. // "image/jpeg" keeps the server from applying a content coding of its own,
  11270. // so the hand-crafted Content-Encoding below survives.
  11271. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11272. res.set_content(gzipped, "image/jpeg");
  11273. res.set_header("Content-Encoding", "gzip");
  11274. });
  11275. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11276. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11277. res.set_content(gzipped, "image/jpeg");
  11278. res.set_header("Content-Encoding", "GZIP");
  11279. });
  11280. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11281. auto se = detail::scope_exit([&] {
  11282. svr.stop();
  11283. t.join();
  11284. ASSERT_FALSE(svr.is_running());
  11285. });
  11286. svr.wait_until_ready();
  11287. Client cli(HOST, PORT);
  11288. {
  11289. auto res = cli.Get("/gzipped");
  11290. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11292. EXPECT_EQ("Hello World!", res->body);
  11293. #else
  11294. ASSERT_FALSE(res);
  11295. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11296. #endif
  11297. }
  11298. {
  11299. // open_stream() must behave the same way.
  11300. auto handle = cli.open_stream("GET", "/gzipped");
  11301. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11302. ASSERT_TRUE(handle.is_valid());
  11303. std::string received;
  11304. char buf[256];
  11305. ssize_t n;
  11306. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11307. received.append(buf, static_cast<size_t>(n));
  11308. }
  11309. EXPECT_EQ("Hello World!", received);
  11310. #else
  11311. EXPECT_FALSE(handle.is_valid());
  11312. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11313. #endif
  11314. }
  11315. {
  11316. // A differently-cased coding must not be mistaken for an unknown one, or
  11317. // the body would be handed back still compressed.
  11318. auto res = cli.Get("/gzipped-uppercase");
  11319. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ("Hello World!", res->body);
  11322. #else
  11323. ASSERT_FALSE(res);
  11324. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11325. #endif
  11326. }
  11327. }
  11328. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11329. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11330. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11331. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11332. // body a second time and appending a second Content-Encoding field line, so
  11333. // clients that decode one coding per listed value handed back raw gzip bytes.
  11334. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11335. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11336. Server svr;
  11337. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11338. // keeps the server from applying a coding of its own.
  11339. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11340. res.set_content(gzipped, "text/plain");
  11341. res.set_header("Content-Encoding", "gzip");
  11342. });
  11343. auto port = svr.bind_to_any_port(HOST);
  11344. thread t = thread([&]() { svr.listen_after_bind(); });
  11345. auto se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. t.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. });
  11350. svr.wait_until_ready();
  11351. Client cli(HOST, port);
  11352. Headers headers = {{"Accept-Encoding", "gzip"}};
  11353. auto res = cli.Get("/pre-gzipped", headers);
  11354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11355. EXPECT_EQ(StatusCode::OK_200, res->status);
  11356. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11357. EXPECT_EQ("Hello World!", res->body);
  11358. }
  11359. // A chunked provider settles its coding where the headers are written and
  11360. // reuses it at write time. Both ends of that have to hold: a handler's own
  11361. // Content-Encoding suppresses the coding, and a response without one is still
  11362. // compressed as it always was.
  11363. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11364. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11365. const std::string plain = "Hello World! Hello World! Hello World!";
  11366. Server svr;
  11367. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11368. res.set_header("Content-Encoding", "gzip");
  11369. res.set_chunked_content_provider(
  11370. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11371. sink.write(gzipped.data(), gzipped.size());
  11372. sink.done();
  11373. return true;
  11374. });
  11375. });
  11376. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11377. res.set_chunked_content_provider(
  11378. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11379. sink.write(plain.data(), plain.size());
  11380. sink.done();
  11381. return true;
  11382. });
  11383. });
  11384. auto port = svr.bind_to_any_port(HOST);
  11385. thread t = thread([&]() { svr.listen_after_bind(); });
  11386. auto se = detail::scope_exit([&] {
  11387. svr.stop();
  11388. t.join();
  11389. ASSERT_FALSE(svr.is_running());
  11390. });
  11391. svr.wait_until_ready();
  11392. Client cli(HOST, port);
  11393. Headers headers = {{"Accept-Encoding", "gzip"}};
  11394. {
  11395. auto res = cli.Get("/pre-gzipped", headers);
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. EXPECT_EQ(StatusCode::OK_200, res->status);
  11398. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11399. EXPECT_EQ("Hello World!", res->body);
  11400. }
  11401. {
  11402. auto res = cli.Get("/negotiated", headers);
  11403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11404. EXPECT_EQ(StatusCode::OK_200, res->status);
  11405. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11406. EXPECT_EQ(plain, res->body);
  11407. }
  11408. }
  11409. #endif
  11410. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11411. // the same message as the comma-joined one, so both have to be read the same
  11412. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11413. // single gzip coding, and a body the sender says was encoded twice was handed
  11414. // back after one pass, still compressed but presented as decoded.
  11415. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11416. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11417. Server svr;
  11418. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11419. res.set_content(body, "image/jpeg");
  11420. res.headers.emplace("Content-Encoding", "gzip");
  11421. res.headers.emplace("Content-Encoding", "gzip");
  11422. });
  11423. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11424. res.set_content(body, "image/jpeg");
  11425. res.set_header("Content-Encoding", "gzip, gzip");
  11426. });
  11427. auto port = svr.bind_to_any_port(HOST);
  11428. thread t = thread([&]() { svr.listen_after_bind(); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. t.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, port);
  11436. // Two codings is not something cpp-httplib decodes, so both representations
  11437. // take the pass-through path rather than one of them being gunzipped once.
  11438. for (const char *path : {"/split", "/joined"}) {
  11439. auto res = cli.Get(path);
  11440. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11441. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11442. EXPECT_EQ(body, res->body) << path;
  11443. }
  11444. }
  11445. // Regression test for DoS vulnerability: a malicious server sending a response
  11446. // without Content-Length header must not cause unbounded memory consumption on
  11447. // the client side. The client should stop reading after a reasonable limit,
  11448. // similar to the server-side set_payload_max_length protection.
  11449. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11450. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11451. #ifndef _WIN32
  11452. signal(SIGPIPE, SIG_IGN);
  11453. #endif
  11454. auto server_thread = std::thread([] {
  11455. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11456. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11457. default_socket_options(srv);
  11458. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11459. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11460. sockaddr_in addr{};
  11461. addr.sin_family = AF_INET;
  11462. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11463. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11464. int opt = 1;
  11465. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11466. #ifdef _WIN32
  11467. reinterpret_cast<const char *>(&opt),
  11468. #else
  11469. &opt,
  11470. #endif
  11471. sizeof(opt));
  11472. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11473. ::listen(srv, 1);
  11474. sockaddr_in cli_addr{};
  11475. socklen_t cli_len = sizeof(cli_addr);
  11476. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11477. if (cli != INVALID_SOCKET) {
  11478. char buf[4096];
  11479. ::recv(cli, buf, sizeof(buf), 0);
  11480. // Malicious response: no Content-Length, no chunked encoding
  11481. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11482. "Connection: close\r\n"
  11483. "\r\n";
  11484. ::send(cli,
  11485. #ifdef _WIN32
  11486. static_cast<const char *>(response_header.c_str()),
  11487. static_cast<int>(response_header.size()),
  11488. #else
  11489. response_header.c_str(), response_header.size(),
  11490. #endif
  11491. 0);
  11492. // Send 10MB of data
  11493. std::string chunk(64 * 1024, 'A');
  11494. size_t total_sent = 0;
  11495. while (total_sent < MALICIOUS_DATA_SIZE) {
  11496. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11497. auto sent = ::send(cli,
  11498. #ifdef _WIN32
  11499. static_cast<const char *>(chunk.c_str()),
  11500. static_cast<int>(to_send),
  11501. #else
  11502. chunk.c_str(), to_send,
  11503. #endif
  11504. 0);
  11505. if (sent <= 0) break;
  11506. total_sent += static_cast<size_t>(sent);
  11507. }
  11508. detail::close_socket(cli);
  11509. }
  11510. detail::close_socket(srv);
  11511. });
  11512. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11513. size_t total_read = 0;
  11514. {
  11515. Client cli("127.0.0.1", PORT + 2);
  11516. cli.set_read_timeout(5, 0);
  11517. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11518. auto stream = cli.open_stream("GET", "/malicious");
  11519. ASSERT_TRUE(stream.is_valid());
  11520. char buffer[64 * 1024];
  11521. ssize_t n;
  11522. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11523. total_read += static_cast<size_t>(n);
  11524. }
  11525. } // StreamHandle and Client destroyed here, closing the socket
  11526. server_thread.join();
  11527. // With set_payload_max_length, the client must stop reading before consuming
  11528. // all 10MB. The read loop should be cut off at or near the configured limit.
  11529. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11530. << "Client read " << total_read << " bytes, exceeding the configured "
  11531. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11532. }
  11533. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11534. // the entire response body without truncation.
  11535. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11536. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11537. #ifndef _WIN32
  11538. signal(SIGPIPE, SIG_IGN);
  11539. #endif
  11540. auto server_thread = std::thread([] {
  11541. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11542. default_socket_options(srv);
  11543. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11544. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11545. sockaddr_in addr{};
  11546. addr.sin_family = AF_INET;
  11547. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11548. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11549. int opt = 1;
  11550. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11551. #ifdef _WIN32
  11552. reinterpret_cast<const char *>(&opt),
  11553. #else
  11554. &opt,
  11555. #endif
  11556. sizeof(opt));
  11557. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11558. ::listen(srv, 1);
  11559. sockaddr_in cli_addr{};
  11560. socklen_t cli_len = sizeof(cli_addr);
  11561. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11562. if (cli != INVALID_SOCKET) {
  11563. char buf[4096];
  11564. ::recv(cli, buf, sizeof(buf), 0);
  11565. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11566. "Connection: close\r\n"
  11567. "\r\n";
  11568. ::send(cli,
  11569. #ifdef _WIN32
  11570. static_cast<const char *>(response_header.c_str()),
  11571. static_cast<int>(response_header.size()),
  11572. #else
  11573. response_header.c_str(), response_header.size(),
  11574. #endif
  11575. 0);
  11576. std::string chunk(64 * 1024, 'A');
  11577. size_t total_sent = 0;
  11578. while (total_sent < DATA_SIZE) {
  11579. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11580. auto sent = ::send(cli,
  11581. #ifdef _WIN32
  11582. static_cast<const char *>(chunk.c_str()),
  11583. static_cast<int>(to_send),
  11584. #else
  11585. chunk.c_str(), to_send,
  11586. #endif
  11587. 0);
  11588. if (sent <= 0) break;
  11589. total_sent += static_cast<size_t>(sent);
  11590. }
  11591. #ifdef _WIN32
  11592. ::shutdown(cli, SD_SEND);
  11593. #else
  11594. ::shutdown(cli, SHUT_WR);
  11595. #endif
  11596. // Drain until the client closes its end, ensuring all data is delivered
  11597. char drain[1024];
  11598. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11599. detail::close_socket(cli);
  11600. }
  11601. detail::close_socket(srv);
  11602. });
  11603. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11604. size_t total_read = 0;
  11605. {
  11606. Client cli("127.0.0.1", PORT + 2);
  11607. cli.set_read_timeout(5, 0);
  11608. cli.set_payload_max_length(0); // 0 means no limit
  11609. auto stream = cli.open_stream("GET", "/data");
  11610. ASSERT_TRUE(stream.is_valid());
  11611. char buffer[64 * 1024];
  11612. ssize_t n;
  11613. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11614. total_read += static_cast<size_t>(n);
  11615. }
  11616. }
  11617. server_thread.join();
  11618. EXPECT_EQ(total_read, DATA_SIZE)
  11619. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11620. << " bytes without truncation, but only read " << total_read << " bytes.";
  11621. }
  11622. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11623. // enormous Content-Length must not cause the client to pre-allocate a huge
  11624. // response body buffer. The reservation is capped at payload_max_length_, and
  11625. // the read itself fails when the body exceeds the limit.
  11626. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11627. #ifndef _WIN32
  11628. signal(SIGPIPE, SIG_IGN);
  11629. #endif
  11630. auto server_thread = std::thread([] {
  11631. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11632. default_socket_options(srv);
  11633. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11634. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11635. sockaddr_in addr{};
  11636. addr.sin_family = AF_INET;
  11637. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11638. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11639. int opt = 1;
  11640. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11641. #ifdef _WIN32
  11642. reinterpret_cast<const char *>(&opt),
  11643. #else
  11644. &opt,
  11645. #endif
  11646. sizeof(opt));
  11647. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11648. ::listen(srv, 1);
  11649. sockaddr_in cli_addr{};
  11650. socklen_t cli_len = sizeof(cli_addr);
  11651. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11652. if (cli != INVALID_SOCKET) {
  11653. char buf[4096];
  11654. ::recv(cli, buf, sizeof(buf), 0);
  11655. // Malicious response: claim a 20GB body but send only a tiny payload.
  11656. std::string response = "HTTP/1.1 200 OK\r\n"
  11657. "Content-Length: 20000000000\r\n"
  11658. "\r\n"
  11659. "abc";
  11660. ::send(cli,
  11661. #ifdef _WIN32
  11662. static_cast<const char *>(response.c_str()),
  11663. static_cast<int>(response.size()),
  11664. #else
  11665. response.c_str(), response.size(),
  11666. #endif
  11667. 0);
  11668. detail::close_socket(cli);
  11669. }
  11670. detail::close_socket(srv);
  11671. });
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11673. {
  11674. Client cli("127.0.0.1", PORT + 2);
  11675. cli.set_read_timeout(5, 0);
  11676. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11677. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11678. // (server claims more bytes than payload_max_length permits), but it must
  11679. // not exhaust memory before getting there.
  11680. auto res = cli.Get("/malicious");
  11681. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11682. }
  11683. server_thread.join();
  11684. }
  11685. // Verify that content_receiver bypasses the default payload_max_length,
  11686. // allowing streaming downloads larger than 100MB without requiring an explicit
  11687. // set_payload_max_length call.
  11688. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11689. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11690. #ifndef _WIN32
  11691. signal(SIGPIPE, SIG_IGN);
  11692. #endif
  11693. auto server_thread = std::thread([] {
  11694. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11695. default_socket_options(srv);
  11696. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11697. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11698. sockaddr_in addr{};
  11699. addr.sin_family = AF_INET;
  11700. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11701. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11702. int opt = 1;
  11703. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11704. #ifdef _WIN32
  11705. reinterpret_cast<const char *>(&opt),
  11706. #else
  11707. &opt,
  11708. #endif
  11709. sizeof(opt));
  11710. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11711. ::listen(srv, 1);
  11712. sockaddr_in cli_addr{};
  11713. socklen_t cli_len = sizeof(cli_addr);
  11714. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11715. if (cli != INVALID_SOCKET) {
  11716. char buf[4096];
  11717. ::recv(cli, buf, sizeof(buf), 0);
  11718. // Response with Content-Length larger than default 100MB limit
  11719. auto content_length = std::to_string(DATA_SIZE);
  11720. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11721. "Content-Length: " +
  11722. content_length +
  11723. "\r\n"
  11724. "Connection: close\r\n"
  11725. "\r\n";
  11726. ::send(cli,
  11727. #ifdef _WIN32
  11728. static_cast<const char *>(response_header.c_str()),
  11729. static_cast<int>(response_header.size()),
  11730. #else
  11731. response_header.c_str(), response_header.size(),
  11732. #endif
  11733. 0);
  11734. std::string chunk(64 * 1024, 'A');
  11735. size_t total_sent = 0;
  11736. while (total_sent < DATA_SIZE) {
  11737. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11738. auto sent = ::send(cli,
  11739. #ifdef _WIN32
  11740. static_cast<const char *>(chunk.c_str()),
  11741. static_cast<int>(to_send),
  11742. #else
  11743. chunk.c_str(), to_send,
  11744. #endif
  11745. 0);
  11746. if (sent <= 0) break;
  11747. total_sent += static_cast<size_t>(sent);
  11748. }
  11749. detail::close_socket(cli);
  11750. }
  11751. detail::close_socket(srv);
  11752. });
  11753. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11754. size_t total_received = 0;
  11755. {
  11756. Client cli("127.0.0.1", PORT + 2);
  11757. cli.set_read_timeout(10, 0);
  11758. // Do NOT call set_payload_max_length — use the default 100MB limit
  11759. auto res =
  11760. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11761. total_received += data_length;
  11762. return true;
  11763. });
  11764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11765. EXPECT_EQ(StatusCode::OK_200, res->status);
  11766. }
  11767. server_thread.join();
  11768. EXPECT_EQ(total_received, DATA_SIZE)
  11769. << "With content_receiver, the client should read all " << DATA_SIZE
  11770. << " bytes despite the default 100MB payload_max_length, but only read "
  11771. << total_received << " bytes.";
  11772. }
  11773. // Verify that an explicit set_payload_max_length smaller than the response is
  11774. // enforced even when a content_receiver is used.
  11775. TEST(ClientVulnerabilityTest,
  11776. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11777. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11778. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11779. #ifndef _WIN32
  11780. signal(SIGPIPE, SIG_IGN);
  11781. #endif
  11782. auto server_thread = std::thread([] {
  11783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11784. default_socket_options(srv);
  11785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11787. sockaddr_in addr{};
  11788. addr.sin_family = AF_INET;
  11789. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11790. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11791. int opt = 1;
  11792. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11793. #ifdef _WIN32
  11794. reinterpret_cast<const char *>(&opt),
  11795. #else
  11796. &opt,
  11797. #endif
  11798. sizeof(opt));
  11799. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11800. ::listen(srv, 1);
  11801. sockaddr_in cli_addr{};
  11802. socklen_t cli_len = sizeof(cli_addr);
  11803. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11804. if (cli != INVALID_SOCKET) {
  11805. char buf[4096];
  11806. ::recv(cli, buf, sizeof(buf), 0);
  11807. auto content_length = std::to_string(DATA_SIZE);
  11808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11809. "Content-Length: " +
  11810. content_length +
  11811. "\r\n"
  11812. "Connection: close\r\n"
  11813. "\r\n";
  11814. ::send(cli,
  11815. #ifdef _WIN32
  11816. static_cast<const char *>(response_header.c_str()),
  11817. static_cast<int>(response_header.size()),
  11818. #else
  11819. response_header.c_str(), response_header.size(),
  11820. #endif
  11821. 0);
  11822. std::string chunk(64 * 1024, 'A');
  11823. size_t total_sent = 0;
  11824. while (total_sent < DATA_SIZE) {
  11825. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11826. auto sent = ::send(cli,
  11827. #ifdef _WIN32
  11828. static_cast<const char *>(chunk.c_str()),
  11829. static_cast<int>(to_send),
  11830. #else
  11831. chunk.c_str(), to_send,
  11832. #endif
  11833. 0);
  11834. if (sent <= 0) break;
  11835. total_sent += static_cast<size_t>(sent);
  11836. }
  11837. detail::close_socket(cli);
  11838. }
  11839. detail::close_socket(srv);
  11840. });
  11841. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11842. size_t total_received = 0;
  11843. {
  11844. Client cli("127.0.0.1", PORT + 2);
  11845. cli.set_read_timeout(10, 0);
  11846. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11847. auto res =
  11848. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11849. total_received += data_length;
  11850. return true;
  11851. });
  11852. // Should fail because 200MB exceeds the explicit 150MB limit
  11853. EXPECT_FALSE(res);
  11854. }
  11855. server_thread.join();
  11856. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11857. << "Client with content_receiver should respect the explicit "
  11858. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11859. << total_received << " bytes.";
  11860. }
  11861. // Verify that an explicit set_payload_max_length larger than the response
  11862. // allows the content_receiver to read all data successfully.
  11863. TEST(ClientVulnerabilityTest,
  11864. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11865. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11866. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11867. #ifndef _WIN32
  11868. signal(SIGPIPE, SIG_IGN);
  11869. #endif
  11870. auto server_thread = std::thread([] {
  11871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11872. default_socket_options(srv);
  11873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11875. sockaddr_in addr{};
  11876. addr.sin_family = AF_INET;
  11877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11879. int opt = 1;
  11880. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11881. #ifdef _WIN32
  11882. reinterpret_cast<const char *>(&opt),
  11883. #else
  11884. &opt,
  11885. #endif
  11886. sizeof(opt));
  11887. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11888. ::listen(srv, 1);
  11889. sockaddr_in cli_addr{};
  11890. socklen_t cli_len = sizeof(cli_addr);
  11891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11892. if (cli != INVALID_SOCKET) {
  11893. char buf[4096];
  11894. ::recv(cli, buf, sizeof(buf), 0);
  11895. auto content_length = std::to_string(DATA_SIZE);
  11896. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11897. "Content-Length: " +
  11898. content_length +
  11899. "\r\n"
  11900. "Connection: close\r\n"
  11901. "\r\n";
  11902. ::send(cli,
  11903. #ifdef _WIN32
  11904. static_cast<const char *>(response_header.c_str()),
  11905. static_cast<int>(response_header.size()),
  11906. #else
  11907. response_header.c_str(), response_header.size(),
  11908. #endif
  11909. 0);
  11910. std::string chunk(64 * 1024, 'A');
  11911. size_t total_sent = 0;
  11912. while (total_sent < DATA_SIZE) {
  11913. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11914. auto sent = ::send(cli,
  11915. #ifdef _WIN32
  11916. static_cast<const char *>(chunk.c_str()),
  11917. static_cast<int>(to_send),
  11918. #else
  11919. chunk.c_str(), to_send,
  11920. #endif
  11921. 0);
  11922. if (sent <= 0) break;
  11923. total_sent += static_cast<size_t>(sent);
  11924. }
  11925. #ifdef _WIN32
  11926. ::shutdown(cli, SD_SEND);
  11927. #else
  11928. ::shutdown(cli, SHUT_WR);
  11929. #endif
  11930. char drain[1024];
  11931. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11932. detail::close_socket(cli);
  11933. }
  11934. detail::close_socket(srv);
  11935. });
  11936. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11937. size_t total_received = 0;
  11938. {
  11939. Client cli("127.0.0.1", PORT + 2);
  11940. cli.set_read_timeout(10, 0);
  11941. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11942. auto res =
  11943. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11944. total_received += data_length;
  11945. return true;
  11946. });
  11947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11948. EXPECT_EQ(StatusCode::OK_200, res->status);
  11949. }
  11950. server_thread.join();
  11951. EXPECT_EQ(total_received, DATA_SIZE)
  11952. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11953. << " bytes (larger than " << DATA_SIZE
  11954. << " bytes response), content_receiver should read all data, but only "
  11955. "read "
  11956. << total_received << " bytes.";
  11957. }
  11958. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11959. // Regression test for "zip bomb" attack on the client side: a malicious server
  11960. // sends a small gzip-compressed response that decompresses to a huge payload.
  11961. // The client must enforce payload_max_length on the decompressed size.
  11962. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11963. constexpr size_t DECOMPRESSED_SIZE =
  11964. 10 * 1024 * 1024; // 10MB after decompression
  11965. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11966. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11967. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11968. std::string compressed;
  11969. {
  11970. httplib::detail::gzip_compressor compressor;
  11971. bool ok =
  11972. compressor.compress(uncompressed.data(), uncompressed.size(),
  11973. /*last=*/true, [&](const char *buf, size_t len) {
  11974. compressed.append(buf, len);
  11975. return true;
  11976. });
  11977. ASSERT_TRUE(ok);
  11978. }
  11979. // Sanity: compressed data should be much smaller than the decompressed size
  11980. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11981. #ifndef _WIN32
  11982. signal(SIGPIPE, SIG_IGN);
  11983. #endif
  11984. // Set up the listening socket in the main thread so the server is guaranteed
  11985. // to be ready before the client connects (eliminates race condition).
  11986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11987. default_socket_options(srv);
  11988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11990. sockaddr_in addr{};
  11991. addr.sin_family = AF_INET;
  11992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11994. int opt = 1;
  11995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11996. #ifdef _WIN32
  11997. reinterpret_cast<const char *>(&opt),
  11998. #else
  11999. &opt,
  12000. #endif
  12001. sizeof(opt));
  12002. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12003. ASSERT_EQ(0, ::listen(srv, 1));
  12004. auto server_thread = std::thread([&compressed, srv] {
  12005. sockaddr_in cli_addr{};
  12006. socklen_t cli_len = sizeof(cli_addr);
  12007. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12008. if (cli != INVALID_SOCKET) {
  12009. // Read the full HTTP request (until \r\n\r\n)
  12010. char buf[4096];
  12011. size_t total = 0;
  12012. while (total < sizeof(buf)) {
  12013. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12014. if (n <= 0) break;
  12015. total += static_cast<size_t>(n);
  12016. // Check for end of headers
  12017. if (total >= 4) {
  12018. std::string req(buf, total);
  12019. if (req.find("\r\n\r\n") != std::string::npos) break;
  12020. }
  12021. }
  12022. // Malicious response: gzip-compressed body, no Content-Length
  12023. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12024. "Content-Encoding: gzip\r\n"
  12025. "Connection: close\r\n"
  12026. "\r\n";
  12027. ::send(cli,
  12028. #ifdef _WIN32
  12029. static_cast<const char *>(response_header.c_str()),
  12030. static_cast<int>(response_header.size()),
  12031. #else
  12032. response_header.c_str(), response_header.size(),
  12033. #endif
  12034. 0);
  12035. // Send the compressed payload (small on the wire, huge when decompressed)
  12036. size_t total_sent = 0;
  12037. while (total_sent < compressed.size()) {
  12038. auto to_send = std::min(compressed.size() - total_sent,
  12039. static_cast<size_t>(64 * 1024));
  12040. auto sent =
  12041. ::send(cli,
  12042. #ifdef _WIN32
  12043. static_cast<const char *>(compressed.c_str() + total_sent),
  12044. static_cast<int>(to_send),
  12045. #else
  12046. compressed.c_str() + total_sent, to_send,
  12047. #endif
  12048. 0);
  12049. if (sent <= 0) break;
  12050. total_sent += static_cast<size_t>(sent);
  12051. }
  12052. detail::close_socket(cli);
  12053. }
  12054. });
  12055. auto se = detail::scope_exit([&] {
  12056. detail::close_socket(srv);
  12057. server_thread.join();
  12058. });
  12059. size_t total_decompressed = 0;
  12060. {
  12061. Client cli("127.0.0.1", PORT + 3);
  12062. cli.set_read_timeout(5, 0);
  12063. cli.set_decompress(true);
  12064. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12065. auto stream = cli.open_stream("GET", "/zipbomb");
  12066. ASSERT_TRUE(stream.is_valid());
  12067. char buffer[64 * 1024];
  12068. ssize_t n;
  12069. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12070. total_decompressed += static_cast<size_t>(n);
  12071. }
  12072. }
  12073. // The decompressed size must be capped by payload_max_length. Without
  12074. // protection, the client would decompress the full 10MB from a tiny
  12075. // compressed payload, enabling a zip bomb DoS attack.
  12076. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12077. << "Client decompressed " << total_decompressed
  12078. << " bytes from a gzip response. The decompressed size should be "
  12079. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12080. }
  12081. #endif
  12082. TEST(HostAndPortPropertiesTest, NoSSL) {
  12083. httplib::Client cli("www.google.com", 1234);
  12084. ASSERT_EQ("www.google.com", cli.host());
  12085. ASSERT_EQ(1234, cli.port());
  12086. }
  12087. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12088. httplib::Client cli("www.google.com:1234");
  12089. ASSERT_EQ("www.google.com", cli.host());
  12090. ASSERT_EQ(1234, cli.port());
  12091. }
  12092. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12093. // Port number that overflows int — should not crash, client becomes invalid
  12094. httplib::Client cli("http://www.google.com:99999999999999999999");
  12095. ASSERT_FALSE(cli.is_valid());
  12096. }
  12097. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12098. // Port 99999 exceeds valid range (1-65535) — should not crash
  12099. httplib::Client cli("http://www.google.com:99999");
  12100. ASSERT_FALSE(cli.is_valid());
  12101. }
  12102. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12103. httplib::Client cli("http://www.google.com:80abc");
  12104. ASSERT_FALSE(cli.is_valid());
  12105. }
  12106. #ifdef CPPHTTPLIB_SSL_ENABLED
  12107. TEST(HostAndPortPropertiesTest, SSL) {
  12108. httplib::SSLClient cli("www.google.com");
  12109. ASSERT_EQ("www.google.com", cli.host());
  12110. ASSERT_EQ(443, cli.port());
  12111. }
  12112. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12113. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12114. std::string cert;
  12115. read_file(CA_CERT_FILE, cert);
  12116. httplib::SSLClient httplib_client("www.google.com");
  12117. // Load CA store first time
  12118. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12119. // Load CA store second time (update)
  12120. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12121. // Verify client is still valid and can make connections
  12122. httplib_client.enable_server_certificate_verification(true);
  12123. auto res = httplib_client.Get("/");
  12124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12125. // Google may return 200 or 301 depending on various factors
  12126. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12127. res->status == StatusCode::MovedPermanently_301);
  12128. }
  12129. TEST(SSLClientTest, ServerNameIndication_Online) {
  12130. auto host = "httpbingo.org";
  12131. auto path = std::string{"/get"};
  12132. SSLClient cli(host, 443);
  12133. auto res = cli.Get(path);
  12134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12135. ASSERT_EQ(StatusCode::OK_200, res->status);
  12136. }
  12137. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12138. // Use a site that will cause SSL verification failure due to self-signed cert
  12139. SSLClient cli("self-signed.badssl.com", 443);
  12140. cli.enable_server_certificate_verification(true);
  12141. auto res = cli.Get("/");
  12142. ASSERT_TRUE(!res);
  12143. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12144. // Verify backend error is captured for SSLServerVerification
  12145. // This occurs when certificate verification fails
  12146. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12147. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12148. EXPECT_NE(0UL, res.ssl_backend_error());
  12149. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12150. // For OpenSSL, ssl_error is 0 for verification errors
  12151. EXPECT_EQ(0, res.ssl_error());
  12152. #if !defined(_WIN32) || \
  12153. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12154. // On non-Windows or when Windows Schannel is disabled, the error comes
  12155. // from OpenSSL's verification
  12156. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12157. res.ssl_backend_error());
  12158. #endif
  12159. #endif
  12160. }
  12161. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12162. // Use a site where hostname doesn't match the certificate
  12163. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12164. SSLClient cli("wrong.host.badssl.com", 443);
  12165. cli.enable_server_certificate_verification(true);
  12166. cli.enable_server_hostname_verification(true);
  12167. auto res = cli.Get("/");
  12168. ASSERT_TRUE(!res);
  12169. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12170. // Verify backend error is captured for hostname verification failure
  12171. EXPECT_NE(0UL, res.ssl_backend_error());
  12172. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12173. // For OpenSSL, ssl_error is 0 for verification errors
  12174. EXPECT_EQ(0, res.ssl_error());
  12175. #if !defined(_WIN32) || \
  12176. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12177. // On non-Windows or when Windows Schannel is disabled, the error comes
  12178. // from OpenSSL's hostname verification
  12179. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12180. res.ssl_backend_error());
  12181. #endif
  12182. #endif
  12183. }
  12184. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12185. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12186. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12187. SSLClient cli("www.google.com", 443);
  12188. cli.enable_server_certificate_verification(true);
  12189. auto res = cli.Get("/");
  12190. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12191. }
  12192. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12193. SSLClient cli("www.google.com", 443);
  12194. cli.enable_server_certificate_verification(true);
  12195. cli.enable_windows_certificate_verification(false);
  12196. auto res = cli.Get("/");
  12197. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12198. }
  12199. // The server sends an intermediate cross-signed by a root Windows trusts,
  12200. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12201. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12202. SSLClient cli("accounts.spotify.com", 443);
  12203. auto res = cli.Get("/");
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12205. << " ssl_backend_error=" << res.ssl_backend_error();
  12206. }
  12207. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12208. // policy status, which no backend reports for a self-signed certificate.
  12209. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12210. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12211. ASSERT_TRUE(svr.is_valid());
  12212. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12213. auto se = detail::scope_exit([&] {
  12214. svr.stop();
  12215. t.join();
  12216. ASSERT_FALSE(svr.is_running());
  12217. });
  12218. svr.wait_until_ready();
  12219. SSLClient cli("127.0.0.1", PORT);
  12220. cli.set_connection_timeout(30);
  12221. auto res = cli.Get("/");
  12222. ASSERT_FALSE(res);
  12223. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12224. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12225. }
  12226. #endif
  12227. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12228. Client cli("https://google.com");
  12229. auto res = cli.Get("/");
  12230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12231. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12232. }
  12233. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12234. SSLClient cli("google.com");
  12235. cli.set_ca_cert_path(CA_CERT_FILE);
  12236. auto res = cli.Get("/");
  12237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12238. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12239. }
  12240. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12241. SSLClient cli("google.com");
  12242. cli.enable_server_certificate_verification(true);
  12243. cli.set_ca_cert_path("hello");
  12244. auto res = cli.Get("/");
  12245. ASSERT_TRUE(!res);
  12246. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12247. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12248. // should be set
  12249. EXPECT_EQ(0, res.ssl_error());
  12250. // Verify backend error is captured for SSLLoadingCerts
  12251. // This error occurs when loading CA certificates fails
  12252. EXPECT_NE(0UL, res.ssl_backend_error());
  12253. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12254. // OpenSSL specific error codes:
  12255. // > openssl errstr 0x80000002
  12256. // error:80000002:system library::No such file or directory
  12257. // > openssl errstr 0xA000126
  12258. // error:0A000126:SSL routines::unexpected eof while reading
  12259. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12260. res.ssl_backend_error() == 0xA000126);
  12261. #endif
  12262. }
  12263. TEST(SSLClientTest, ServerCertificateVerification4) {
  12264. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12265. ASSERT_TRUE(svr.is_valid());
  12266. svr.Get("/test", [&](const Request &, Response &res) {
  12267. res.set_content("test", "text/plain");
  12268. svr.stop();
  12269. ASSERT_TRUE(true);
  12270. });
  12271. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12272. auto se = detail::scope_exit([&] {
  12273. t.join();
  12274. ASSERT_FALSE(svr.is_running());
  12275. });
  12276. svr.wait_until_ready();
  12277. SSLClient cli("127.0.0.1", PORT);
  12278. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12279. cli.enable_server_certificate_verification(true);
  12280. cli.set_connection_timeout(30);
  12281. auto res = cli.Get("/test");
  12282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12283. ASSERT_EQ(StatusCode::OK_200, res->status);
  12284. }
  12285. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12286. std::string cert;
  12287. read_file(CA_CERT_FILE, cert);
  12288. SSLClient cli("google.com");
  12289. cli.load_ca_cert_store(cert.data(), cert.size());
  12290. const auto res = cli.Get("/");
  12291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12292. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12293. }
  12294. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12295. // clang-format off
  12296. static constexpr char cert[] =
  12297. "GlobalSign Root CA\n"
  12298. "==================\n"
  12299. "-----BEGIN CERTIFICATE-----\n"
  12300. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12301. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12302. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12303. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12304. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12305. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12306. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12307. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12308. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12309. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12310. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12311. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12312. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12313. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12314. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12315. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12316. "-----END CERTIFICATE-----\n";
  12317. // clang-format on
  12318. SSLClient cli("google.com");
  12319. cli.load_ca_cert_store(cert, sizeof(cert));
  12320. const auto res = cli.Get("/");
  12321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12322. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12323. }
  12324. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12325. SSLClient cli("www.youtube.com");
  12326. cli.set_ca_cert_path(CA_CERT_FILE);
  12327. cli.enable_server_certificate_verification(true);
  12328. cli.set_follow_location(true);
  12329. auto res = cli.Get("/");
  12330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12331. ASSERT_EQ(StatusCode::OK_200, res->status);
  12332. }
  12333. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12334. SSLClient cli("wWw.YouTube.Com");
  12335. cli.set_ca_cert_path(CA_CERT_FILE);
  12336. cli.enable_server_certificate_verification(true);
  12337. cli.enable_server_hostname_verification(true);
  12338. cli.set_follow_location(true);
  12339. auto res = cli.Get("/");
  12340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12341. ASSERT_EQ(StatusCode::OK_200, res->status);
  12342. }
  12343. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12344. SSLClient cli("gOoGlE.COm");
  12345. cli.enable_server_certificate_verification(true);
  12346. cli.enable_server_hostname_verification(true);
  12347. cli.set_follow_location(true);
  12348. auto res = cli.Get("/");
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. ASSERT_EQ(StatusCode::OK_200, res->status);
  12351. }
  12352. TEST(SSLClientTest, Issue2004_Online) {
  12353. Client client("https://google.com");
  12354. client.set_follow_location(true);
  12355. auto res = client.Get("/");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. ASSERT_EQ(StatusCode::OK_200, res->status);
  12358. auto body = res->body;
  12359. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12360. }
  12361. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12362. // Create SSLClient with invalid cert/key to make is_valid() return false
  12363. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12364. "nonexistent_key.pem");
  12365. // is_valid() should be false due to cert loading failure
  12366. ASSERT_FALSE(cli.is_valid());
  12367. auto res = cli.Get("/");
  12368. ASSERT_FALSE(res);
  12369. EXPECT_EQ(Error::SSLConnection, res.error());
  12370. }
  12371. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12372. // Test for Issue #2251: SSL error not properly reported when client cert
  12373. // and key paths are swapped or mismatched
  12374. // This simulates the scenario where user accidentally swaps the cert and key
  12375. // files
  12376. // Using client cert file as private key and vice versa (completely wrong)
  12377. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12378. // Should fail validation due to cert/key mismatch
  12379. ASSERT_FALSE(cli.is_valid());
  12380. // Attempt to make a request should fail with proper error
  12381. auto res = cli.Get("/");
  12382. ASSERT_FALSE(res);
  12383. EXPECT_EQ(Error::SSLConnection, res.error());
  12384. // SSL error should be recorded in the Result object (this is the key fix for
  12385. // Issue #2251)
  12386. auto backend_error = res.ssl_backend_error();
  12387. EXPECT_NE(0u, backend_error);
  12388. }
  12389. // Tests cert/key mismatch detection at the TLS context level
  12390. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12391. // Test that using mismatched cert/key causes connection failure.
  12392. // We verify this at the SSLClient level rather than through internal
  12393. // TLS API functions.
  12394. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12395. cli.enable_server_certificate_verification(false);
  12396. cli.set_connection_timeout(2);
  12397. // The mismatch should cause a connection or handshake error
  12398. auto res = cli.Get("/test");
  12399. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12400. // Either way, the request should fail
  12401. EXPECT_FALSE(res);
  12402. }
  12403. #endif
  12404. #if 0
  12405. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12406. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12407. ASSERT_TRUE(cli != nullptr);
  12408. cli->set_address_family(AF_INET6);
  12409. cli->set_interface("en0");
  12410. auto res = cli->Get("/get");
  12411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12412. ASSERT_EQ(StatusCode::OK_200, res->status);
  12413. }
  12414. #endif
  12415. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12416. #ifdef CPPHTTPLIB_SSL_ENABLED
  12417. void ClientCertPresent(
  12418. const std::string &client_cert_file,
  12419. const std::string &client_private_key_file,
  12420. const std::string &client_encrypted_private_key_pass = std::string()) {
  12421. using namespace httplib::tls;
  12422. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12423. CLIENT_CA_CERT_DIR);
  12424. ASSERT_TRUE(svr.is_valid());
  12425. svr.Get("/test", [&](const Request &req, Response &res) {
  12426. res.set_content("test", "text/plain");
  12427. auto cert = req.peer_cert();
  12428. ASSERT_TRUE(static_cast<bool>(cert));
  12429. std::string common_name = cert.subject_cn();
  12430. EXPECT_EQ("Common Name", common_name);
  12431. });
  12432. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12433. auto se = detail::scope_exit([&] {
  12434. svr.stop();
  12435. t.join();
  12436. ASSERT_FALSE(svr.is_running());
  12437. });
  12438. svr.wait_until_ready();
  12439. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12440. client_encrypted_private_key_pass);
  12441. cli.enable_server_certificate_verification(false);
  12442. cli.set_connection_timeout(30);
  12443. auto res = cli.Get("/test");
  12444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12445. ASSERT_EQ(StatusCode::OK_200, res->status);
  12446. }
  12447. TEST(SSLClientServerTest, ClientCertPresent) {
  12448. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12449. }
  12450. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12451. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12452. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12453. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12454. }
  12455. // PEM memory-based constructor tests (works with all TLS backends)
  12456. void PemMemoryClientCertPresent(
  12457. const std::string &client_cert_file,
  12458. const std::string &client_private_key_file,
  12459. const std::string &client_encrypted_private_key_pass = std::string()) {
  12460. // Read PEM files into memory
  12461. std::string server_cert_pem, server_key_pem;
  12462. std::string client_ca_pem;
  12463. std::string client_cert_pem, client_key_pem;
  12464. read_file(SERVER_CERT_FILE, server_cert_pem);
  12465. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12466. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12467. read_file(client_cert_file, client_cert_pem);
  12468. read_file(client_private_key_file, client_key_pem);
  12469. // Create server with PEM memory
  12470. SSLServer::PemMemory server_pem = {
  12471. server_cert_pem.c_str(),
  12472. server_cert_pem.size(),
  12473. server_key_pem.c_str(),
  12474. server_key_pem.size(),
  12475. client_ca_pem.c_str(),
  12476. client_ca_pem.size(),
  12477. nullptr // no password for server key
  12478. };
  12479. SSLServer svr(server_pem);
  12480. ASSERT_TRUE(svr.is_valid());
  12481. svr.Get("/test", [&](const Request &, Response &res) {
  12482. res.set_content("test", "text/plain");
  12483. });
  12484. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12485. auto se = detail::scope_exit([&] {
  12486. svr.stop();
  12487. t.join();
  12488. ASSERT_FALSE(svr.is_running());
  12489. });
  12490. svr.wait_until_ready();
  12491. // Create client with PEM memory
  12492. const char *password = client_encrypted_private_key_pass.empty()
  12493. ? nullptr
  12494. : client_encrypted_private_key_pass.c_str();
  12495. SSLClient::PemMemory client_pem = {
  12496. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12497. client_key_pem.size(), password};
  12498. SSLClient cli(HOST, PORT, client_pem);
  12499. cli.enable_server_certificate_verification(false);
  12500. cli.set_connection_timeout(30);
  12501. auto res = cli.Get("/test");
  12502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12503. ASSERT_EQ(StatusCode::OK_200, res->status);
  12504. }
  12505. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12506. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12507. }
  12508. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12509. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12510. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12511. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12512. }
  12513. TEST(SSLClientServerTest, ClientCertMissing) {
  12514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12515. CLIENT_CA_CERT_DIR);
  12516. ASSERT_TRUE(svr.is_valid());
  12517. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12518. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12519. auto se = detail::scope_exit([&] {
  12520. svr.stop();
  12521. t.join();
  12522. ASSERT_FALSE(svr.is_running());
  12523. });
  12524. svr.wait_until_ready();
  12525. SSLClient cli(HOST, PORT);
  12526. cli.set_connection_timeout(30);
  12527. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12528. // the chain check on Windows, so the result does not depend on the order.
  12529. cli.enable_server_hostname_verification(false);
  12530. auto res = cli.Get("/test");
  12531. ASSERT_TRUE(!res);
  12532. // When client cert is missing and server requires it, connection fails
  12533. // Error type depends on backend implementation
  12534. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12535. res.error() == Error::SSLConnection);
  12536. // Verify backend error is captured
  12537. // Note: This test may have different error codes depending on the exact
  12538. // verification failure
  12539. EXPECT_NE(0UL, res.ssl_backend_error());
  12540. }
  12541. TEST(SSLClientServerTest, TrustDirOptional) {
  12542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12543. ASSERT_TRUE(svr.is_valid());
  12544. svr.Get("/test", [&](const Request &, Response &res) {
  12545. res.set_content("test", "text/plain");
  12546. });
  12547. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12548. auto se = detail::scope_exit([&] {
  12549. svr.stop();
  12550. t.join();
  12551. ASSERT_FALSE(svr.is_running());
  12552. });
  12553. svr.wait_until_ready();
  12554. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12555. cli.enable_server_certificate_verification(false);
  12556. cli.set_connection_timeout(30);
  12557. auto res = cli.Get("/test");
  12558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12559. ASSERT_EQ(StatusCode::OK_200, res->status);
  12560. }
  12561. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12562. class NoListenSSLServer : public SSLServer {
  12563. public:
  12564. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12565. const char *client_ca_cert_file_path,
  12566. const char *client_ca_cert_dir_path = nullptr)
  12567. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12568. client_ca_cert_dir_path),
  12569. stop_(false) {}
  12570. std::atomic_bool stop_;
  12571. private:
  12572. bool process_and_close_socket(socket_t /*sock*/) override {
  12573. // Don't create SSL context
  12574. while (!stop_.load()) {
  12575. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12576. }
  12577. return true;
  12578. }
  12579. };
  12580. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12581. CLIENT_CA_CERT_FILE);
  12582. ASSERT_TRUE(svr.is_valid());
  12583. svr.Get("/test", [&](const Request &, Response &res) {
  12584. res.set_content("test", "text/plain");
  12585. });
  12586. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12587. auto se = detail::scope_exit([&] {
  12588. svr.stop_ = true;
  12589. svr.stop();
  12590. t.join();
  12591. ASSERT_FALSE(svr.is_running());
  12592. });
  12593. svr.wait_until_ready();
  12594. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12595. cli.enable_server_certificate_verification(false);
  12596. cli.set_connection_timeout(1);
  12597. auto res = cli.Get("/test");
  12598. ASSERT_TRUE(!res);
  12599. EXPECT_EQ(Error::SSLConnection, res.error());
  12600. // Timeout results in WantRead error code (maps to backend-specific value)
  12601. EXPECT_NE(0, res.ssl_error());
  12602. }
  12603. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12604. // Test SSLServer with client certificate verification using the standard
  12605. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12607. CLIENT_CA_CERT_DIR);
  12608. ASSERT_TRUE(svr.is_valid());
  12609. svr.Get("/test", [&](const Request &req, Response &res) {
  12610. res.set_content("test", "text/plain");
  12611. auto cert = req.peer_cert();
  12612. ASSERT_TRUE(static_cast<bool>(cert));
  12613. auto common_name = cert.subject_cn();
  12614. EXPECT_EQ("Common Name", common_name);
  12615. });
  12616. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12617. auto se = detail::scope_exit([&] {
  12618. svr.stop();
  12619. t.join();
  12620. ASSERT_FALSE(svr.is_running());
  12621. });
  12622. svr.wait_until_ready();
  12623. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12624. cli.enable_server_certificate_verification(false);
  12625. cli.set_connection_timeout(30);
  12626. auto res = cli.Get("/test");
  12627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12628. ASSERT_EQ(StatusCode::OK_200, res->status);
  12629. }
  12630. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12631. // Verifies that wildcard matching and exact matching work consistently
  12632. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12633. using namespace httplib::tls;
  12634. // We need a running server to test against
  12635. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12636. ASSERT_TRUE(svr.is_valid());
  12637. svr.Get("/test", [](const Request &, Response &res) {
  12638. res.set_content("ok", "text/plain");
  12639. });
  12640. thread t([&]() { svr.listen(HOST, PORT); });
  12641. auto se = detail::scope_exit([&] {
  12642. svr.stop();
  12643. t.join();
  12644. });
  12645. svr.wait_until_ready();
  12646. bool verify_callback_called = false;
  12647. bool verify_result_wrong = false;
  12648. SSLClient cli(HOST, PORT);
  12649. cli.enable_server_certificate_verification(true);
  12650. cli.set_ca_cert_path(CA_CERT_FILE);
  12651. cli.set_connection_timeout(5);
  12652. // Note: Test certificate has CN="Common Name", not "localhost"
  12653. bool verify_result_cn = false;
  12654. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12655. verify_callback_called = true;
  12656. if (!ctx.cert) return false;
  12657. // Test 1: "Common Name" should match (our test server cert CN)
  12658. verify_result_cn = ctx.check_hostname("Common Name");
  12659. // Test 2: wrong hostname should not match
  12660. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12661. return true; // Accept for the purpose of this test
  12662. });
  12663. auto res = cli.Get("/test");
  12664. // The request may succeed or fail depending on cert configuration
  12665. // but the callback should have been called
  12666. ASSERT_TRUE(verify_callback_called)
  12667. << "Verify callback should have been called";
  12668. // CN="Common Name" should match our test certificate
  12669. //
  12670. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12671. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12672. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12673. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12674. // <openssl/base.h>, which is included transitively when
  12675. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12676. #if defined(OPENSSL_IS_BORINGSSL)
  12677. EXPECT_FALSE(verify_result_cn)
  12678. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12679. #else
  12680. EXPECT_TRUE(verify_result_cn)
  12681. << "verify_hostname should match 'Common Name' (certificate CN)";
  12682. #endif
  12683. // Wrong hostname should not match
  12684. EXPECT_FALSE(verify_result_wrong)
  12685. << "verify_hostname should not match 'wronghost.example.com'";
  12686. }
  12687. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12688. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12689. // X509_check_ip behavior and must hold for every backend.
  12690. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12691. using namespace httplib::tls;
  12692. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12693. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12694. ASSERT_TRUE(svr.is_valid());
  12695. svr.Get("/test", [](const Request &, Response &res) {
  12696. res.set_content("ok", "text/plain");
  12697. });
  12698. thread t([&]() { svr.listen(HOST, PORT); });
  12699. auto se = detail::scope_exit([&] {
  12700. svr.stop();
  12701. t.join();
  12702. });
  12703. svr.wait_until_ready();
  12704. bool verify_callback_called = false;
  12705. bool ip_matched_via_cn = true;
  12706. SSLClient cli(HOST, PORT);
  12707. cli.enable_server_certificate_verification(true);
  12708. cli.set_ca_cert_path(CA_CERT_FILE);
  12709. cli.set_connection_timeout(5);
  12710. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12711. verify_callback_called = true;
  12712. if (!ctx.cert) return false;
  12713. // The IP appears only in the CN, so it must NOT be accepted.
  12714. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12715. return true; // Accept for the purpose of this test
  12716. });
  12717. cli.Get("/test");
  12718. ASSERT_TRUE(verify_callback_called)
  12719. << "Verify callback should have been called";
  12720. EXPECT_FALSE(ip_matched_via_cn)
  12721. << "An IP host must not be authenticated via the certificate CN";
  12722. }
  12723. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12724. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12725. using namespace httplib::tls;
  12726. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12727. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12728. ASSERT_TRUE(svr.is_valid());
  12729. svr.Get("/test", [](const Request &, Response &res) {
  12730. res.set_content("ok", "text/plain");
  12731. });
  12732. thread t([&]() { svr.listen(HOST, PORT); });
  12733. auto se = detail::scope_exit([&] {
  12734. svr.stop();
  12735. t.join();
  12736. });
  12737. svr.wait_until_ready();
  12738. bool verify_callback_called = false;
  12739. bool san_matched = false;
  12740. bool wrong_ipv6_matched = true;
  12741. bool cn_ipv6_matched = true;
  12742. SSLClient cli(HOST, PORT);
  12743. cli.enable_server_certificate_verification(true);
  12744. cli.set_ca_cert_path(CA_CERT_FILE);
  12745. cli.set_connection_timeout(5);
  12746. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12747. verify_callback_called = true;
  12748. if (!ctx.cert) return false;
  12749. // Matches the IPv6 iPAddress SAN.
  12750. san_matched = ctx.check_hostname("2001:db8::1");
  12751. // A different IPv6 address must not match.
  12752. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12753. // "::1" lives only in the CN, so it must not be accepted.
  12754. cn_ipv6_matched = ctx.check_hostname("::1");
  12755. return true; // Accept for the purpose of this test
  12756. });
  12757. cli.Get("/test");
  12758. ASSERT_TRUE(verify_callback_called)
  12759. << "Verify callback should have been called";
  12760. EXPECT_TRUE(san_matched)
  12761. << "verify_hostname should match an IPv6 iPAddress SAN";
  12762. EXPECT_FALSE(wrong_ipv6_matched)
  12763. << "verify_hostname should not match a non-matching IPv6 address";
  12764. EXPECT_FALSE(cn_ipv6_matched)
  12765. << "An IPv6 host must not be authenticated via the certificate CN";
  12766. }
  12767. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12768. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12769. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12770. using namespace httplib::tls;
  12771. // SANs: DNS:a.zz, IP:42.46.122.122
  12772. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12773. ASSERT_TRUE(svr.is_valid());
  12774. svr.Get("/test", [](const Request &, Response &res) {
  12775. res.set_content("ok", "text/plain");
  12776. });
  12777. auto port = svr.bind_to_any_port(HOST);
  12778. thread t([&]() { svr.listen_after_bind(); });
  12779. auto se = detail::scope_exit([&] {
  12780. svr.stop();
  12781. t.join();
  12782. });
  12783. svr.wait_until_ready();
  12784. bool verify_callback_called = false;
  12785. bool dns_san_matched = false;
  12786. bool ip_san_matched = false;
  12787. bool ip_matched_via_dns_san = true;
  12788. bool dns_matched_via_ip_san = true;
  12789. SSLClient cli(HOST, port);
  12790. cli.enable_server_certificate_verification(true);
  12791. cli.set_ca_cert_path(CA_CERT_FILE);
  12792. cli.set_connection_timeout(5);
  12793. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12794. verify_callback_called = true;
  12795. if (!ctx.cert) return false;
  12796. dns_san_matched = ctx.check_hostname("a.zz");
  12797. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12798. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12799. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12800. return true; // Accept for the purpose of this test
  12801. });
  12802. cli.Get("/test");
  12803. ASSERT_TRUE(verify_callback_called)
  12804. << "Verify callback should have been called";
  12805. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12806. EXPECT_TRUE(ip_san_matched)
  12807. << "verify_hostname should match an iPAddress SAN";
  12808. EXPECT_FALSE(ip_matched_via_dns_san)
  12809. << "An IP host must not be authenticated via a dNSName SAN";
  12810. EXPECT_FALSE(dns_matched_via_ip_san)
  12811. << "A DNS host must not be authenticated via an iPAddress SAN";
  12812. }
  12813. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12814. // "www.*.example.test" names one host and not every host under example.test.
  12815. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12816. using namespace httplib::tls;
  12817. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12818. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12819. ASSERT_TRUE(svr.is_valid());
  12820. svr.Get("/test", [](const Request &, Response &res) {
  12821. res.set_content("ok", "text/plain");
  12822. });
  12823. auto port = svr.bind_to_any_port(HOST);
  12824. thread t([&]() { svr.listen_after_bind(); });
  12825. auto se = detail::scope_exit([&] {
  12826. svr.stop();
  12827. t.join();
  12828. });
  12829. svr.wait_until_ready();
  12830. bool verify_callback_called = false;
  12831. bool leftmost_wildcard_matched = false;
  12832. bool wildcard_spanned_labels = true;
  12833. bool inner_wildcard_matched = true;
  12834. SSLClient cli(HOST, port);
  12835. cli.enable_server_certificate_verification(true);
  12836. cli.set_ca_cert_path(CA_CERT_FILE);
  12837. cli.set_connection_timeout(5);
  12838. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12839. verify_callback_called = true;
  12840. if (!ctx.cert) return false;
  12841. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12842. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12843. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12844. return true; // Accept for the purpose of this test
  12845. });
  12846. cli.Get("/test");
  12847. ASSERT_TRUE(verify_callback_called)
  12848. << "Verify callback should have been called";
  12849. EXPECT_TRUE(leftmost_wildcard_matched)
  12850. << "A leftmost wildcard should match a single label";
  12851. EXPECT_FALSE(wildcard_spanned_labels)
  12852. << "A wildcard label must not match more than one label";
  12853. EXPECT_FALSE(inner_wildcard_matched)
  12854. << "A wildcard outside the leftmost label must not be honoured";
  12855. }
  12856. // sans() must report each SAN entry under its own type.
  12857. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12858. using namespace httplib::tls;
  12859. // SANs: DNS:a.zz, IP:42.46.122.122
  12860. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12861. ASSERT_TRUE(svr.is_valid());
  12862. svr.Get("/test", [](const Request &, Response &res) {
  12863. res.set_content("ok", "text/plain");
  12864. });
  12865. auto port = svr.bind_to_any_port(HOST);
  12866. thread t([&]() { svr.listen_after_bind(); });
  12867. auto se = detail::scope_exit([&] {
  12868. svr.stop();
  12869. t.join();
  12870. });
  12871. svr.wait_until_ready();
  12872. bool verify_callback_called = false;
  12873. std::vector<SanEntry> sans;
  12874. SSLClient cli(HOST, port);
  12875. cli.enable_server_certificate_verification(true);
  12876. cli.set_ca_cert_path(CA_CERT_FILE);
  12877. cli.set_connection_timeout(5);
  12878. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12879. verify_callback_called = true;
  12880. if (!ctx.cert) return false;
  12881. sans = ctx.sans();
  12882. return true; // Accept for the purpose of this test
  12883. });
  12884. cli.Get("/test");
  12885. ASSERT_TRUE(verify_callback_called)
  12886. << "Verify callback should have been called";
  12887. auto has_san = [&](SanType type, const std::string &value) {
  12888. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12889. return san.type == type && san.value == value;
  12890. });
  12891. };
  12892. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12893. << "sans() should report the dNSName SAN";
  12894. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12895. << "sans() should report the iPAddress SAN";
  12896. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12897. << "sans() must not report the dNSName SAN as an address";
  12898. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12899. << "sans() must not report the iPAddress SAN as a DNS name";
  12900. }
  12901. #endif
  12902. // mbedTLS-specific callback constructor test
  12903. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12904. #ifdef CPPHTTPLIB_SSL_ENABLED
  12905. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12907. ASSERT_TRUE(svr.is_valid());
  12908. // Set up a handler to verify client certificate is present
  12909. bool client_cert_verified = false;
  12910. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12911. // Verify that client certificate was provided
  12912. client_cert_verified = true;
  12913. res.set_content("success", "text/plain");
  12914. });
  12915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12916. auto se = detail::scope_exit([&] {
  12917. svr.stop();
  12918. t.join();
  12919. ASSERT_FALSE(svr.is_running());
  12920. });
  12921. svr.wait_until_ready();
  12922. // Client with certificate
  12923. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12924. cli.enable_server_certificate_verification(false);
  12925. cli.set_connection_timeout(30);
  12926. auto res = cli.Get("/test");
  12927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12928. ASSERT_EQ(StatusCode::OK_200, res->status);
  12929. ASSERT_TRUE(client_cert_verified);
  12930. EXPECT_EQ("success", res->body);
  12931. }
  12932. #endif
  12933. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12934. // backends
  12935. #ifdef CPPHTTPLIB_SSL_ENABLED
  12936. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12937. using namespace httplib::tls;
  12938. // Test that when client CA cert file is provided,
  12939. // the server properly requests and validates client certificates
  12940. // Create a server with client authentication
  12941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12942. ASSERT_TRUE(svr.is_valid());
  12943. bool handler_called = false;
  12944. svr.Get("/test", [&](const Request &req, Response &res) {
  12945. handler_called = true;
  12946. // Verify that a client certificate was provided
  12947. auto cert = req.peer_cert();
  12948. ASSERT_TRUE(static_cast<bool>(cert));
  12949. // Get the issuer name
  12950. std::string issuer_str = cert.issuer_name();
  12951. ASSERT_FALSE(issuer_str.empty());
  12952. // The client certificate should be issued by our test CA
  12953. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12954. res.set_content("authenticated", "text/plain");
  12955. });
  12956. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12957. auto se = detail::scope_exit([&] {
  12958. svr.stop();
  12959. t.join();
  12960. ASSERT_FALSE(svr.is_running());
  12961. });
  12962. svr.wait_until_ready();
  12963. // Connect with a client certificate issued by the CA
  12964. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12965. cli.enable_server_certificate_verification(false);
  12966. cli.set_connection_timeout(30);
  12967. auto res = cli.Get("/test");
  12968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12969. ASSERT_EQ(StatusCode::OK_200, res->status);
  12970. ASSERT_TRUE(handler_called);
  12971. EXPECT_EQ("authenticated", res->body);
  12972. }
  12973. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12974. using namespace httplib::tls;
  12975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12976. ASSERT_TRUE(svr.is_valid());
  12977. svr.Get("/test", [](const Request &, Response &res) {
  12978. res.set_content("ok", "text/plain");
  12979. });
  12980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12981. auto se = detail::scope_exit([&] {
  12982. svr.stop();
  12983. t.join();
  12984. });
  12985. svr.wait_until_ready();
  12986. SSLClient cli(HOST, PORT);
  12987. cli.enable_server_certificate_verification(false);
  12988. cli.set_connection_timeout(30);
  12989. bool cert_checked = false;
  12990. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12991. if (ctx.cert) {
  12992. auto sans = ctx.sans();
  12993. // Test certificate may or may not have SANs - just verify the API
  12994. // works If SANs exist, verify the types are valid
  12995. for (const auto &san : sans) {
  12996. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12997. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12998. san.type == SanType::OTHER);
  12999. EXPECT_FALSE(san.value.empty());
  13000. }
  13001. cert_checked = true;
  13002. }
  13003. return true;
  13004. });
  13005. auto res = cli.Get("/test");
  13006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13007. EXPECT_TRUE(cert_checked);
  13008. }
  13009. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13010. using namespace httplib::tls;
  13011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13012. ASSERT_TRUE(svr.is_valid());
  13013. svr.Get("/test", [](const Request &, Response &res) {
  13014. res.set_content("ok", "text/plain");
  13015. });
  13016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13017. auto se = detail::scope_exit([&] {
  13018. svr.stop();
  13019. t.join();
  13020. });
  13021. svr.wait_until_ready();
  13022. SSLClient cli(HOST, PORT);
  13023. cli.enable_server_certificate_verification(false);
  13024. cli.set_connection_timeout(30);
  13025. bool validity_checked = false;
  13026. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13027. if (ctx.cert) {
  13028. time_t not_before = 0, not_after = 0;
  13029. bool result = ctx.validity(not_before, not_after);
  13030. EXPECT_TRUE(result);
  13031. // Verify that not_before < now < not_after for a valid cert
  13032. time_t now = time(nullptr);
  13033. EXPECT_LT(not_before, now);
  13034. EXPECT_GT(not_after, now);
  13035. validity_checked = true;
  13036. }
  13037. return true;
  13038. });
  13039. auto res = cli.Get("/test");
  13040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13041. EXPECT_TRUE(validity_checked);
  13042. }
  13043. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13044. using namespace httplib::tls;
  13045. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13046. ASSERT_TRUE(svr.is_valid());
  13047. svr.Get("/test", [](const Request &, Response &res) {
  13048. res.set_content("ok", "text/plain");
  13049. });
  13050. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13051. auto se = detail::scope_exit([&] {
  13052. svr.stop();
  13053. t.join();
  13054. });
  13055. svr.wait_until_ready();
  13056. SSLClient cli(HOST, PORT);
  13057. cli.enable_server_certificate_verification(false);
  13058. cli.set_connection_timeout(30);
  13059. bool serial_checked = false;
  13060. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13061. if (ctx.cert) {
  13062. std::string serial = ctx.serial();
  13063. EXPECT_FALSE(serial.empty());
  13064. // Serial should be a hex string
  13065. for (char c : serial) {
  13066. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13067. (c >= 'a' && c <= 'f'));
  13068. }
  13069. serial_checked = true;
  13070. }
  13071. return true;
  13072. });
  13073. auto res = cli.Get("/test");
  13074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13075. EXPECT_TRUE(serial_checked);
  13076. }
  13077. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13078. // Test 1: Valid CA file - no error should be recorded
  13079. {
  13080. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13081. CLIENT_CA_CERT_FILE);
  13082. ASSERT_TRUE(svr.is_valid());
  13083. // With valid setup, last_ssl_error should be 0
  13084. EXPECT_EQ(0, svr.ssl_last_error());
  13085. }
  13086. // Test 2: Invalid CA file content
  13087. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13088. {
  13089. // Create a temporary file with completely invalid content
  13090. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13091. {
  13092. std::ofstream ofs(temp_invalid_ca);
  13093. ofs << "This is not a certificate file at all\n";
  13094. ofs << "Just plain text content\n";
  13095. }
  13096. // Create server with invalid CA file
  13097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13098. // Clean up temporary file
  13099. std::remove(temp_invalid_ca);
  13100. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13101. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13102. // Note: SSL_CTX_load_verify_locations typically fails first,
  13103. // but our error handling code path is still exercised
  13104. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13105. }
  13106. }
  13107. TEST(VerifyCallbackTest, VerifyContextFields) {
  13108. using namespace httplib::tls;
  13109. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13110. ASSERT_TRUE(svr.is_valid());
  13111. svr.Get("/test", [](const Request &, Response &res) {
  13112. res.set_content("ok", "text/plain");
  13113. });
  13114. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13115. auto se = detail::scope_exit([&] {
  13116. svr.stop();
  13117. t.join();
  13118. });
  13119. svr.wait_until_ready();
  13120. SSLClient cli(HOST, PORT);
  13121. cli.enable_server_certificate_verification(false);
  13122. cli.set_connection_timeout(30);
  13123. int callback_count = 0;
  13124. bool saw_leaf_cert = false;
  13125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13126. if (ctx.cert) {
  13127. callback_count++;
  13128. // We should see at least one certificate (the leaf)
  13129. std::string cn = ctx.subject_cn();
  13130. if (!cn.empty()) { saw_leaf_cert = true; }
  13131. // Verify context fields are populated
  13132. EXPECT_NE(ctx.session, nullptr);
  13133. EXPECT_GE(ctx.depth, 0);
  13134. }
  13135. return true;
  13136. });
  13137. auto res = cli.Get("/test");
  13138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13139. EXPECT_GT(callback_count, 0);
  13140. EXPECT_TRUE(saw_leaf_cert);
  13141. }
  13142. // A verifier belongs to the client that set it, not to the thread that set it.
  13143. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13144. using namespace httplib::tls;
  13145. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13146. ASSERT_TRUE(svr.is_valid());
  13147. svr.Get("/test", [](const Request &, Response &res) {
  13148. res.set_content("ok", "text/plain");
  13149. });
  13150. auto port = svr.bind_to_any_port(HOST);
  13151. thread t([&]() { svr.listen_after_bind(); });
  13152. auto se = detail::scope_exit([&] {
  13153. svr.stop();
  13154. t.join();
  13155. });
  13156. svr.wait_until_ready();
  13157. auto rejecting_calls = 0;
  13158. SSLClient rejecting(HOST, port);
  13159. rejecting.enable_server_certificate_verification(false);
  13160. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13161. rejecting_calls++;
  13162. return false;
  13163. });
  13164. auto accepting_calls = 0;
  13165. SSLClient accepting(HOST, port);
  13166. accepting.enable_server_certificate_verification(false);
  13167. // Set on another thread than the requests below.
  13168. thread([&]() {
  13169. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13170. accepting_calls++;
  13171. return true;
  13172. });
  13173. }).join();
  13174. // Requested on another thread than the verifier was set on.
  13175. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13176. EXPECT_GT(rejecting_calls, 0);
  13177. auto res = accepting.Get("/test");
  13178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13179. EXPECT_GT(accepting_calls, 0);
  13180. }
  13181. // VerifyContext::session is the same handle the other tls:: functions take.
  13182. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13183. using namespace httplib::tls;
  13184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13185. ASSERT_TRUE(svr.is_valid());
  13186. svr.Get("/test", [](const Request &, Response &res) {
  13187. res.set_content("ok", "text/plain");
  13188. });
  13189. auto port = svr.bind_to_any_port(HOST);
  13190. thread t([&]() { svr.listen_after_bind(); });
  13191. auto se = detail::scope_exit([&] {
  13192. svr.stop();
  13193. t.join();
  13194. });
  13195. svr.wait_until_ready();
  13196. SSLClient cli(HOST, port);
  13197. cli.enable_server_certificate_verification(false);
  13198. session_t verifier_session = nullptr;
  13199. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13200. verifier_session = ctx.session;
  13201. return true;
  13202. });
  13203. session_t session_verifier_session = nullptr;
  13204. cli.set_session_verifier([&](session_t session) {
  13205. session_verifier_session = session;
  13206. return SSLVerifierResponse::NoDecisionMade;
  13207. });
  13208. auto res = cli.Get("/test");
  13209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13210. EXPECT_NE(nullptr, verifier_session);
  13211. EXPECT_EQ(session_verifier_session, verifier_session);
  13212. }
  13213. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13214. using httplib::tls::TlsError;
  13215. // Test that verify_error_to_string returns empty for success
  13216. std::string success_str = TlsError::verify_error_to_string(0);
  13217. EXPECT_TRUE(success_str.empty());
  13218. // Test that verify_error_to_string returns non-empty for error codes
  13219. // Using a common error code (certificate expired)
  13220. std::string error_str =
  13221. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13222. EXPECT_FALSE(error_str.empty());
  13223. }
  13224. TEST(SessionVerifierTest, CertificateAccepted) {
  13225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13226. ASSERT_TRUE(svr.is_valid());
  13227. svr.Get("/test", [](const Request &, Response &res) {
  13228. res.set_content("ok", "text/plain");
  13229. });
  13230. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13231. auto se = detail::scope_exit([&] {
  13232. svr.stop();
  13233. t.join();
  13234. });
  13235. svr.wait_until_ready();
  13236. SSLClient cli(HOST, PORT);
  13237. cli.enable_server_certificate_verification(false);
  13238. cli.set_connection_timeout(30);
  13239. bool callback_called = false;
  13240. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13241. EXPECT_NE(session, nullptr);
  13242. callback_called = true;
  13243. return SSLVerifierResponse::CertificateAccepted;
  13244. });
  13245. auto res = cli.Get("/test");
  13246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13247. EXPECT_EQ(200, res->status);
  13248. EXPECT_TRUE(callback_called);
  13249. }
  13250. TEST(SessionVerifierTest, CertificateRejected) {
  13251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13252. ASSERT_TRUE(svr.is_valid());
  13253. svr.Get("/test", [](const Request &, Response &res) {
  13254. res.set_content("ok", "text/plain");
  13255. });
  13256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13257. auto se = detail::scope_exit([&] {
  13258. svr.stop();
  13259. t.join();
  13260. });
  13261. svr.wait_until_ready();
  13262. SSLClient cli(HOST, PORT);
  13263. cli.enable_server_certificate_verification(false);
  13264. cli.set_connection_timeout(30);
  13265. bool callback_called = false;
  13266. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13267. EXPECT_NE(session, nullptr);
  13268. callback_called = true;
  13269. return SSLVerifierResponse::CertificateRejected;
  13270. });
  13271. auto res = cli.Get("/test");
  13272. EXPECT_FALSE(res);
  13273. EXPECT_TRUE(callback_called);
  13274. }
  13275. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13277. ASSERT_TRUE(svr.is_valid());
  13278. svr.Get("/test", [](const Request &, Response &res) {
  13279. res.set_content("ok", "text/plain");
  13280. });
  13281. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13282. auto se = detail::scope_exit([&] {
  13283. svr.stop();
  13284. t.join();
  13285. });
  13286. svr.wait_until_ready();
  13287. // NoDecisionMade with verification disabled should succeed (no default check)
  13288. SSLClient cli(HOST, PORT);
  13289. cli.enable_server_certificate_verification(false);
  13290. cli.set_connection_timeout(30);
  13291. bool callback_called = false;
  13292. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13293. EXPECT_NE(session, nullptr);
  13294. callback_called = true;
  13295. return SSLVerifierResponse::NoDecisionMade;
  13296. });
  13297. auto res = cli.Get("/test");
  13298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13299. EXPECT_EQ(200, res->status);
  13300. EXPECT_TRUE(callback_called);
  13301. }
  13302. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13303. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13304. ASSERT_TRUE(svr.is_valid());
  13305. svr.Get("/test", [](const Request &, Response &res) {
  13306. res.set_content("ok", "text/plain");
  13307. });
  13308. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13309. auto se = detail::scope_exit([&] {
  13310. svr.stop();
  13311. t.join();
  13312. });
  13313. svr.wait_until_ready();
  13314. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13315. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13316. // so we only check that the request fails, not whether the callback was
  13317. // called.
  13318. SSLClient cli(HOST, PORT);
  13319. cli.enable_server_certificate_verification(true);
  13320. cli.set_connection_timeout(30);
  13321. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13322. EXPECT_NE(session, nullptr);
  13323. return SSLVerifierResponse::NoDecisionMade;
  13324. });
  13325. auto res = cli.Get("/test");
  13326. EXPECT_FALSE(res);
  13327. }
  13328. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13329. // Test SSL server using PemMemory constructor with client CA certificates
  13330. // Read PEM files
  13331. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13332. read_file(SERVER_CERT_FILE, server_cert_pem);
  13333. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13334. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13335. // Create SSLServer with PemMemory constructor including client CA
  13336. SSLServer::PemMemory server_pem = {
  13337. server_cert_pem.c_str(),
  13338. server_cert_pem.size(),
  13339. server_key_pem.c_str(),
  13340. server_key_pem.size(),
  13341. client_ca_pem.c_str(),
  13342. client_ca_pem.size(),
  13343. nullptr // no password for server key
  13344. };
  13345. SSLServer svr(server_pem);
  13346. ASSERT_TRUE(svr.is_valid());
  13347. // No SSL error should be recorded for valid setup
  13348. EXPECT_EQ(0, svr.ssl_last_error());
  13349. // Set up server endpoints
  13350. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13351. res.set_content("ok", "text/plain");
  13352. });
  13353. // Start server in a thread
  13354. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13355. svr.wait_until_ready();
  13356. // Connect with client certificate (using constructor with paths)
  13357. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13358. cli.enable_server_certificate_verification(false);
  13359. auto res = cli.Get("/test-pem-ca");
  13360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13361. EXPECT_EQ(200, res->status);
  13362. EXPECT_EQ("ok", res->body);
  13363. svr.stop();
  13364. server_thread.join();
  13365. }
  13366. #endif
  13367. #ifdef _WIN32
  13368. TEST(CleanupTest, WSACleanup) {
  13369. int ret = WSACleanup();
  13370. ASSERT_EQ(0, ret);
  13371. }
  13372. #endif
  13373. #ifndef CPPHTTPLIB_SSL_ENABLED
  13374. TEST(NoSSLSupport, SimpleInterface) {
  13375. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13376. }
  13377. #endif
  13378. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13379. TEST(InvalidScheme, SimpleInterface) {
  13380. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13381. }
  13382. #endif
  13383. TEST(NoScheme, SimpleInterface) {
  13384. Client cli("yahoo.com:80");
  13385. ASSERT_TRUE(cli.is_valid());
  13386. }
  13387. TEST(SendAPI, SimpleInterface_Online) {
  13388. Client cli("http://yahoo.com");
  13389. Request req;
  13390. req.method = "GET";
  13391. req.path = "/";
  13392. auto res = cli.send(req);
  13393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13394. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13395. }
  13396. TEST(SendAPI, WithParamsInRequest) {
  13397. Server svr;
  13398. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13399. EXPECT_TRUE(req.has_param("test"));
  13400. EXPECT_EQ("test_value", req.get_param_value("test"));
  13401. });
  13402. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13403. auto se = detail::scope_exit([&] {
  13404. svr.stop();
  13405. t.join();
  13406. ASSERT_FALSE(svr.is_running());
  13407. });
  13408. svr.wait_until_ready();
  13409. Client cli(HOST, PORT);
  13410. {
  13411. Request req;
  13412. req.method = "GET";
  13413. req.path = "/";
  13414. req.params.emplace("test", "test_value");
  13415. auto res = cli.send(req);
  13416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13417. }
  13418. {
  13419. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13421. }
  13422. }
  13423. TEST(ClientImplMethods, GetSocketTest) {
  13424. httplib::Server svr;
  13425. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13426. res.status = StatusCode::OK_200;
  13427. });
  13428. auto port = svr.bind_to_any_port("127.0.0.1");
  13429. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13430. auto se = detail::scope_exit([&] {
  13431. svr.stop();
  13432. thread.join();
  13433. ASSERT_FALSE(svr.is_running());
  13434. });
  13435. svr.wait_until_ready();
  13436. {
  13437. httplib::Client cli("127.0.0.1", port);
  13438. cli.set_keep_alive(true);
  13439. // Use the behavior of cpp-httplib of opening the connection
  13440. // only when the first request happens. If that changes,
  13441. // this test would be obsolete.
  13442. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13443. // This also implicitly tests the server. But other tests would fail much
  13444. // earlier than this one to be considered.
  13445. auto res = cli.Get("/");
  13446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13447. EXPECT_EQ(StatusCode::OK_200, res->status);
  13448. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13449. }
  13450. }
  13451. #ifdef CPPHTTPLIB_SSL_ENABLED
  13452. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13453. Client cli("http://yahoo.com");
  13454. auto res = cli.Get("/");
  13455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13456. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13457. cli.set_follow_location(true);
  13458. res = cli.Get("/");
  13459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13460. EXPECT_EQ(StatusCode::OK_200, res->status);
  13461. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13462. }
  13463. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13464. Client cli("https://yahoo.com");
  13465. auto res = cli.Get("/");
  13466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13467. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13468. cli.set_follow_location(true);
  13469. res = cli.Get("/");
  13470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13471. EXPECT_EQ(StatusCode::OK_200, res->status);
  13472. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13473. }
  13474. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13475. Client cli("https://yahoo.com");
  13476. auto res = cli.Get("/");
  13477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13478. ASSERT_FALSE(!res);
  13479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13480. ASSERT_FALSE(res == nullptr);
  13481. ASSERT_TRUE(res != nullptr);
  13482. EXPECT_EQ(Error::Success, res.error());
  13483. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13484. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13485. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13486. cli.set_follow_location(true);
  13487. res = cli.Get("/");
  13488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13489. EXPECT_EQ(Error::Success, res.error());
  13490. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13491. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13492. EXPECT_EQ(StatusCode::OK_200, res->status);
  13493. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13494. }
  13495. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13496. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13497. Client cli("https://cdnjs.cloudflare.com");
  13498. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13499. Headers{{"Accept-Encoding", "br"}});
  13500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13501. EXPECT_EQ(StatusCode::OK_200, res->status);
  13502. EXPECT_EQ(287630U, res->body.size());
  13503. EXPECT_EQ("application/javascript; charset=utf-8",
  13504. res->get_header_value("Content-Type"));
  13505. }
  13506. #endif
  13507. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13508. #undef REDIR_HOST // Silence compiler warning
  13509. #define REDIR_HOST "https://httpbingo.org"
  13510. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13511. Client cli(REDIR_HOST);
  13512. cli.set_follow_location(true);
  13513. auto res =
  13514. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13516. EXPECT_EQ(StatusCode::OK_200, res->status);
  13517. }
  13518. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13519. Client cli(REDIR_HOST);
  13520. cli.set_follow_location(true);
  13521. Params params;
  13522. params.emplace("url", "http://example.com");
  13523. params.emplace("status_code", "302");
  13524. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13526. EXPECT_EQ(StatusCode::OK_200, res->status);
  13527. }
  13528. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13529. Client cli(REDIR_HOST);
  13530. cli.set_follow_location(true);
  13531. Params params;
  13532. params.emplace("url", "http://example.com");
  13533. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13535. EXPECT_EQ(StatusCode::OK_200, res->status);
  13536. }
  13537. TEST(HttpToHttpsRedirectTest, CertFile) {
  13538. auto ssl_port = PORT + 1;
  13539. Server svr;
  13540. ASSERT_TRUE(svr.is_valid());
  13541. svr.Get("/index", [&](const Request &, Response &res) {
  13542. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13543. "/index");
  13544. svr.stop();
  13545. });
  13546. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13547. ASSERT_TRUE(ssl_svr.is_valid());
  13548. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13549. res.set_content("test", "text/plain");
  13550. ssl_svr.stop();
  13551. });
  13552. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13553. thread t2 =
  13554. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13555. auto se = detail::scope_exit([&] {
  13556. t2.join();
  13557. t.join();
  13558. ASSERT_FALSE(svr.is_running());
  13559. });
  13560. svr.wait_until_ready();
  13561. ssl_svr.wait_until_ready();
  13562. Client cli("127.0.0.1", PORT);
  13563. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13564. cli.enable_server_certificate_verification(true);
  13565. cli.set_follow_location(true);
  13566. cli.set_connection_timeout(30);
  13567. auto res = cli.Get("/index");
  13568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13569. ASSERT_EQ(StatusCode::OK_200, res->status);
  13570. }
  13571. TEST(SSLClientRedirectTest, CertFile) {
  13572. auto ssl_port = PORT + 1;
  13573. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13574. ASSERT_TRUE(ssl_svr1.is_valid());
  13575. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13576. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13577. "/index");
  13578. ssl_svr1.stop();
  13579. });
  13580. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13581. ASSERT_TRUE(ssl_svr2.is_valid());
  13582. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13583. res.set_content("test", "text/plain");
  13584. ssl_svr2.stop();
  13585. });
  13586. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13587. thread t2 =
  13588. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13589. auto se = detail::scope_exit([&] {
  13590. t2.join();
  13591. t.join();
  13592. ASSERT_FALSE(ssl_svr1.is_running());
  13593. });
  13594. ssl_svr1.wait_until_ready();
  13595. ssl_svr2.wait_until_ready();
  13596. SSLClient cli("127.0.0.1", PORT);
  13597. std::string cert;
  13598. read_file(SERVER_CERT2_FILE, cert);
  13599. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13600. cli.enable_server_certificate_verification(true);
  13601. cli.set_follow_location(true);
  13602. cli.set_connection_timeout(30);
  13603. auto res = cli.Get("/index");
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. ASSERT_EQ(StatusCode::OK_200, res->status);
  13606. }
  13607. #endif
  13608. #ifdef CPPHTTPLIB_SSL_ENABLED
  13609. // Test that set_ca_cert_store() skips system certs (consistent with
  13610. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13611. // should be trusted - system certs should NOT be loaded.
  13612. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13613. // Load a specific cert that is NOT a system CA cert
  13614. std::string cert;
  13615. read_file(SERVER_CERT2_FILE, cert);
  13616. SSLClient cli("google.com");
  13617. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13618. cli.enable_server_certificate_verification(true);
  13619. // This should FAIL because:
  13620. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13621. // 2. System certs should NOT be loaded when custom store is set
  13622. // If system certs WERE loaded, this would succeed
  13623. auto res = cli.Get("/");
  13624. ASSERT_FALSE(res);
  13625. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13626. }
  13627. // Same as above, but through the native store handle path. Regression test:
  13628. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13629. // merged system certs into the user-provided store.
  13630. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13631. std::string cert;
  13632. read_file(SERVER_CERT2_FILE, cert);
  13633. SSLClient cli("google.com");
  13634. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13635. cli.enable_server_certificate_verification(true);
  13636. auto res = cli.Get("/");
  13637. ASSERT_FALSE(res);
  13638. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13639. }
  13640. // A custom store set via the native handle must still verify a server whose
  13641. // cert it does contain.
  13642. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13643. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13644. ASSERT_TRUE(svr.is_valid());
  13645. svr.Get("/test", [&](const Request &, Response &res) {
  13646. res.set_content("test", "text/plain");
  13647. });
  13648. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13649. auto se = detail::scope_exit([&] {
  13650. svr.stop();
  13651. t.join();
  13652. ASSERT_FALSE(svr.is_running());
  13653. });
  13654. svr.wait_until_ready();
  13655. SSLClient cli("127.0.0.1", PORT);
  13656. std::string cert;
  13657. read_file(SERVER_CERT2_FILE, cert);
  13658. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13659. cli.enable_server_certificate_verification(true);
  13660. cli.set_connection_timeout(30);
  13661. auto res = cli.Get("/test");
  13662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13663. ASSERT_EQ(StatusCode::OK_200, res->status);
  13664. }
  13665. // CA certs loaded through the universal Client must be transferred to the
  13666. // client created internally for following an HTTPS redirect. Regression test:
  13667. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13668. // the CA data for redirect transfer.
  13669. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13670. auto ssl_port = PORT + 1;
  13671. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13672. ASSERT_TRUE(ssl_svr1.is_valid());
  13673. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13674. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13675. "/index");
  13676. });
  13677. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13678. ASSERT_TRUE(ssl_svr2.is_valid());
  13679. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13680. res.set_content("test", "text/plain");
  13681. });
  13682. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13683. thread t2 =
  13684. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13685. auto se = detail::scope_exit([&] {
  13686. ssl_svr2.stop();
  13687. ssl_svr1.stop();
  13688. t2.join();
  13689. t.join();
  13690. ASSERT_FALSE(ssl_svr1.is_running());
  13691. });
  13692. ssl_svr1.wait_until_ready();
  13693. ssl_svr2.wait_until_ready();
  13694. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13695. std::string cert;
  13696. read_file(SERVER_CERT2_FILE, cert);
  13697. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13698. cli.enable_server_certificate_verification(true);
  13699. cli.set_follow_location(true);
  13700. cli.set_connection_timeout(30);
  13701. auto res = cli.Get("/index");
  13702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13703. ASSERT_EQ(StatusCode::OK_200, res->status);
  13704. }
  13705. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13706. // so a host signed by a system CA verifies even though a custom CA is set
  13707. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13708. std::string cert;
  13709. read_file(SERVER_CERT2_FILE, cert);
  13710. SSLClient cli("google.com");
  13711. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13712. cli.enable_system_ca(true);
  13713. cli.enable_server_certificate_verification(true);
  13714. auto res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13717. }
  13718. // The custom CA remains effective when combined with the system CA
  13719. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13720. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13721. ASSERT_TRUE(svr.is_valid());
  13722. svr.Get("/test", [&](const Request &, Response &res) {
  13723. res.set_content("test", "text/plain");
  13724. });
  13725. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13726. auto se = detail::scope_exit([&] {
  13727. svr.stop();
  13728. t.join();
  13729. ASSERT_FALSE(svr.is_running());
  13730. });
  13731. svr.wait_until_ready();
  13732. SSLClient cli("127.0.0.1", PORT);
  13733. std::string cert;
  13734. read_file(SERVER_CERT2_FILE, cert);
  13735. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13736. cli.enable_system_ca(true);
  13737. cli.enable_server_certificate_verification(true);
  13738. cli.set_connection_timeout(30);
  13739. auto res = cli.Get("/test");
  13740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13741. ASSERT_EQ(StatusCode::OK_200, res->status);
  13742. }
  13743. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13744. // skip chain verification entirely (only the certificate identity was
  13745. // checked), so a server presenting an untrusted certificate with a matching
  13746. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13747. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13748. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13749. ASSERT_TRUE(svr.is_valid());
  13750. svr.Get("/test", [&](const Request &, Response &res) {
  13751. res.set_content("test", "text/plain");
  13752. });
  13753. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13754. auto se = detail::scope_exit([&] {
  13755. svr.stop();
  13756. t.join();
  13757. ASSERT_FALSE(svr.is_running());
  13758. });
  13759. svr.wait_until_ready();
  13760. SSLClient cli("127.0.0.1", PORT);
  13761. std::string cert;
  13762. // A trusted CA that did not sign the server certificate. The server cert
  13763. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13764. // this connection.
  13765. read_file(CLIENT_CA_CERT_FILE, cert);
  13766. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13767. cli.enable_server_certificate_verification(true);
  13768. cli.set_connection_timeout(30);
  13769. auto res = cli.Get("/test");
  13770. ASSERT_FALSE(res);
  13771. }
  13772. // enable_system_ca(false) prevents system CA loading entirely
  13773. TEST(SSLClientTest, DisableSystemCa_Online) {
  13774. SSLClient cli("google.com");
  13775. cli.enable_system_ca(false);
  13776. cli.enable_server_certificate_verification(true);
  13777. auto res = cli.Get("/");
  13778. ASSERT_FALSE(res);
  13779. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13780. // itself when the CA chain is empty
  13781. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13782. res.error() == Error::SSLConnection);
  13783. }
  13784. // The universal Client forwards enable_system_ca()
  13785. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13786. std::string cert;
  13787. read_file(SERVER_CERT2_FILE, cert);
  13788. Client cli("https://google.com");
  13789. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13790. cli.enable_system_ca(true);
  13791. cli.enable_server_certificate_verification(true);
  13792. auto res = cli.Get("/");
  13793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13794. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13795. }
  13796. // The system CA policy must carry over to the client created internally for
  13797. // following a cross-host HTTPS redirect
  13798. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13799. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13800. ASSERT_TRUE(svr.is_valid());
  13801. svr.Get("/index", [&](const Request &, Response &res) {
  13802. res.set_redirect("https://www.google.com/");
  13803. });
  13804. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13805. auto se = detail::scope_exit([&] {
  13806. svr.stop();
  13807. t.join();
  13808. ASSERT_FALSE(svr.is_running());
  13809. });
  13810. svr.wait_until_ready();
  13811. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13812. std::string cert;
  13813. read_file(SERVER_CERT2_FILE, cert);
  13814. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13815. cli.enable_system_ca(true);
  13816. cli.enable_server_certificate_verification(true);
  13817. cli.set_follow_location(true);
  13818. cli.set_connection_timeout(30);
  13819. // Receiving any response proves the redirect client completed the TLS
  13820. // handshake with a system-CA-signed host
  13821. auto res = cli.Get("/index");
  13822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13823. }
  13824. TEST(MultipartFormDataTest, LargeData) {
  13825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13826. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13827. const ContentReader &content_reader) {
  13828. if (req.is_multipart_form_data()) {
  13829. std::vector<FormData> items;
  13830. content_reader(
  13831. [&](const FormData &file) {
  13832. items.push_back(file);
  13833. return true;
  13834. },
  13835. [&](const char *data, size_t data_length) {
  13836. items.back().content.append(data, data_length);
  13837. return true;
  13838. });
  13839. EXPECT_TRUE(std::string(items[0].name) == "document");
  13840. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13841. EXPECT_TRUE(items[0].filename == "2MB_data");
  13842. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13843. EXPECT_TRUE(items[1].name == "hello");
  13844. EXPECT_TRUE(items[1].content == "world");
  13845. EXPECT_TRUE(items[1].filename == "");
  13846. EXPECT_TRUE(items[1].content_type == "");
  13847. } else {
  13848. std::string body;
  13849. content_reader([&](const char *data, size_t data_length) {
  13850. body.append(data, data_length);
  13851. return true;
  13852. });
  13853. }
  13854. });
  13855. auto port = svr.bind_to_any_port(HOST);
  13856. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13857. auto se = detail::scope_exit([&] {
  13858. svr.stop();
  13859. t.join();
  13860. ASSERT_FALSE(svr.is_running());
  13861. });
  13862. svr.wait_until_ready();
  13863. {
  13864. std::string data(1024 * 1024 * 2, '.');
  13865. std::stringstream buffer;
  13866. buffer << data;
  13867. SSLClient cli(HOST, port);
  13868. cli.enable_server_certificate_verification(false);
  13869. UploadFormDataItems items{
  13870. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13871. {"hello", "world", "", ""},
  13872. };
  13873. auto res = cli.Post("/post", items);
  13874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13875. ASSERT_EQ(StatusCode::OK_200, res->status);
  13876. }
  13877. }
  13878. TEST(MultipartFormDataTest, DataProviderItems) {
  13879. std::random_device seed_gen;
  13880. std::mt19937 random(seed_gen());
  13881. std::string rand1;
  13882. rand1.resize(1000);
  13883. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13884. std::string rand2;
  13885. rand2.resize(3000);
  13886. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13888. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13889. const ContentReader &content_reader) {
  13890. ASSERT_FALSE(req.is_multipart_form_data());
  13891. std::string body;
  13892. content_reader([&](const char *data, size_t data_length) {
  13893. body.append(data, data_length);
  13894. return true;
  13895. });
  13896. EXPECT_EQ(body, "");
  13897. });
  13898. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13899. const ContentReader &content_reader) {
  13900. ASSERT_TRUE(req.is_multipart_form_data());
  13901. std::vector<FormData> items;
  13902. content_reader(
  13903. [&](const FormData &file) {
  13904. items.push_back(file);
  13905. return true;
  13906. },
  13907. [&](const char *data, size_t data_length) {
  13908. items.back().content.append(data, data_length);
  13909. return true;
  13910. });
  13911. ASSERT_TRUE(items.size() == 2);
  13912. EXPECT_EQ(std::string(items[0].name), "name1");
  13913. EXPECT_EQ(items[0].content, "Testing123");
  13914. EXPECT_EQ(items[0].filename, "filename1");
  13915. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13916. EXPECT_EQ(items[1].name, "name2");
  13917. EXPECT_EQ(items[1].content, "Testing456");
  13918. EXPECT_EQ(items[1].filename, "");
  13919. EXPECT_EQ(items[1].content_type, "");
  13920. });
  13921. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13922. const ContentReader &content_reader) {
  13923. ASSERT_TRUE(req.is_multipart_form_data());
  13924. std::vector<FormData> items;
  13925. content_reader(
  13926. [&](const FormData &file) {
  13927. items.push_back(file);
  13928. return true;
  13929. },
  13930. [&](const char *data, size_t data_length) {
  13931. items.back().content.append(data, data_length);
  13932. return true;
  13933. });
  13934. ASSERT_TRUE(items.size() == 2);
  13935. EXPECT_EQ(items[0].name, "name3");
  13936. EXPECT_EQ(items[0].content, rand1);
  13937. EXPECT_EQ(items[0].filename, "filename3");
  13938. EXPECT_EQ(items[0].content_type, "");
  13939. EXPECT_EQ(items[1].name, "name4");
  13940. EXPECT_EQ(items[1].content, rand2);
  13941. EXPECT_EQ(items[1].filename, "filename4");
  13942. EXPECT_EQ(items[1].content_type, "");
  13943. });
  13944. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13945. const ContentReader &content_reader) {
  13946. ASSERT_TRUE(req.is_multipart_form_data());
  13947. std::vector<FormData> items;
  13948. content_reader(
  13949. [&](const FormData &file) {
  13950. items.push_back(file);
  13951. return true;
  13952. },
  13953. [&](const char *data, size_t data_length) {
  13954. items.back().content.append(data, data_length);
  13955. return true;
  13956. });
  13957. ASSERT_TRUE(items.size() == 4);
  13958. EXPECT_EQ(std::string(items[0].name), "name1");
  13959. EXPECT_EQ(items[0].content, "Testing123");
  13960. EXPECT_EQ(items[0].filename, "filename1");
  13961. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13962. EXPECT_EQ(items[1].name, "name2");
  13963. EXPECT_EQ(items[1].content, "Testing456");
  13964. EXPECT_EQ(items[1].filename, "");
  13965. EXPECT_EQ(items[1].content_type, "");
  13966. EXPECT_EQ(items[2].name, "name3");
  13967. EXPECT_EQ(items[2].content, rand1);
  13968. EXPECT_EQ(items[2].filename, "filename3");
  13969. EXPECT_EQ(items[2].content_type, "");
  13970. EXPECT_EQ(items[3].name, "name4");
  13971. EXPECT_EQ(items[3].content, rand2);
  13972. EXPECT_EQ(items[3].filename, "filename4");
  13973. EXPECT_EQ(items[3].content_type, "");
  13974. });
  13975. auto port = svr.bind_to_any_port("localhost");
  13976. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13977. auto se = detail::scope_exit([&] {
  13978. svr.stop();
  13979. t.join();
  13980. ASSERT_FALSE(svr.is_running());
  13981. });
  13982. svr.wait_until_ready();
  13983. {
  13984. SSLClient cli("localhost", port);
  13985. cli.enable_server_certificate_verification(false);
  13986. UploadFormDataItems items{
  13987. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13988. {"name2", "Testing456", "", ""}, // not a file
  13989. };
  13990. {
  13991. auto res = cli.Post("/post-none", {}, {}, {});
  13992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13993. ASSERT_EQ(StatusCode::OK_200, res->status);
  13994. }
  13995. FormDataProviderItems providers;
  13996. {
  13997. auto res =
  13998. cli.Post("/post-items", {}, items, providers); // empty providers
  13999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14000. ASSERT_EQ(StatusCode::OK_200, res->status);
  14001. }
  14002. providers.push_back({"name3",
  14003. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14004. // test the offset is given correctly at each step
  14005. if (!offset)
  14006. sink.os.write(rand1.data(), 30);
  14007. else if (offset == 30)
  14008. sink.os.write(rand1.data() + 30, 300);
  14009. else if (offset == 330)
  14010. sink.os.write(rand1.data() + 330, 670);
  14011. else if (offset == rand1.size())
  14012. sink.done();
  14013. return true;
  14014. },
  14015. "filename3",
  14016. {}});
  14017. providers.push_back({"name4",
  14018. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14019. // test the offset is given correctly at each step
  14020. if (!offset)
  14021. sink.os.write(rand2.data(), 2000);
  14022. else if (offset == 2000)
  14023. sink.os.write(rand2.data() + 2000, 1);
  14024. else if (offset == 2001)
  14025. sink.os.write(rand2.data() + 2001, 999);
  14026. else if (offset == rand2.size())
  14027. sink.done();
  14028. return true;
  14029. },
  14030. "filename4",
  14031. {}});
  14032. {
  14033. auto res = cli.Post("/post-providers", {}, {}, providers);
  14034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14035. ASSERT_EQ(StatusCode::OK_200, res->status);
  14036. }
  14037. {
  14038. auto res = cli.Post("/post-both", {}, items, providers);
  14039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14040. ASSERT_EQ(StatusCode::OK_200, res->status);
  14041. }
  14042. }
  14043. }
  14044. TEST(MultipartFormDataTest, BadHeader) {
  14045. Server svr;
  14046. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14047. res.set_content("ok", "text/plain");
  14048. });
  14049. thread t = thread([&] { svr.listen(HOST, PORT); });
  14050. auto se = detail::scope_exit([&] {
  14051. svr.stop();
  14052. t.join();
  14053. ASSERT_FALSE(svr.is_running());
  14054. });
  14055. svr.wait_until_ready();
  14056. const std::string body =
  14057. "This is the preamble. It is to be ignored, though it\r\n"
  14058. "is a handy place for composition agents to include an\r\n"
  14059. "explanatory note to non-MIME conformant readers.\r\n"
  14060. "\r\n"
  14061. "\r\n"
  14062. "--simple boundary\r\n"
  14063. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14064. ": BAD...\r\n"
  14065. "\r\n"
  14066. "value1\r\n"
  14067. "--simple boundary\r\n"
  14068. "Content-Disposition: form-data; name=\"field2\"; "
  14069. "filename=\"example.txt\"\r\n"
  14070. "\r\n"
  14071. "value2\r\n"
  14072. "--simple boundary--\r\n"
  14073. "This is the epilogue. It is also to be ignored.\r\n";
  14074. std::string content_type =
  14075. R"(multipart/form-data; boundary="simple boundary")";
  14076. Client cli(HOST, PORT);
  14077. auto res = cli.Post("/post", body, content_type.c_str());
  14078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14079. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14080. }
  14081. TEST(MultipartFormDataTest, WithPreamble) {
  14082. Server svr;
  14083. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14084. res.set_content("ok", "text/plain");
  14085. });
  14086. thread t = thread([&] { svr.listen(HOST, PORT); });
  14087. auto se = detail::scope_exit([&] {
  14088. svr.stop();
  14089. t.join();
  14090. ASSERT_FALSE(svr.is_running());
  14091. });
  14092. svr.wait_until_ready();
  14093. const std::string body =
  14094. "This is the preamble. It is to be ignored, though it\r\n"
  14095. "is a handy place for composition agents to include an\r\n"
  14096. "explanatory note to non-MIME conformant readers.\r\n"
  14097. "\r\n"
  14098. "\r\n"
  14099. "--simple boundary\r\n"
  14100. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14101. "\r\n"
  14102. "value1\r\n"
  14103. "--simple boundary\r\n"
  14104. "Content-Disposition: form-data; name=\"field2\"; "
  14105. "filename=\"example.txt\"\r\n"
  14106. "\r\n"
  14107. "value2\r\n"
  14108. "--simple boundary--\r\n"
  14109. "This is the epilogue. It is also to be ignored.\r\n";
  14110. std::string content_type =
  14111. R"(multipart/form-data; boundary="simple boundary")";
  14112. Client cli(HOST, PORT);
  14113. auto res = cli.Post("/post", body, content_type.c_str());
  14114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14115. EXPECT_EQ(StatusCode::OK_200, res->status);
  14116. }
  14117. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14118. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14119. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14120. const ContentReader &content_reader) {
  14121. if (req.is_multipart_form_data()) {
  14122. std::vector<FormData> items;
  14123. content_reader(
  14124. [&](const FormData &file) {
  14125. items.push_back(file);
  14126. return true;
  14127. },
  14128. [&](const char *data, size_t data_length) {
  14129. items.back().content.append(data, data_length);
  14130. return true;
  14131. });
  14132. EXPECT_TRUE(std::string(items[0].name) == "document");
  14133. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14134. EXPECT_TRUE(items[0].filename == "2MB_data");
  14135. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14136. EXPECT_TRUE(items[1].name == "hello");
  14137. EXPECT_TRUE(items[1].content == "world");
  14138. EXPECT_TRUE(items[1].filename == "");
  14139. EXPECT_TRUE(items[1].content_type == "");
  14140. } else {
  14141. std::string body;
  14142. content_reader([&](const char *data, size_t data_length) {
  14143. body.append(data, data_length);
  14144. return true;
  14145. });
  14146. }
  14147. });
  14148. auto port = svr.bind_to_any_port("localhost");
  14149. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14150. auto se = detail::scope_exit([&] {
  14151. svr.stop();
  14152. t.join();
  14153. ASSERT_FALSE(svr.is_running());
  14154. });
  14155. svr.wait_until_ready();
  14156. {
  14157. std::string data(1024 * 1024 * 2, '.');
  14158. std::stringstream buffer;
  14159. buffer << data;
  14160. SSLClient cli("localhost", port);
  14161. cli.enable_server_certificate_verification(false);
  14162. UploadFormDataItems items{
  14163. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14164. {"hello", "world", "", ""},
  14165. };
  14166. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14168. ASSERT_EQ(StatusCode::OK_200, res->status);
  14169. }
  14170. }
  14171. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14172. std::string data(1024 * 1024 * 2, '&');
  14173. std::stringstream buffer;
  14174. buffer << data;
  14175. Client cli("https://localhost:8080");
  14176. UploadFormDataItems items{
  14177. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14178. {"hello", "world", "", ""},
  14179. };
  14180. for (const char &c : " \t\r\n") {
  14181. auto res =
  14182. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14183. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14184. ASSERT_FALSE(res);
  14185. }
  14186. }
  14187. TEST(MultipartFormDataTest, PutFormData) {
  14188. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14189. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14190. const ContentReader &content_reader) {
  14191. if (req.is_multipart_form_data()) {
  14192. std::vector<FormData> items;
  14193. content_reader(
  14194. [&](const FormData &file) {
  14195. items.push_back(file);
  14196. return true;
  14197. },
  14198. [&](const char *data, size_t data_length) {
  14199. items.back().content.append(data, data_length);
  14200. return true;
  14201. });
  14202. EXPECT_TRUE(std::string(items[0].name) == "document");
  14203. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14204. EXPECT_TRUE(items[0].filename == "2MB_data");
  14205. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14206. EXPECT_TRUE(items[1].name == "hello");
  14207. EXPECT_TRUE(items[1].content == "world");
  14208. EXPECT_TRUE(items[1].filename == "");
  14209. EXPECT_TRUE(items[1].content_type == "");
  14210. } else {
  14211. std::string body;
  14212. content_reader([&](const char *data, size_t data_length) {
  14213. body.append(data, data_length);
  14214. return true;
  14215. });
  14216. }
  14217. });
  14218. auto port = svr.bind_to_any_port("localhost");
  14219. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14220. auto se = detail::scope_exit([&] {
  14221. svr.stop();
  14222. t.join();
  14223. ASSERT_FALSE(svr.is_running());
  14224. });
  14225. svr.wait_until_ready();
  14226. {
  14227. std::string data(1024 * 1024 * 2, '&');
  14228. std::stringstream buffer;
  14229. buffer << data;
  14230. SSLClient cli("localhost", port);
  14231. cli.enable_server_certificate_verification(false);
  14232. UploadFormDataItems items{
  14233. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14234. {"hello", "world", "", ""},
  14235. };
  14236. auto res = cli.Put("/put", items);
  14237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14238. ASSERT_EQ(StatusCode::OK_200, res->status);
  14239. }
  14240. }
  14241. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14242. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14243. svr.Put("/put_customboundary",
  14244. [&](const Request &req, const Response & /*res*/,
  14245. const ContentReader &content_reader) {
  14246. if (req.is_multipart_form_data()) {
  14247. std::vector<FormData> items;
  14248. content_reader(
  14249. [&](const FormData &file) {
  14250. items.push_back(file);
  14251. return true;
  14252. },
  14253. [&](const char *data, size_t data_length) {
  14254. items.back().content.append(data, data_length);
  14255. return true;
  14256. });
  14257. EXPECT_TRUE(std::string(items[0].name) == "document");
  14258. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14259. EXPECT_TRUE(items[0].filename == "2MB_data");
  14260. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14261. EXPECT_TRUE(items[1].name == "hello");
  14262. EXPECT_TRUE(items[1].content == "world");
  14263. EXPECT_TRUE(items[1].filename == "");
  14264. EXPECT_TRUE(items[1].content_type == "");
  14265. } else {
  14266. std::string body;
  14267. content_reader([&](const char *data, size_t data_length) {
  14268. body.append(data, data_length);
  14269. return true;
  14270. });
  14271. }
  14272. });
  14273. auto port = svr.bind_to_any_port("localhost");
  14274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. ASSERT_FALSE(svr.is_running());
  14279. });
  14280. svr.wait_until_ready();
  14281. {
  14282. std::string data(1024 * 1024 * 2, '&');
  14283. std::stringstream buffer;
  14284. buffer << data;
  14285. SSLClient cli("localhost", port);
  14286. cli.enable_server_certificate_verification(false);
  14287. UploadFormDataItems items{
  14288. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14289. {"hello", "world", "", ""},
  14290. };
  14291. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14293. ASSERT_EQ(StatusCode::OK_200, res->status);
  14294. }
  14295. }
  14296. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14297. std::string data(1024 * 1024 * 2, '&');
  14298. std::stringstream buffer;
  14299. buffer << data;
  14300. Client cli("https://localhost:8080");
  14301. cli.enable_server_certificate_verification(false);
  14302. UploadFormDataItems items{
  14303. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14304. {"hello", "world", "", ""},
  14305. };
  14306. for (const char &c : " \t\r\n") {
  14307. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14308. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14309. ASSERT_FALSE(res);
  14310. }
  14311. }
  14312. TEST(MultipartFormDataTest, AlternateFilename) {
  14313. auto handled = false;
  14314. Server svr;
  14315. svr.Post("/test", [&](const Request &req, Response &res) {
  14316. ASSERT_EQ(2u, req.form.files.size());
  14317. ASSERT_EQ(1u, req.form.fields.size());
  14318. // Test files
  14319. const auto &file1 = req.form.get_file("file1");
  14320. ASSERT_EQ("file1", file1.name);
  14321. ASSERT_EQ("A.txt", file1.filename);
  14322. ASSERT_EQ("text/plain", file1.content_type);
  14323. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14324. const auto &file2 = req.form.get_file("file2");
  14325. ASSERT_EQ("file2", file2.name);
  14326. ASSERT_EQ("a.html", file2.filename);
  14327. ASSERT_EQ("text/html", file2.content_type);
  14328. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14329. file2.content);
  14330. // Test text field
  14331. const auto &text = req.form.get_field("text");
  14332. ASSERT_EQ("text default", text);
  14333. res.set_content("ok", "text/plain");
  14334. handled = true;
  14335. });
  14336. thread t = thread([&] { svr.listen(HOST, PORT); });
  14337. auto se = detail::scope_exit([&] {
  14338. svr.stop();
  14339. t.join();
  14340. ASSERT_FALSE(svr.is_running());
  14341. ASSERT_TRUE(handled);
  14342. });
  14343. svr.wait_until_ready();
  14344. auto req = "POST /test HTTP/1.1\r\n"
  14345. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14346. "Content-Length: 399\r\n"
  14347. "\r\n"
  14348. "----------\r\n"
  14349. "Content-Disposition: form-data; name=\"text\"\r\n"
  14350. "\r\n"
  14351. "text default\r\n"
  14352. "----------\r\n"
  14353. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14354. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14355. "Content-Type: text/plain\r\n"
  14356. "\r\n"
  14357. "Content of a.txt.\r\n"
  14358. "\r\n"
  14359. "----------\r\n"
  14360. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14361. "\"a.html\"\r\n"
  14362. "Content-Type: text/html\r\n"
  14363. "\r\n"
  14364. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14365. "\r\n"
  14366. "------------\r\n";
  14367. ASSERT_TRUE(send_request(1, req));
  14368. }
  14369. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14370. auto handled = false;
  14371. Server svr;
  14372. svr.Post("/test", [&](const Request &req, Response &res) {
  14373. // Case-insensitive "utf-8''" prefix with a long value
  14374. const auto &file = req.form.get_file("file1");
  14375. ASSERT_EQ("file1", file.name);
  14376. // 8000 chars exercises both the Content-Disposition parser and the
  14377. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14378. // Prior to the fix, std::regex_match on this header would cause O(N)
  14379. // stack recursion in libstdc++, leading to SIGSEGV.
  14380. std::string expected_filename(8000, 'A');
  14381. ASSERT_EQ(expected_filename, file.filename);
  14382. res.set_content("ok", "text/plain");
  14383. handled = true;
  14384. });
  14385. thread t = thread([&] { svr.listen(HOST, PORT); });
  14386. auto se = detail::scope_exit([&] {
  14387. svr.stop();
  14388. t.join();
  14389. ASSERT_FALSE(svr.is_running());
  14390. ASSERT_TRUE(handled);
  14391. });
  14392. svr.wait_until_ready();
  14393. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14394. // Regression test for GHSA-qq6v-r583-3h69
  14395. std::string long_filename(8000, 'A');
  14396. std::string body = "----------\r\n"
  14397. "Content-Disposition: form-data; name=\"file1\"; "
  14398. "filename*=\"Utf-8''" +
  14399. long_filename +
  14400. "\"\r\n"
  14401. "\r\n"
  14402. "hello\r\n"
  14403. "------------\r\n";
  14404. auto req = "POST /test HTTP/1.1\r\n"
  14405. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14406. "Content-Length: " +
  14407. std::to_string(body.size()) + "\r\n\r\n" + body;
  14408. ASSERT_TRUE(send_request(1, req));
  14409. }
  14410. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14411. auto handled = false;
  14412. Server svr;
  14413. svr.Post("/test", [&](const Request &req, Response &) {
  14414. ASSERT_EQ(2u, req.form.fields.size());
  14415. const auto &text1 = req.form.get_field("text1");
  14416. ASSERT_EQ("text1", text1);
  14417. const auto &text2 = req.form.get_field("text2");
  14418. ASSERT_EQ("text2", text2);
  14419. handled = true;
  14420. });
  14421. thread t = thread([&] { svr.listen(HOST, PORT); });
  14422. auto se = detail::scope_exit([&] {
  14423. svr.stop();
  14424. t.join();
  14425. ASSERT_FALSE(svr.is_running());
  14426. ASSERT_TRUE(handled);
  14427. });
  14428. svr.wait_until_ready();
  14429. auto req = "POST /test HTTP/1.1\r\n"
  14430. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14431. "Content-Length: 146\r\n"
  14432. "\r\n----------\r\n"
  14433. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14434. "\r\n"
  14435. "text1"
  14436. "\r\n----------\r\n"
  14437. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14438. "\r\n"
  14439. "text2"
  14440. "\r\n------------";
  14441. std::string response;
  14442. ASSERT_TRUE(send_request(1, req, &response));
  14443. ASSERT_EQ("200", response.substr(9, 3));
  14444. }
  14445. TEST(MultipartFormDataTest, ContentLength) {
  14446. auto handled = false;
  14447. Server svr;
  14448. svr.Post("/test", [&](const Request &req, Response &) {
  14449. ASSERT_EQ(2u, req.form.fields.size());
  14450. const auto &text1 = req.form.get_field("text1");
  14451. ASSERT_EQ("text1", text1);
  14452. const auto &text2 = req.form.get_field("text2");
  14453. ASSERT_EQ("text2", text2);
  14454. handled = true;
  14455. });
  14456. thread t = thread([&] { svr.listen(HOST, PORT); });
  14457. auto se = detail::scope_exit([&] {
  14458. svr.stop();
  14459. t.join();
  14460. ASSERT_FALSE(svr.is_running());
  14461. ASSERT_TRUE(handled);
  14462. });
  14463. svr.wait_until_ready();
  14464. auto req = "POST /test HTTP/1.1\r\n"
  14465. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14466. "Content-Length: 167\r\n"
  14467. "\r\n----------\r\n"
  14468. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14469. "Content-Length: 5\r\n"
  14470. "\r\n"
  14471. "text1"
  14472. "\r\n----------\r\n"
  14473. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14474. "\r\n"
  14475. "text2"
  14476. "\r\n------------\r\n";
  14477. std::string response;
  14478. ASSERT_TRUE(send_request(1, req, &response));
  14479. ASSERT_EQ("200", response.substr(9, 3));
  14480. }
  14481. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14482. auto handled = false;
  14483. Server svr;
  14484. svr.Post("/test", [&](const Request &req, Response &) {
  14485. ASSERT_EQ(2u, req.form.fields.size());
  14486. const auto &text1 = req.form.get_field("text1");
  14487. ASSERT_EQ("text1", text1);
  14488. // TODO: Add header access for text fields if needed
  14489. const auto &text2 = req.form.get_field("text2");
  14490. ASSERT_EQ("text2", text2);
  14491. // TODO: Header access for text fields needs to be implemented
  14492. // auto &headers = it->second.headers;
  14493. // ASSERT_EQ(3U, headers.size());
  14494. // auto custom_header = headers.find("x-whatever");
  14495. // ASSERT_TRUE(custom_header != headers.end());
  14496. // ASSERT_NE("customvalue", custom_header->second);
  14497. // ASSERT_EQ("CustomValue", custom_header->second);
  14498. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14499. handled = true;
  14500. });
  14501. thread t = thread([&] { svr.listen(HOST, PORT); });
  14502. auto se = detail::scope_exit([&] {
  14503. svr.stop();
  14504. t.join();
  14505. ASSERT_FALSE(svr.is_running());
  14506. ASSERT_TRUE(handled);
  14507. });
  14508. svr.wait_until_ready();
  14509. auto req = "POST /test HTTP/1.1\r\n"
  14510. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14511. "Content-Length: 232\r\n"
  14512. "\r\n----------\r\n"
  14513. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14514. "Content-Length: 5\r\n"
  14515. "X-Test: 1\r\n"
  14516. "\r\n"
  14517. "text1"
  14518. "\r\n----------\r\n"
  14519. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14520. "Content-Type: text/plain\r\n"
  14521. "X-Whatever: CustomValue\r\n"
  14522. "\r\n"
  14523. "text2"
  14524. "\r\n------------\r\n"
  14525. "That should be disregarded. Not even read";
  14526. std::string response;
  14527. ASSERT_TRUE(send_request(1, req, &response));
  14528. ASSERT_EQ("200", response.substr(9, 3));
  14529. }
  14530. TEST(MultipartFormDataTest, LargeHeader) {
  14531. auto handled = false;
  14532. Server svr;
  14533. svr.Post("/test", [&](const Request &req, Response &) {
  14534. ASSERT_EQ(1u, req.form.fields.size());
  14535. const auto &text = req.form.get_field("name1");
  14536. ASSERT_EQ("text1", text);
  14537. handled = true;
  14538. });
  14539. thread t = thread([&] { svr.listen(HOST, PORT); });
  14540. auto se = detail::scope_exit([&] {
  14541. svr.stop();
  14542. t.join();
  14543. ASSERT_FALSE(svr.is_running());
  14544. ASSERT_TRUE(handled);
  14545. });
  14546. svr.wait_until_ready();
  14547. auto boundary = std::string("cpp-httplib-multipart-data");
  14548. std::string content = "--" + boundary +
  14549. "\r\n"
  14550. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14551. "\r\n"
  14552. "text1\r\n"
  14553. "--" +
  14554. boundary + "--\r\n";
  14555. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14556. "Content-Type: multipart/form-data;boundary=" +
  14557. boundary +
  14558. "\r\n"
  14559. "Content-Length: " +
  14560. std::to_string(content.size()) +
  14561. "\r\n"
  14562. "Dummy-Header: ";
  14563. std::string header_suffix = "\r\n"
  14564. "\r\n";
  14565. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14566. size_t header_dummy_size =
  14567. read_buff_size -
  14568. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14569. auto header_dummy = std::string(header_dummy_size, '@');
  14570. auto req = header_prefix + header_dummy + header_suffix + content;
  14571. std::string response;
  14572. ASSERT_TRUE(send_request(1, req, &response));
  14573. ASSERT_EQ("200", response.substr(9, 3));
  14574. }
  14575. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14576. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14577. // (not chunked Transfer-Encoding) after the streaming refactor.
  14578. auto handled = false;
  14579. Server svr;
  14580. svr.Post("/upload", [&](const Request &req, Response &res) {
  14581. auto cl_it = req.headers.find("Content-Length");
  14582. EXPECT_TRUE(cl_it != req.headers.end());
  14583. auto te_it = req.headers.find("Transfer-Encoding");
  14584. EXPECT_TRUE(te_it == req.headers.end());
  14585. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14586. res.set_content("ok", "text/plain");
  14587. handled = true;
  14588. });
  14589. auto port = svr.bind_to_any_port(HOST);
  14590. auto t = thread([&] { svr.listen_after_bind(); });
  14591. auto se = detail::scope_exit([&] {
  14592. svr.stop();
  14593. t.join();
  14594. ASSERT_FALSE(svr.is_running());
  14595. ASSERT_TRUE(handled);
  14596. });
  14597. svr.wait_until_ready();
  14598. UploadFormDataItems items = {
  14599. {"field1", "hello", "", "text/plain"},
  14600. {"file1", "world", "test.txt", "application/octet-stream"},
  14601. };
  14602. Client cli(HOST, port);
  14603. auto res = cli.Post("/upload", {}, items);
  14604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14605. EXPECT_EQ(StatusCode::OK_200, res->status);
  14606. }
  14607. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14608. // Verify that make_multipart_content_provider coalesces many small segments
  14609. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14610. constexpr size_t kItemCount = 1000;
  14611. UploadFormDataItems items;
  14612. items.reserve(kItemCount);
  14613. for (size_t i = 0; i < kItemCount; i++) {
  14614. items.push_back(
  14615. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14616. }
  14617. const std::string boundary = "----test-boundary";
  14618. auto content_length = detail::get_multipart_content_length(items, boundary);
  14619. auto provider = detail::make_multipart_content_provider(items, boundary);
  14620. // Drive the provider the same way write_content_with_progress does
  14621. size_t write_count = 0;
  14622. size_t total_bytes = 0;
  14623. DataSink sink;
  14624. size_t offset = 0;
  14625. sink.write = [&](const char *d, size_t l) -> bool {
  14626. (void)d;
  14627. write_count++;
  14628. total_bytes += l;
  14629. offset += l;
  14630. return true;
  14631. };
  14632. sink.is_writable = []() -> bool { return true; };
  14633. while (offset < content_length) {
  14634. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14635. }
  14636. EXPECT_EQ(content_length, total_bytes);
  14637. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14638. // With buffering into 64KB blocks, write_count should be much smaller.
  14639. auto segment_count = 3 * kItemCount + 1;
  14640. EXPECT_LT(write_count, segment_count / 10);
  14641. }
  14642. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14643. // Integration test: send many UploadFormDataItems and verify the server
  14644. // receives all of them correctly (#2410).
  14645. constexpr size_t kItemCount = 500;
  14646. auto handled = false;
  14647. Server svr;
  14648. svr.Post("/upload", [&](const Request &req, Response &res) {
  14649. EXPECT_EQ(kItemCount, req.form.fields.size());
  14650. for (size_t i = 0; i < kItemCount; i++) {
  14651. auto key = "field" + std::to_string(i);
  14652. auto val = "value" + std::to_string(i);
  14653. auto it = req.form.fields.find(key);
  14654. if (it != req.form.fields.end()) {
  14655. EXPECT_EQ(val, it->second.content);
  14656. } else {
  14657. ADD_FAILURE() << "Missing field: " << key;
  14658. }
  14659. }
  14660. res.set_content("ok", "text/plain");
  14661. handled = true;
  14662. });
  14663. auto port = svr.bind_to_any_port(HOST);
  14664. auto t = thread([&] { svr.listen_after_bind(); });
  14665. auto se = detail::scope_exit([&] {
  14666. svr.stop();
  14667. t.join();
  14668. ASSERT_FALSE(svr.is_running());
  14669. ASSERT_TRUE(handled);
  14670. });
  14671. svr.wait_until_ready();
  14672. UploadFormDataItems items;
  14673. items.reserve(kItemCount);
  14674. for (size_t i = 0; i < kItemCount; i++) {
  14675. items.push_back(
  14676. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14677. }
  14678. Client cli(HOST, port);
  14679. auto res = cli.Post("/upload", items);
  14680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14681. EXPECT_EQ(StatusCode::OK_200, res->status);
  14682. }
  14683. TEST(MultipartFormDataTest, MakeFileProvider) {
  14684. // Verify make_file_provider sends a file's contents correctly.
  14685. const std::string file_content(4096, 'Z');
  14686. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14687. {
  14688. std::ofstream ofs(tmp_path, std::ios::binary);
  14689. ofs.write(file_content.data(),
  14690. static_cast<std::streamsize>(file_content.size()));
  14691. }
  14692. auto handled = false;
  14693. Server svr;
  14694. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14695. const ContentReader &content_reader) {
  14696. ASSERT_TRUE(req.is_multipart_form_data());
  14697. std::vector<FormData> items;
  14698. content_reader(
  14699. [&](const FormData &file) {
  14700. items.push_back(file);
  14701. return true;
  14702. },
  14703. [&](const char *data, size_t data_length) {
  14704. items.back().content.append(data, data_length);
  14705. return true;
  14706. });
  14707. ASSERT_EQ(1u, items.size());
  14708. EXPECT_EQ("myfile", items[0].name);
  14709. EXPECT_EQ("data.bin", items[0].filename);
  14710. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14711. EXPECT_EQ(file_content, items[0].content);
  14712. handled = true;
  14713. });
  14714. auto port = svr.bind_to_any_port(HOST);
  14715. auto t = thread([&] { svr.listen_after_bind(); });
  14716. auto se = detail::scope_exit([&] {
  14717. svr.stop();
  14718. t.join();
  14719. ASSERT_FALSE(svr.is_running());
  14720. ASSERT_TRUE(handled);
  14721. std::remove(tmp_path.c_str());
  14722. });
  14723. svr.wait_until_ready();
  14724. FormDataProviderItems providers;
  14725. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14726. "application/octet-stream"));
  14727. Client cli(HOST, port);
  14728. auto res = cli.Post("/upload", {}, {}, providers);
  14729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14730. EXPECT_EQ(StatusCode::OK_200, res->status);
  14731. }
  14732. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14733. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14734. // (100) headers is rejected with a 400 Bad Request response.
  14735. Server svr;
  14736. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14737. res.set_content("ok", "text/plain");
  14738. });
  14739. thread t = thread([&] { svr.listen(HOST, PORT); });
  14740. auto se = detail::scope_exit([&] {
  14741. svr.stop();
  14742. t.join();
  14743. ASSERT_FALSE(svr.is_running());
  14744. });
  14745. svr.wait_until_ready();
  14746. // Build a multipart part with 101 custom headers (exceeding
  14747. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14748. std::stringstream body;
  14749. body << "--simpleboundary\r\n"
  14750. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14751. for (int i = 0; i < 101; i++) {
  14752. body << "X-Custom-Header-" << i << ": value\r\n";
  14753. }
  14754. body << "\r\n"
  14755. << "value1\r\n"
  14756. << "--simpleboundary--\r\n";
  14757. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14758. Client cli(HOST, PORT);
  14759. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14762. }
  14763. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14764. // A body that never contains the declared boundary must not be accumulated
  14765. // while the parser waits for it. Buffering it would also make every read
  14766. // rescan everything seen so far, which is quadratic in the body size.
  14767. Server svr;
  14768. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14769. res.set_content("ok", "text/plain");
  14770. });
  14771. auto port = svr.bind_to_any_port(HOST);
  14772. thread t = thread([&] { svr.listen_after_bind(); });
  14773. auto se = detail::scope_exit([&] {
  14774. svr.stop();
  14775. t.join();
  14776. ASSERT_FALSE(svr.is_running());
  14777. });
  14778. svr.wait_until_ready();
  14779. Client cli(HOST, port);
  14780. cli.set_read_timeout(60, 0);
  14781. cli.set_write_timeout(60, 0);
  14782. // '-' is the worst case: it matches the first character of the boundary, so
  14783. // every position has to be checked against it.
  14784. auto post_dashes = [&](size_t size) {
  14785. const std::string body(size, '-');
  14786. auto start = std::chrono::steady_clock::now();
  14787. auto res =
  14788. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14789. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14790. std::chrono::steady_clock::now() - start)
  14791. .count();
  14792. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14793. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14794. return ms;
  14795. };
  14796. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14797. // Windows.
  14798. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14799. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14800. // Comparing the two sizes rather than checking an absolute duration keeps
  14801. // this meaningful across build types and CI load, both of which move the
  14802. // absolute numbers by more than an order of magnitude. Four times the bytes
  14803. // costs about four times the time when parsing is linear, and about sixteen
  14804. // times when the body is buffered and rescanned.
  14805. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14806. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14807. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14808. << "ms, which suggests the body is being buffered and rescanned";
  14809. }
  14810. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14811. // A boundary can only be followed by CRLF or by "--", so anything else is
  14812. // malformed no matter what comes next. The parser must say so right away
  14813. // instead of buffering the rest of the declared body.
  14814. Server svr;
  14815. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14816. res.set_content("ok", "text/plain");
  14817. });
  14818. auto port = svr.bind_to_any_port(HOST);
  14819. thread t = thread([&] { svr.listen_after_bind(); });
  14820. auto se = detail::scope_exit([&] {
  14821. svr.stop();
  14822. t.join();
  14823. ASSERT_FALSE(svr.is_running());
  14824. });
  14825. svr.wait_until_ready();
  14826. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14827. // buffers instead of failing would still be waiting for the remaining bytes.
  14828. const std::string body = "--zzzz\r\n"
  14829. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14830. "\r\n"
  14831. "text1"
  14832. "\r\n--zzzzXX";
  14833. const std::string req = "POST /post HTTP/1.1\r\n"
  14834. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14835. "Content-Length: 1048576\r\n"
  14836. "\r\n" +
  14837. body;
  14838. std::string response;
  14839. ASSERT_TRUE(send_request(3, req, &response, port));
  14840. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14841. EXPECT_EQ("400", response.substr(9, 3));
  14842. }
  14843. // Posts a multipart body split into two writes, so that the server sees the
  14844. // split at whatever offset the caller chose, and expects the single "text1"
  14845. // field to come through.
  14846. static void expect_split_multipart_ok(const std::string &body1,
  14847. const std::string &body2) {
  14848. auto handled = false;
  14849. Server svr;
  14850. svr.Post("/post", [&](const Request &req, Response &) {
  14851. EXPECT_EQ(1u, req.form.fields.size());
  14852. EXPECT_EQ("text1", req.form.get_field("text1"));
  14853. handled = true;
  14854. });
  14855. auto port = svr.bind_to_any_port(HOST);
  14856. thread t = thread([&] { svr.listen_after_bind(); });
  14857. auto se = detail::scope_exit([&] {
  14858. svr.stop();
  14859. t.join();
  14860. ASSERT_FALSE(svr.is_running());
  14861. ASSERT_TRUE(handled);
  14862. });
  14863. svr.wait_until_ready();
  14864. // "Connection: close" makes the server close once it has answered, so the
  14865. // response drain ends immediately instead of idling until the read timeout.
  14866. const std::string head =
  14867. "POST /post HTTP/1.1\r\n"
  14868. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14869. "Connection: close\r\n"
  14870. "Content-Length: " +
  14871. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14872. std::string response;
  14873. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14874. ASSERT_GE(response.size(), 12u) << "no response";
  14875. EXPECT_EQ("200", response.substr(9, 3));
  14876. }
  14877. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14878. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14879. // ignored, including when it does not arrive in the same read as the
  14880. // close-delimiter itself.
  14881. expect_split_multipart_ok("--zzzz\r\n"
  14882. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14883. "\r\n"
  14884. "text1"
  14885. "\r\n--zzzz--",
  14886. "\r\nthis epilogue must be ignored\r\n");
  14887. }
  14888. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14889. // The initial boundary may be preceded by a preamble of any length and may
  14890. // straddle a read boundary. Discarding data while waiting for it must not
  14891. // throw away a partial boundary sitting at the end of the buffer.
  14892. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14893. "zz\r\n"
  14894. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14895. "\r\n"
  14896. "text1"
  14897. "\r\n--zzzz--\r\n");
  14898. }
  14899. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14900. // The received boundary was only checked for being non-empty, so it could be
  14901. // as long as a header is allowed to be. The parser scans the body for
  14902. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14903. // costs a nearly full comparison at nearly every position, making the
  14904. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14905. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14906. Server svr;
  14907. svr.Post("/post", [](const Request &req, Response &res) {
  14908. EXPECT_EQ(1u, req.form.fields.size());
  14909. EXPECT_EQ("text1", req.form.get_field("text1"));
  14910. res.set_content("ok", "text/plain");
  14911. });
  14912. auto port = svr.bind_to_any_port(HOST);
  14913. thread t = thread([&] { svr.listen_after_bind(); });
  14914. auto se = detail::scope_exit([&] {
  14915. svr.stop();
  14916. t.join();
  14917. ASSERT_FALSE(svr.is_running());
  14918. });
  14919. svr.wait_until_ready();
  14920. Client cli(HOST, port);
  14921. auto post_with_boundary_of_length = [&](size_t len) {
  14922. const std::string boundary(len, 'a');
  14923. const std::string body =
  14924. "--" + boundary +
  14925. "\r\n"
  14926. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14927. "\r\n"
  14928. "text1"
  14929. "\r\n--" +
  14930. boundary + "--\r\n";
  14931. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14932. };
  14933. auto res = post_with_boundary_of_length(70);
  14934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14935. EXPECT_EQ(StatusCode::OK_200, res->status);
  14936. res = post_with_boundary_of_length(71);
  14937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14938. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14939. }
  14940. TEST(MakeFileBodyTest, Basic) {
  14941. const std::string file_content(4096, 'Z');
  14942. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14943. {
  14944. std::ofstream ofs(tmp_path, std::ios::binary);
  14945. ofs.write(file_content.data(),
  14946. static_cast<std::streamsize>(file_content.size()));
  14947. }
  14948. auto handled = false;
  14949. Server svr;
  14950. svr.Post("/upload", [&](const Request &req, Response &res) {
  14951. EXPECT_EQ(file_content, req.body);
  14952. handled = true;
  14953. res.status = StatusCode::OK_200;
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. auto t = thread([&] { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. ASSERT_FALSE(svr.is_running());
  14961. ASSERT_TRUE(handled);
  14962. std::remove(tmp_path.c_str());
  14963. });
  14964. svr.wait_until_ready();
  14965. auto fb = make_file_body(tmp_path);
  14966. ASSERT_GT(fb.first, 0u);
  14967. Client cli(HOST, port);
  14968. auto res =
  14969. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14971. EXPECT_EQ(StatusCode::OK_200, res->status);
  14972. }
  14973. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14974. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14975. {
  14976. std::ofstream ofs(path, std::ios::binary);
  14977. const std::string content(100, 'A');
  14978. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14979. }
  14980. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14981. auto body = make_file_body(path);
  14982. ASSERT_EQ(100u, body.first);
  14983. ASSERT_TRUE(static_cast<bool>(body.second));
  14984. // Rewritten shorter after its length was measured - and, on a server, after
  14985. // that length has already gone out as Content-Length.
  14986. {
  14987. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14988. const std::string content(10, 'A');
  14989. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14990. }
  14991. std::string written;
  14992. DataSink sink;
  14993. sink.write = [&](const char *d, size_t l) {
  14994. written.append(d, l);
  14995. return true;
  14996. };
  14997. // The provider has to report failure. write_content_with_progress() advances
  14998. // its offset only by what was written, so a provider that returns true
  14999. // without completing the length it promised is called again straight away,
  15000. // and again.
  15001. EXPECT_FALSE(body.second(0, body.first, sink));
  15002. EXPECT_EQ(std::string(10, 'A'), written);
  15003. }
  15004. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15005. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15006. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15007. {
  15008. std::ofstream ofs(path, std::ios::binary);
  15009. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15010. }
  15011. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15012. auto body = make_file_body(path);
  15013. ASSERT_EQ(content.size(), body.first);
  15014. ASSERT_TRUE(static_cast<bool>(body.second));
  15015. std::string written;
  15016. DataSink sink;
  15017. sink.write = [&](const char *d, size_t l) {
  15018. written.append(d, l);
  15019. return true;
  15020. };
  15021. EXPECT_TRUE(body.second(0, body.first, sink));
  15022. EXPECT_EQ(content, written);
  15023. }
  15024. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15025. static constexpr unsigned int number_of_tasks{1000000};
  15026. std::atomic_uint count{0};
  15027. std::unique_ptr<TaskQueue> task_queue{
  15028. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15029. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15030. auto queued = task_queue->enqueue(
  15031. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15032. EXPECT_TRUE(queued);
  15033. }
  15034. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15035. task_queue->shutdown();
  15036. #else
  15037. EXPECT_NO_THROW(task_queue->shutdown());
  15038. #endif
  15039. EXPECT_EQ(number_of_tasks, count.load());
  15040. }
  15041. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15042. static constexpr unsigned int number_of_tasks{1000000};
  15043. static constexpr unsigned int qlimit{2};
  15044. unsigned int queued_count{0};
  15045. std::atomic_uint count{0};
  15046. std::unique_ptr<TaskQueue> task_queue{
  15047. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15048. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15049. if (task_queue->enqueue(
  15050. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15051. queued_count++;
  15052. }
  15053. }
  15054. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15055. task_queue->shutdown();
  15056. #else
  15057. EXPECT_NO_THROW(task_queue->shutdown());
  15058. #endif
  15059. EXPECT_EQ(queued_count, count.load());
  15060. EXPECT_TRUE(queued_count <= number_of_tasks);
  15061. EXPECT_TRUE(queued_count >= qlimit);
  15062. }
  15063. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15064. // Use a short idle timeout so a dynamic thread spawns, times out and
  15065. // exits during the test, and the pool keeps working afterwards.
  15066. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15067. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15068. /*idle_timeout_sec=*/1}};
  15069. std::atomic_uint count{0};
  15070. std::condition_variable cv;
  15071. std::mutex mtx;
  15072. bool release = false;
  15073. // Block the base thread so the second task spawns a dynamic thread.
  15074. EXPECT_TRUE(task_queue->enqueue([&] {
  15075. std::unique_lock<std::mutex> lock(mtx);
  15076. while (!release) {
  15077. cv.wait(lock);
  15078. }
  15079. count++;
  15080. }));
  15081. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15082. // Let the dynamic thread finish its task and exceed the idle timeout.
  15083. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15084. {
  15085. std::unique_lock<std::mutex> lock(mtx);
  15086. release = true;
  15087. }
  15088. cv.notify_all();
  15089. // The pool must still accept and run tasks after the dynamic thread exited.
  15090. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15091. task_queue->shutdown();
  15092. EXPECT_EQ(3u, count.load());
  15093. }
  15094. TEST(TaskQueueTest, MaxQueuedRequests) {
  15095. static constexpr unsigned int qlimit{3};
  15096. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15097. std::condition_variable sem_cv;
  15098. std::mutex sem_mtx;
  15099. int credits = 0;
  15100. bool queued;
  15101. /* Fill up the queue with tasks that will block until we give them credits to
  15102. * complete. */
  15103. for (unsigned int n = 0; n <= qlimit;) {
  15104. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15105. std::unique_lock<std::mutex> lock(sem_mtx);
  15106. while (credits <= 0) {
  15107. sem_cv.wait(lock);
  15108. }
  15109. /* Consume the credit and signal the test code if they are all gone. */
  15110. if (--credits == 0) { sem_cv.notify_one(); }
  15111. });
  15112. if (n < qlimit) {
  15113. /* The first qlimit enqueues must succeed. */
  15114. EXPECT_TRUE(queued);
  15115. } else {
  15116. /* The last one will succeed only when the worker thread
  15117. * starts and dequeues the first blocking task. Although
  15118. * not necessary for the correctness of this test, we sleep for
  15119. * a short while to avoid busy waiting. */
  15120. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15121. }
  15122. if (queued) { n++; }
  15123. }
  15124. /* Further enqueues must fail since the queue is full. */
  15125. for (auto i = 0; i < 4; i++) {
  15126. queued = task_queue->enqueue([] {});
  15127. EXPECT_FALSE(queued);
  15128. }
  15129. /* Give the credits to allow the previous tasks to complete. */
  15130. {
  15131. std::unique_lock<std::mutex> lock(sem_mtx);
  15132. credits += qlimit + 1;
  15133. }
  15134. sem_cv.notify_all();
  15135. /* Wait for all the credits to be consumed. */
  15136. {
  15137. std::unique_lock<std::mutex> lock(sem_mtx);
  15138. while (credits > 0) {
  15139. sem_cv.wait(lock);
  15140. }
  15141. }
  15142. /* Check that we are able again to enqueue at least qlimit tasks. */
  15143. for (unsigned int i = 0; i < qlimit; i++) {
  15144. queued = task_queue->enqueue([] {});
  15145. EXPECT_TRUE(queued);
  15146. }
  15147. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15148. task_queue->shutdown();
  15149. #else
  15150. EXPECT_NO_THROW(task_queue->shutdown());
  15151. #endif
  15152. }
  15153. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15154. Server svr;
  15155. std::string method;
  15156. std::string body;
  15157. auto has_content_length = false;
  15158. auto has_transfer_encoding = false;
  15159. std::atomic<int> bad_requests{0};
  15160. // Leftover body bytes get parsed as a malformed request and answered with
  15161. // 400
  15162. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15163. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15164. });
  15165. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15166. res.set_redirect("/down", StatusCode::SeeOther_303);
  15167. });
  15168. svr.Get("/down", [&](const Request &req, Response &res) {
  15169. method = req.method;
  15170. body = req.body;
  15171. has_content_length = req.has_header("Content-Length");
  15172. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15173. res.set_content("ok", "text/plain");
  15174. });
  15175. auto port = svr.bind_to_any_port(HOST);
  15176. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15177. auto se = detail::scope_exit([&] {
  15178. svr.stop();
  15179. thread.join();
  15180. ASSERT_FALSE(svr.is_running());
  15181. });
  15182. svr.wait_until_ready();
  15183. const std::string payload = "SECRET-BODY";
  15184. auto check = [&](Client &cli, const Result &res) {
  15185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15186. EXPECT_EQ(StatusCode::OK_200, res->status);
  15187. EXPECT_EQ("ok", res->body);
  15188. EXPECT_EQ("GET", method);
  15189. EXPECT_TRUE(body.empty());
  15190. EXPECT_FALSE(has_content_length);
  15191. EXPECT_FALSE(has_transfer_encoding);
  15192. // Nothing of the original body may be left on the connection
  15193. auto res2 = cli.Get("/down");
  15194. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15195. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15196. EXPECT_EQ("ok", res2->body);
  15197. EXPECT_EQ(0, bad_requests);
  15198. };
  15199. // With content length
  15200. {
  15201. Client cli(HOST, port);
  15202. cli.set_keep_alive(true);
  15203. cli.set_follow_location(true);
  15204. auto res = cli.Post(
  15205. "/up", payload.size(),
  15206. [&](size_t offset, size_t length, DataSink &sink) {
  15207. return sink.write(payload.data() + offset, length);
  15208. },
  15209. "text/plain");
  15210. check(cli, res);
  15211. }
  15212. // Without content length (chunked)
  15213. {
  15214. Client cli(HOST, port);
  15215. cli.set_keep_alive(true);
  15216. cli.set_follow_location(true);
  15217. auto res = cli.Post(
  15218. "/up",
  15219. [&](size_t /*offset*/, DataSink &sink) {
  15220. sink.write(payload.data(), payload.size());
  15221. sink.done();
  15222. return true;
  15223. },
  15224. "text/plain");
  15225. check(cli, res);
  15226. }
  15227. }
  15228. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15229. Server svr;
  15230. std::string target;
  15231. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15232. // Echo the still-encoded name back in the Location
  15233. const std::string prefix = "/start/";
  15234. res.status = StatusCode::Found_302;
  15235. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15236. });
  15237. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15238. target = req.target;
  15239. res.set_content("ok", "text/plain");
  15240. });
  15241. auto port = svr.bind_to_any_port(HOST);
  15242. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15243. auto se = detail::scope_exit([&] {
  15244. svr.stop();
  15245. thread.join();
  15246. ASSERT_FALSE(svr.is_running());
  15247. });
  15248. svr.wait_until_ready();
  15249. // Decoding the Location path would turn the first four into a path
  15250. // separator, a query delimiter, a fragment delimiter and a different
  15251. // percent-encoded octet. The rest must keep reaching the server as they are.
  15252. const std::vector<std::string> names = {
  15253. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15254. };
  15255. for (auto path_encode : {true, false}) {
  15256. Client cli(HOST, port);
  15257. cli.set_follow_location(true);
  15258. cli.set_path_encode(path_encode);
  15259. for (const auto &name : names) {
  15260. target.clear();
  15261. auto res = cli.Get("/start/" + name);
  15262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15263. EXPECT_EQ(StatusCode::OK_200, res->status);
  15264. EXPECT_EQ("/dest/" + name, target);
  15265. }
  15266. }
  15267. }
  15268. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15269. Server svr;
  15270. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15271. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15272. });
  15273. svr.Get("/hello", [](const Request &req, Response &res) {
  15274. res.set_content(req.get_param_value("key"), "text/plain");
  15275. });
  15276. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. thread.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. });
  15282. svr.wait_until_ready();
  15283. {
  15284. Client cli(HOST, PORT);
  15285. cli.set_follow_location(true);
  15286. auto res = cli.Get("/");
  15287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15288. EXPECT_EQ(StatusCode::OK_200, res->status);
  15289. EXPECT_EQ("val&key2=val2", res->body);
  15290. }
  15291. }
  15292. #endif
  15293. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15294. Server svr;
  15295. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15296. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15297. });
  15298. svr.Get("/hello", [](const Request &req, Response &res) {
  15299. res.set_content(req.get_param_value("key"), "text/plain");
  15300. });
  15301. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15302. auto se = detail::scope_exit([&] {
  15303. svr.stop();
  15304. thread.join();
  15305. ASSERT_FALSE(svr.is_running());
  15306. });
  15307. svr.wait_until_ready();
  15308. {
  15309. Client cli(HOST, PORT);
  15310. cli.set_follow_location(true);
  15311. auto res = cli.Get("/");
  15312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15313. EXPECT_EQ(StatusCode::OK_200, res->status);
  15314. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15315. }
  15316. }
  15317. TEST(RedirectTest, RedirectWithPlusInPath) {
  15318. Server svr;
  15319. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15320. res.set_redirect("/a+b");
  15321. });
  15322. // Route pattern uses regex; escape + as \\+
  15323. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15324. res.set_content(req.path, "text/plain");
  15325. });
  15326. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15327. auto se = detail::scope_exit([&] {
  15328. svr.stop();
  15329. thread.join();
  15330. ASSERT_FALSE(svr.is_running());
  15331. });
  15332. svr.wait_until_ready();
  15333. {
  15334. Client cli(HOST, PORT);
  15335. cli.set_follow_location(true);
  15336. auto res = cli.Get("/");
  15337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15338. EXPECT_EQ(StatusCode::OK_200, res->status);
  15339. EXPECT_EQ("/a+b", res->body);
  15340. }
  15341. }
  15342. TEST(RedirectTest, ResolveRelativeLocation) {
  15343. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15344. const std::vector<std::pair<std::string, std::string>> cases = {
  15345. {"g", "/b/c/g"},
  15346. {"./g", "/b/c/g"},
  15347. {"g/", "/b/c/g/"},
  15348. {"?y", "/b/c/d;p?y"},
  15349. {"g?y", "/b/c/g?y"},
  15350. {"#s", "/b/c/d;p?q#s"},
  15351. {"g#s", "/b/c/g#s"},
  15352. {"g?y#s", "/b/c/g?y#s"},
  15353. {";x", "/b/c/;x"},
  15354. {"g;x", "/b/c/g;x"},
  15355. {".", "/b/c/"},
  15356. {"./", "/b/c/"},
  15357. {"..", "/b/"},
  15358. {"../", "/b/"},
  15359. {"../g", "/b/g"},
  15360. {"../..", "/"},
  15361. {"../../", "/"},
  15362. {"../../g", "/g"},
  15363. {"../../../g", "/g"},
  15364. {"g.", "/b/c/g."},
  15365. {".g", "/b/c/.g"},
  15366. {"g..", "/b/c/g.."},
  15367. {"..g", "/b/c/..g"},
  15368. {"./../g", "/b/g"},
  15369. {"./g/.", "/b/c/g/"},
  15370. {"g/./h", "/b/c/g/h"},
  15371. {"g/../h", "/b/c/h"},
  15372. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15373. {"g;x=1/../y", "/b/c/y"},
  15374. {"g?y/./x", "/b/c/g?y/./x"},
  15375. {"g#s/../x", "/b/c/g#s/../x"},
  15376. // Not relative-path references, so left for parse_url.
  15377. {"/g", "/g"},
  15378. {"//g", "//g"},
  15379. {"http://g/x", "http://g/x"},
  15380. {"g:h", "g:h"},
  15381. };
  15382. for (const auto &c : cases) {
  15383. EXPECT_EQ(c.second,
  15384. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15385. << c.first;
  15386. }
  15387. }
  15388. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15389. Server svr;
  15390. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15391. res.set_redirect(req.get_param_value("to"));
  15392. });
  15393. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15394. res.set_content(req.target, "text/plain");
  15395. });
  15396. svr.Get("/other", [](const Request &req, Response &res) {
  15397. res.set_content(req.target, "text/plain");
  15398. });
  15399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15400. auto se = detail::scope_exit([&] {
  15401. svr.stop();
  15402. thread.join();
  15403. ASSERT_FALSE(svr.is_running());
  15404. });
  15405. svr.wait_until_ready();
  15406. const std::vector<std::pair<std::string, std::string>> cases = {
  15407. {"next", "/dir/next"},
  15408. {"./next?x=1", "/dir/next?x=1"},
  15409. {"../other", "/other"},
  15410. };
  15411. for (const auto &c : cases) {
  15412. Client cli(HOST, PORT);
  15413. cli.set_follow_location(true);
  15414. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15415. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15416. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15417. EXPECT_EQ(c.second, res->body) << c.first;
  15418. }
  15419. }
  15420. #ifdef CPPHTTPLIB_SSL_ENABLED
  15421. TEST(RedirectTest, Issue2185_Online) {
  15422. SSLClient client("github.com");
  15423. client.set_follow_location(true);
  15424. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15425. "Coollab-Windows.zip");
  15426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15427. EXPECT_EQ(StatusCode::OK_200, res->status);
  15428. EXPECT_EQ(9920427U, res->body.size());
  15429. }
  15430. #endif
  15431. TEST(VulnerabilityTest, CRLFInjection) {
  15432. Server svr;
  15433. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15434. res.set_content("Hello 1", "text/plain");
  15435. });
  15436. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15437. res.set_content("Hello 2", "text/plain");
  15438. });
  15439. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15440. res.set_content("Hello 3", "text/plain");
  15441. });
  15442. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15443. res.set_content("Hello 4", "text/plain");
  15444. });
  15445. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15446. for (const auto &x : req.headers) {
  15447. auto key = x.first;
  15448. EXPECT_STRNE("evil", key.c_str());
  15449. }
  15450. });
  15451. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15452. auto se = detail::scope_exit([&] {
  15453. svr.stop();
  15454. thread.join();
  15455. ASSERT_FALSE(svr.is_running());
  15456. });
  15457. svr.wait_until_ready();
  15458. {
  15459. Client cli(HOST, PORT);
  15460. cli.Post("/test1", "A=B",
  15461. "application/x-www-form-urlencoded\r\nevil: hello1");
  15462. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15463. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15464. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15465. }
  15466. }
  15467. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15468. auto server_thread = std::thread([] {
  15469. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15470. default_socket_options(srv);
  15471. sockaddr_in addr{};
  15472. addr.sin_family = AF_INET;
  15473. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15474. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15475. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15476. ::listen(srv, 1);
  15477. sockaddr_in cli_addr{};
  15478. socklen_t cli_len = sizeof(cli_addr);
  15479. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15480. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15481. std::string buf_all;
  15482. char buf[2048];
  15483. ssize_t n;
  15484. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15485. buf_all.append(buf, static_cast<size_t>(n));
  15486. size_t pos;
  15487. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15488. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15489. auto e = request_block.find("\r\n");
  15490. if (e != std::string::npos) {
  15491. auto request_line = request_block.substr(0, e);
  15492. std::string msg =
  15493. "CRLF injection detected in request line: '" + request_line + "'";
  15494. EXPECT_FALSE(true) << msg;
  15495. }
  15496. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15497. ::send(cli,
  15498. #ifdef _WIN32
  15499. static_cast<const char *>(resp.c_str()),
  15500. static_cast<int>(resp.size()),
  15501. #else
  15502. resp.c_str(), resp.size(),
  15503. #endif
  15504. 0);
  15505. buf_all.erase(0, pos + 4);
  15506. }
  15507. }
  15508. detail::close_socket(cli);
  15509. detail::close_socket(srv);
  15510. });
  15511. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15512. auto cli = Client("127.0.0.1", PORT + 1);
  15513. auto headers = Headers{
  15514. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15515. {"Connection", "keep-alive"}};
  15516. auto res = cli.Get("/hi", headers);
  15517. EXPECT_FALSE(res);
  15518. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15519. server_thread.join();
  15520. }
  15521. // A request rejected before any byte reaches the socket must fail right away
  15522. // instead of waiting for a response the server will never send.
  15523. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15524. // The kernel completes the TCP handshake from the listen backlog, so the
  15525. // client connects, but nothing ever reads, responds or closes.
  15526. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15527. default_socket_options(srv);
  15528. sockaddr_in addr{};
  15529. addr.sin_family = AF_INET;
  15530. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15531. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15532. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15533. ASSERT_EQ(0, ::listen(srv, 8));
  15534. auto cli = Client("127.0.0.1", PORT + 1);
  15535. cli.set_read_timeout(10, 0);
  15536. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15537. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15538. std::chrono::steady_clock::now() - start)
  15539. .count();
  15540. };
  15541. {
  15542. Request req;
  15543. req.method = "GE T";
  15544. req.path = "/";
  15545. auto start = std::chrono::steady_clock::now();
  15546. auto res = cli.send(req);
  15547. EXPECT_FALSE(res);
  15548. EXPECT_EQ(Error::Write, res.error());
  15549. EXPECT_LT(elapsed_ms(start), 1000);
  15550. }
  15551. {
  15552. auto start = std::chrono::steady_clock::now();
  15553. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15554. EXPECT_FALSE(res);
  15555. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15556. EXPECT_LT(elapsed_ms(start), 1000);
  15557. }
  15558. EXPECT_FALSE(cli.is_socket_open());
  15559. detail::close_socket(srv);
  15560. }
  15561. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15562. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15563. default_socket_options(srv);
  15564. sockaddr_in addr{};
  15565. addr.sin_family = AF_INET;
  15566. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15567. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15568. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15569. ASSERT_EQ(0, ::listen(srv, 1));
  15570. std::string received;
  15571. auto server_thread = std::thread([&] {
  15572. auto sock = ::accept(srv, nullptr, nullptr);
  15573. if (sock == INVALID_SOCKET) { return; }
  15574. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15575. char buf[2048];
  15576. ssize_t n;
  15577. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15578. received.append(buf, static_cast<size_t>(n));
  15579. }
  15580. detail::close_socket(sock);
  15581. });
  15582. {
  15583. auto cli = Client("127.0.0.1", PORT + 1);
  15584. // "Z" sorts after the default headers, so writing straight to the socket
  15585. // would have sent the request line and those headers before the rejection.
  15586. auto handle =
  15587. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15588. EXPECT_FALSE(handle.is_valid());
  15589. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15590. }
  15591. server_thread.join();
  15592. detail::close_socket(srv);
  15593. EXPECT_TRUE(received.empty()) << received;
  15594. }
  15595. TEST(PathParamsTest, StaticMatch) {
  15596. const auto pattern = "/users/all";
  15597. detail::PathParamsMatcher matcher(pattern);
  15598. Request request;
  15599. request.path = "/users/all";
  15600. ASSERT_TRUE(matcher.match(request));
  15601. std::unordered_map<std::string, std::string> expected_params = {};
  15602. EXPECT_EQ(request.path_params, expected_params);
  15603. }
  15604. TEST(PathParamsTest, StaticMismatch) {
  15605. const auto pattern = "/users/all";
  15606. detail::PathParamsMatcher matcher(pattern);
  15607. Request request;
  15608. request.path = "/users/1";
  15609. ASSERT_FALSE(matcher.match(request));
  15610. }
  15611. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15612. const auto pattern = "/users/:id/subscriptions";
  15613. detail::PathParamsMatcher matcher(pattern);
  15614. Request request;
  15615. request.path = "/users/42/subscriptions";
  15616. ASSERT_TRUE(matcher.match(request));
  15617. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15618. EXPECT_EQ(request.path_params, expected_params);
  15619. }
  15620. TEST(PathParamsTest, SingleParamInTheEnd) {
  15621. const auto pattern = "/users/:id";
  15622. detail::PathParamsMatcher matcher(pattern);
  15623. Request request;
  15624. request.path = "/users/24";
  15625. ASSERT_TRUE(matcher.match(request));
  15626. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15627. EXPECT_EQ(request.path_params, expected_params);
  15628. }
  15629. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15630. const auto pattern = "/users/:id/";
  15631. detail::PathParamsMatcher matcher(pattern);
  15632. Request request;
  15633. request.path = "/users/42/";
  15634. ASSERT_TRUE(matcher.match(request));
  15635. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15636. EXPECT_EQ(request.path_params, expected_params);
  15637. }
  15638. TEST(PathParamsTest, EmptyParam) {
  15639. const auto pattern = "/users/:id/";
  15640. detail::PathParamsMatcher matcher(pattern);
  15641. Request request;
  15642. request.path = "/users//";
  15643. ASSERT_TRUE(matcher.match(request));
  15644. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15645. EXPECT_EQ(request.path_params, expected_params);
  15646. }
  15647. TEST(PathParamsTest, FragmentMismatch) {
  15648. const auto pattern = "/users/:id/";
  15649. detail::PathParamsMatcher matcher(pattern);
  15650. Request request;
  15651. request.path = "/admins/24/";
  15652. ASSERT_FALSE(matcher.match(request));
  15653. }
  15654. TEST(PathParamsTest, ExtraFragments) {
  15655. const auto pattern = "/users/:id";
  15656. detail::PathParamsMatcher matcher(pattern);
  15657. Request request;
  15658. request.path = "/users/42/subscriptions";
  15659. ASSERT_FALSE(matcher.match(request));
  15660. }
  15661. TEST(PathParamsTest, MissingTrailingParam) {
  15662. const auto pattern = "/users/:id";
  15663. detail::PathParamsMatcher matcher(pattern);
  15664. Request request;
  15665. request.path = "/users";
  15666. ASSERT_FALSE(matcher.match(request));
  15667. }
  15668. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15669. const auto pattern = "/users/:id/subscriptions";
  15670. detail::PathParamsMatcher matcher(pattern);
  15671. Request request;
  15672. request.path = "/users/subscriptions";
  15673. ASSERT_FALSE(matcher.match(request));
  15674. }
  15675. TEST(PathParamsTest, MultipleParams) {
  15676. const auto pattern = "/users/:userid/subscriptions/:subid";
  15677. detail::PathParamsMatcher matcher(pattern);
  15678. Request request;
  15679. request.path = "/users/42/subscriptions/2";
  15680. ASSERT_TRUE(matcher.match(request));
  15681. std::unordered_map<std::string, std::string> expected_params = {
  15682. {"userid", "42"}, {"subid", "2"}};
  15683. EXPECT_EQ(request.path_params, expected_params);
  15684. }
  15685. TEST(PathParamsTest, SequenceOfParams) {
  15686. const auto pattern = "/values/:x/:y/:z";
  15687. detail::PathParamsMatcher matcher(pattern);
  15688. Request request;
  15689. request.path = "/values/1/2/3";
  15690. ASSERT_TRUE(matcher.match(request));
  15691. std::unordered_map<std::string, std::string> expected_params = {
  15692. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15693. EXPECT_EQ(request.path_params, expected_params);
  15694. }
  15695. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15696. const auto pattern = "/prefix:suffix";
  15697. detail::PathParamsMatcher matcher(pattern);
  15698. Request request;
  15699. request.path = "/prefix:suffix";
  15700. ASSERT_TRUE(matcher.match(request));
  15701. const std::unordered_map<std::string, std::string> expected_params = {};
  15702. EXPECT_EQ(request.path_params, expected_params);
  15703. }
  15704. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15705. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15706. // calling thread's stack on a long enough path for a quantified pattern;
  15707. // RegexMatcher must refuse to run regex matching on paths beyond
  15708. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15709. detail::RegexMatcher matcher("/files/(.*)");
  15710. Request within_limit;
  15711. within_limit.path = "/files/" + std::string(10, 'A');
  15712. EXPECT_TRUE(matcher.match(within_limit));
  15713. Request over_limit;
  15714. over_limit.path =
  15715. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15716. EXPECT_FALSE(matcher.match(over_limit));
  15717. }
  15718. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15719. Server svr;
  15720. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15721. res.set_content("ok", "text/plain");
  15722. });
  15723. auto port = svr.bind_to_any_port(HOST);
  15724. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15725. auto se = detail::scope_exit([&] {
  15726. svr.stop();
  15727. thread.join();
  15728. ASSERT_FALSE(svr.is_running());
  15729. });
  15730. svr.wait_until_ready();
  15731. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15732. // request URI limit; this used to be able to crash the process.
  15733. std::string path =
  15734. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15735. std::string req = "GET " + path +
  15736. " HTTP/1.1\r\n"
  15737. "Host: " +
  15738. std::string(HOST) + ":" + std::to_string(port) +
  15739. "\r\n"
  15740. "Connection: close\r\n"
  15741. "\r\n";
  15742. std::string response;
  15743. ASSERT_TRUE(send_request(5, req, &response, port));
  15744. EXPECT_NE(std::string::npos, response.find("404"));
  15745. }
  15746. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15747. Server svr;
  15748. auto handler = [](const Request & /*req*/, Response &res) {
  15749. res.set_content("hit", "text/plain");
  15750. };
  15751. // No regex metacharacter, so this one is compared literally
  15752. svr.Get("/literal/route", handler);
  15753. // '.' is a regex metacharacter, so this one must keep regex semantics
  15754. svr.Get("/a.c", handler);
  15755. auto port = svr.bind_to_any_port(HOST);
  15756. std::thread t([&]() { svr.listen_after_bind(); });
  15757. auto se = detail::scope_exit([&] {
  15758. svr.stop();
  15759. t.join();
  15760. ASSERT_FALSE(svr.is_running());
  15761. });
  15762. svr.wait_until_ready();
  15763. Client cli(HOST, port);
  15764. struct {
  15765. const char *path;
  15766. int status;
  15767. } cases[] = {
  15768. {"/literal/route", StatusCode::OK_200},
  15769. {"/literal/routes", StatusCode::NotFound_404},
  15770. {"/literal/rout", StatusCode::NotFound_404},
  15771. {"/abc", StatusCode::OK_200},
  15772. {"/a.c", StatusCode::OK_200},
  15773. };
  15774. for (const auto &x : cases) {
  15775. auto res = cli.Get(x.path);
  15776. ASSERT_TRUE(res) << x.path;
  15777. EXPECT_EQ(x.status, res->status) << x.path;
  15778. }
  15779. }
  15780. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15781. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15782. // from exhausting the stack, so it must only constrain routes that actually
  15783. // run a regular expression. A literal route is matched by comparison and
  15784. // stays usable at any length.
  15785. Server svr;
  15786. const std::string pattern =
  15787. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15788. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15789. res.set_content("hit", "text/plain");
  15790. });
  15791. auto port = svr.bind_to_any_port(HOST);
  15792. std::thread t([&]() { svr.listen_after_bind(); });
  15793. auto se = detail::scope_exit([&] {
  15794. svr.stop();
  15795. t.join();
  15796. ASSERT_FALSE(svr.is_running());
  15797. });
  15798. svr.wait_until_ready();
  15799. Client cli(HOST, port);
  15800. auto res = cli.Get(pattern);
  15801. ASSERT_TRUE(res);
  15802. EXPECT_EQ(StatusCode::OK_200, res->status);
  15803. }
  15804. TEST(ParseUrlTest, VariousPatterns) {
  15805. {
  15806. detail::UrlComponents uc;
  15807. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15808. EXPECT_EQ("http", uc.scheme);
  15809. EXPECT_EQ("example.com", uc.host);
  15810. EXPECT_EQ("8080", uc.port);
  15811. EXPECT_EQ("/path", uc.path);
  15812. EXPECT_EQ("?q=1", uc.query);
  15813. }
  15814. {
  15815. detail::UrlComponents uc;
  15816. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15817. EXPECT_EQ("https", uc.scheme);
  15818. EXPECT_EQ("example.com", uc.host);
  15819. EXPECT_TRUE(uc.port.empty());
  15820. EXPECT_EQ("/path", uc.path);
  15821. }
  15822. {
  15823. detail::UrlComponents uc;
  15824. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15825. EXPECT_EQ("::1", uc.host);
  15826. EXPECT_EQ("8080", uc.port);
  15827. EXPECT_EQ("/path", uc.path);
  15828. }
  15829. {
  15830. detail::UrlComponents uc;
  15831. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15832. }
  15833. {
  15834. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15835. // the path while the connection still targets the bracketed host.
  15836. detail::UrlComponents uc;
  15837. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15838. }
  15839. {
  15840. detail::UrlComponents uc;
  15841. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15842. }
  15843. {
  15844. detail::UrlComponents uc;
  15845. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15846. EXPECT_EQ("::1", uc.host);
  15847. EXPECT_TRUE(uc.port.empty());
  15848. EXPECT_EQ("/path", uc.path);
  15849. }
  15850. {
  15851. detail::UrlComponents uc;
  15852. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15853. EXPECT_TRUE(uc.scheme.empty());
  15854. EXPECT_EQ("example.com", uc.host);
  15855. EXPECT_EQ("/path", uc.path);
  15856. EXPECT_EQ("?q=1", uc.query);
  15857. }
  15858. {
  15859. detail::UrlComponents uc;
  15860. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15861. EXPECT_TRUE(uc.host.empty());
  15862. EXPECT_EQ("/path", uc.path);
  15863. EXPECT_EQ("?q=1", uc.query);
  15864. }
  15865. {
  15866. detail::UrlComponents uc;
  15867. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15868. EXPECT_EQ("example.com", uc.host);
  15869. EXPECT_EQ("8080", uc.port);
  15870. }
  15871. {
  15872. // Unix socket path — must not be parsed as host
  15873. detail::UrlComponents uc;
  15874. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15875. EXPECT_TRUE(uc.host.empty());
  15876. }
  15877. {
  15878. detail::UrlComponents uc;
  15879. ASSERT_TRUE(detail::parse_url("", uc));
  15880. EXPECT_TRUE(uc.host.empty());
  15881. EXPECT_TRUE(uc.path.empty());
  15882. }
  15883. {
  15884. detail::UrlComponents uc;
  15885. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15886. }
  15887. {
  15888. detail::UrlComponents uc;
  15889. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15890. }
  15891. {
  15892. // Accepted by parse_url; callers restrict to http/https
  15893. detail::UrlComponents uc;
  15894. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15895. EXPECT_EQ("ftp", uc.scheme);
  15896. }
  15897. {
  15898. detail::UrlComponents uc;
  15899. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15900. }
  15901. {
  15902. detail::UrlComponents uc;
  15903. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15904. }
  15905. }
  15906. TEST(ParseUrlTest, FragmentHandling) {
  15907. {
  15908. detail::UrlComponents uc;
  15909. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15910. EXPECT_EQ("/path", uc.path);
  15911. EXPECT_TRUE(uc.query.empty());
  15912. }
  15913. {
  15914. detail::UrlComponents uc;
  15915. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15916. EXPECT_TRUE(uc.path.empty());
  15917. EXPECT_TRUE(uc.query.empty());
  15918. }
  15919. }
  15920. TEST(ParseUrlTest, UserinfoHandling) {
  15921. // Userinfo with @ but no colon — host includes @
  15922. detail::UrlComponents uc;
  15923. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15924. EXPECT_EQ("user@host.com", uc.host);
  15925. EXPECT_EQ("/path", uc.path);
  15926. }
  15927. TEST(ParseUrlTest, IPv6EdgeCases) {
  15928. {
  15929. detail::UrlComponents uc;
  15930. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15931. EXPECT_TRUE(uc.scheme.empty());
  15932. EXPECT_EQ("::1", uc.host);
  15933. EXPECT_EQ("8080", uc.port);
  15934. }
  15935. {
  15936. // Zone ID '%25' is not in [a-fA-F0-9:]
  15937. detail::UrlComponents uc;
  15938. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15939. }
  15940. }
  15941. TEST(ParseUrlTest, SchemeEdgeCases) {
  15942. {
  15943. detail::UrlComponents uc;
  15944. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15945. }
  15946. {
  15947. detail::UrlComponents uc;
  15948. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15949. }
  15950. {
  15951. detail::UrlComponents uc;
  15952. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15953. }
  15954. }
  15955. TEST(ParseUrlTest, PortEdgeCases) {
  15956. {
  15957. detail::UrlComponents uc;
  15958. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15959. EXPECT_TRUE(uc.port.empty());
  15960. EXPECT_EQ("/path", uc.path);
  15961. }
  15962. {
  15963. // parse_url accepts any port string; validation is done by parse_port
  15964. detail::UrlComponents uc;
  15965. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15966. EXPECT_EQ("abc", uc.port);
  15967. }
  15968. }
  15969. TEST(ParseUrlTest, WebSocketPatterns) {
  15970. {
  15971. detail::UrlComponents uc;
  15972. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15973. EXPECT_EQ("ws", uc.scheme);
  15974. EXPECT_EQ("echo.example.com", uc.host);
  15975. EXPECT_EQ("8080", uc.port);
  15976. EXPECT_EQ("/ws", uc.path);
  15977. }
  15978. {
  15979. detail::UrlComponents uc;
  15980. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15981. EXPECT_EQ("wss", uc.scheme);
  15982. EXPECT_EQ("echo.example.com", uc.host);
  15983. EXPECT_TRUE(uc.port.empty());
  15984. EXPECT_EQ("/ws", uc.path);
  15985. }
  15986. }
  15987. TEST(ParseUrlTest, QueryOnly) {
  15988. detail::UrlComponents uc;
  15989. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15990. EXPECT_TRUE(uc.host.empty());
  15991. EXPECT_TRUE(uc.path.empty());
  15992. EXPECT_EQ("?q=1&r=2", uc.query);
  15993. }
  15994. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15995. detail::UrlComponents uc;
  15996. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15997. EXPECT_TRUE(uc.scheme.empty());
  15998. EXPECT_EQ("example.com", uc.host);
  15999. EXPECT_EQ("443", uc.port);
  16000. EXPECT_EQ("/path", uc.path);
  16001. }
  16002. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16003. // If ipv6 regex working, regex match codepath is taken.
  16004. // else port will default to 80 in Client impl
  16005. int clientImplMagicPort = 80;
  16006. int port = 4321;
  16007. // above ports must be different to avoid false negative
  16008. EXPECT_NE(clientImplMagicPort, port);
  16009. std::string ipV6TestURL = "http://[ff06::c3]";
  16010. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16011. CLIENT_PRIVATE_KEY_FILE);
  16012. EXPECT_EQ(cli.port(), port);
  16013. }
  16014. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16015. auto file_path = "./www/dir/index.html";
  16016. auto dir_path = "./www/dir";
  16017. detail::FileStat stat_file(file_path);
  16018. EXPECT_TRUE(stat_file.is_file());
  16019. EXPECT_FALSE(stat_file.is_dir());
  16020. detail::FileStat stat_dir(dir_path);
  16021. EXPECT_FALSE(stat_dir.is_file());
  16022. EXPECT_TRUE(stat_dir.is_dir());
  16023. }
  16024. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16025. // IPv4 with default HTTP port (80)
  16026. EXPECT_EQ("example.com",
  16027. detail::make_host_and_port_string("example.com", 80, false));
  16028. // IPv4 with default HTTPS port (443)
  16029. EXPECT_EQ("example.com",
  16030. detail::make_host_and_port_string("example.com", 443, true));
  16031. // IPv4 with non-default HTTP port
  16032. EXPECT_EQ("example.com:8080",
  16033. detail::make_host_and_port_string("example.com", 8080, false));
  16034. // IPv4 with non-default HTTPS port
  16035. EXPECT_EQ("example.com:8443",
  16036. detail::make_host_and_port_string("example.com", 8443, true));
  16037. // IPv6 with default HTTP port (80)
  16038. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16039. // IPv6 with default HTTPS port (443)
  16040. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16041. // IPv6 with non-default HTTP port
  16042. EXPECT_EQ("[::1]:8080",
  16043. detail::make_host_and_port_string("::1", 8080, false));
  16044. // IPv6 with non-default HTTPS port
  16045. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16046. // IPv6 full address with default port
  16047. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16048. detail::make_host_and_port_string(
  16049. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16050. // IPv6 full address with non-default port
  16051. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16052. detail::make_host_and_port_string(
  16053. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16054. // IPv6 localhost with non-default port
  16055. EXPECT_EQ("[::1]:3000",
  16056. detail::make_host_and_port_string("::1", 3000, false));
  16057. // IPv6 with zone ID (link-local address) with default port
  16058. EXPECT_EQ("[fe80::1%eth0]",
  16059. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16060. // IPv6 with zone ID (link-local address) with non-default port
  16061. EXPECT_EQ("[fe80::1%eth0]:8080",
  16062. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16063. // Edge case: Port 443 with is_ssl=false (should add port)
  16064. EXPECT_EQ("example.com:443",
  16065. detail::make_host_and_port_string("example.com", 443, false));
  16066. // Edge case: Port 80 with is_ssl=true (should add port)
  16067. EXPECT_EQ("example.com:80",
  16068. detail::make_host_and_port_string("example.com", 80, true));
  16069. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16070. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16071. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16072. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16073. // Security fix: Already bracketed IPv6 should not get double brackets
  16074. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16075. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16076. EXPECT_EQ("[::1]:8080",
  16077. detail::make_host_and_port_string("[::1]", 8080, false));
  16078. EXPECT_EQ("[2001:db8::1]:8080",
  16079. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16080. EXPECT_EQ("[fe80::1%eth0]",
  16081. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16082. EXPECT_EQ("[fe80::1%eth0]:8080",
  16083. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16084. // Edge case: Empty host (should return as-is)
  16085. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16086. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16087. // This is a known limitation but shouldn't crash
  16088. EXPECT_EQ("[host:name]",
  16089. detail::make_host_and_port_string("host:name", 80, false));
  16090. // Port number edge cases (no validation, but should not crash)
  16091. EXPECT_EQ("example.com:0",
  16092. detail::make_host_and_port_string("example.com", 0, false));
  16093. EXPECT_EQ("example.com:-1",
  16094. detail::make_host_and_port_string("example.com", -1, false));
  16095. EXPECT_EQ("example.com:65535",
  16096. detail::make_host_and_port_string("example.com", 65535, false));
  16097. EXPECT_EQ("example.com:65536",
  16098. detail::make_host_and_port_string("example.com", 65536, false));
  16099. }
  16100. #ifdef CPPHTTPLIB_SSL_ENABLED
  16101. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16102. httplib::SSLClient cli("roblox.com", 443);
  16103. cli.set_follow_location(true);
  16104. auto res = cli.Get("/");
  16105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16106. EXPECT_EQ(StatusCode::OK_200, res->status);
  16107. }
  16108. #endif
  16109. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16110. Server svr;
  16111. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16112. EXPECT_EQ(res.status, 400);
  16113. });
  16114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16115. auto se = detail::scope_exit([&] {
  16116. svr.stop();
  16117. thread.join();
  16118. ASSERT_FALSE(svr.is_running());
  16119. });
  16120. svr.wait_until_ready();
  16121. Client cli(HOST, PORT);
  16122. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16123. }
  16124. TEST(InvalidHeaderCharsTest, is_field_name) {
  16125. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16126. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16127. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16128. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16129. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16130. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16131. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16132. EXPECT_FALSE(detail::fields::is_field_name(""));
  16133. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16134. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16135. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16136. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16137. }
  16138. TEST(InvalidHeaderCharsTest, is_field_value) {
  16139. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16140. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16141. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16142. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16143. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16144. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16145. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16146. EXPECT_TRUE(detail::fields::is_field_value(""));
  16147. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16148. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16149. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16150. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16151. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16152. }
  16153. TEST(InvalidHeaderCharsTest, OnServer) {
  16154. Server svr;
  16155. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16156. std::string header = "Not Set";
  16157. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16158. res.set_header(header, "value");
  16159. res.set_content("Page Content Page Content", "text/plain");
  16160. });
  16161. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16162. std::string header = "Not Set";
  16163. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16164. res.set_header("X-Test", header);
  16165. res.set_content("Page Content Page Content", "text/plain");
  16166. });
  16167. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16168. auto se = detail::scope_exit([&] {
  16169. svr.stop();
  16170. thread.join();
  16171. ASSERT_FALSE(svr.is_running());
  16172. });
  16173. svr.wait_until_ready();
  16174. Client cli(HOST, PORT);
  16175. {
  16176. auto res = cli.Get(
  16177. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16179. EXPECT_EQ("Page Content Page Content", res->body);
  16180. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16181. }
  16182. {
  16183. auto res = cli.Get(
  16184. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16186. EXPECT_EQ("Page Content Page Content", res->body);
  16187. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16188. }
  16189. }
  16190. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16191. auto handled = false;
  16192. Server svr;
  16193. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16194. thread t = thread([&] { svr.listen(HOST, PORT); });
  16195. auto se = detail::scope_exit([&] {
  16196. svr.stop();
  16197. t.join();
  16198. ASSERT_FALSE(svr.is_running());
  16199. ASSERT_FALSE(handled);
  16200. });
  16201. svr.wait_until_ready();
  16202. auto req = "POST /test HTTP/1.1\r\n"
  16203. "Content-Length: x\r\n"
  16204. "\r\n";
  16205. std::string response;
  16206. ASSERT_TRUE(send_request(1, req, &response));
  16207. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16208. response.substr(0, response.find("\r\n")));
  16209. }
  16210. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16211. // case-insensitive, and a server that receives a 100-continue expectation in
  16212. // an HTTP/1.0 request MUST ignore it.
  16213. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16214. std::string response;
  16215. ASSERT_TRUE(send_request(1, req, &response, port));
  16216. *got_100 = response.find("100 Continue") != std::string::npos;
  16217. }
  16218. class ExpectTokenTest : public ::testing::Test {
  16219. protected:
  16220. void SetUp() override {
  16221. svr_.Post("/p", [](const Request &, Response &res) {
  16222. res.set_content("ok", "text/plain");
  16223. });
  16224. port_ = svr_.bind_to_any_port(HOST);
  16225. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16226. svr_.wait_until_ready();
  16227. }
  16228. void TearDown() override {
  16229. svr_.stop();
  16230. if (thread_.joinable()) { thread_.join(); }
  16231. }
  16232. std::string request(const char *version, const char *expect_value) const {
  16233. return std::string("POST /p ") + version +
  16234. "\r\n"
  16235. "Host: localhost\r\n"
  16236. "Content-Length: 2\r\n"
  16237. "Connection: close\r\n"
  16238. "Expect: " +
  16239. expect_value +
  16240. "\r\n"
  16241. "\r\n"
  16242. "hi";
  16243. }
  16244. Server svr_;
  16245. int port_ = 0;
  16246. thread thread_;
  16247. };
  16248. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16249. bool got_100 = false;
  16250. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16251. EXPECT_TRUE(got_100);
  16252. }
  16253. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16254. bool got_100 = true;
  16255. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16256. EXPECT_FALSE(got_100);
  16257. }
  16258. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16259. bool got_100 = false;
  16260. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16261. EXPECT_TRUE(got_100);
  16262. }
  16263. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16264. bool got_100 = false;
  16265. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16266. EXPECT_TRUE(got_100);
  16267. }
  16268. // `100 Continue` is sent only when the server starts reading the body, so a
  16269. // request rejected before that never invites the client to send it. The
  16270. // requests below carry the expectation but withhold the body, as a client
  16271. // waiting for `100 Continue` would.
  16272. // A POST that expects `100 Continue` and withholds its two-byte body.
  16273. static std::string expect_headers_only(const std::string &path) {
  16274. return "POST " + path +
  16275. " HTTP/1.1\r\n"
  16276. "Host: localhost\r\n"
  16277. "Content-Length: 2\r\n"
  16278. "Expect: 100-continue\r\n"
  16279. "\r\n";
  16280. }
  16281. class ExpectLazyContinueTest : public ::testing::Test {
  16282. protected:
  16283. void SetUp() override {
  16284. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16285. if (req.path == "/pre-routing") {
  16286. res.status = StatusCode::Unauthorized_401;
  16287. return Server::HandlerResponse::Handled;
  16288. }
  16289. return Server::HandlerResponse::Unhandled;
  16290. });
  16291. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16292. if (req.matched_route == "/pre-request") {
  16293. res.status = StatusCode::Forbidden_403;
  16294. return Server::HandlerResponse::Handled;
  16295. }
  16296. return Server::HandlerResponse::Unhandled;
  16297. });
  16298. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16299. res.set_content("ok", "text/plain");
  16300. });
  16301. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16302. res.set_content("ok", "text/plain");
  16303. });
  16304. svr_.Post("/reader-used", [](const Request &, Response &res,
  16305. const ContentReader &content_reader) {
  16306. std::string body;
  16307. content_reader([&](const char *data, size_t len) {
  16308. body.append(data, len);
  16309. return true;
  16310. });
  16311. res.set_content(body, "text/plain");
  16312. });
  16313. svr_.Post("/reader-unused",
  16314. [](const Request &, Response &res, const ContentReader &) {
  16315. res.set_content("ignored", "text/plain");
  16316. });
  16317. port_ = svr_.bind_to_any_port(HOST);
  16318. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16319. svr_.wait_until_ready();
  16320. }
  16321. void TearDown() override {
  16322. svr_.stop();
  16323. if (thread_.joinable()) { thread_.join(); }
  16324. }
  16325. // Sends `req` and reads until the server closes the connection. Returns
  16326. // false if the read had to wait for the client-side timeout instead.
  16327. bool send_until_closed(const std::string &req, std::string *resp) const {
  16328. auto start = std::chrono::steady_clock::now();
  16329. if (!send_request(3, req, resp, port_)) { return false; }
  16330. auto elapsed = std::chrono::steady_clock::now() - start;
  16331. return elapsed < std::chrono::seconds(2);
  16332. }
  16333. // The final response comes without `100 Continue`, and the server closes
  16334. // the connection since the body may or may not follow.
  16335. void expect_final_without_interim(const std::string &path,
  16336. const char *status_line) const {
  16337. std::string resp;
  16338. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16339. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16340. EXPECT_EQ(0u, resp.find(status_line));
  16341. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16342. }
  16343. Server svr_;
  16344. int port_ = 0;
  16345. thread thread_;
  16346. };
  16347. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16348. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16349. }
  16350. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16351. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16352. }
  16353. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16354. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16355. }
  16356. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16357. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16358. }
  16359. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16360. // The body follows once `100 Continue` has had time to arrive.
  16361. auto req = expect_headers_only("/reader-used");
  16362. req.insert(req.size() - 2, "Connection: close\r\n");
  16363. std::string resp;
  16364. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16365. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16366. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16367. EXPECT_NE(std::string::npos, resp.find("hi"));
  16368. }
  16369. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16370. // Large enough for the client to add `Expect: 100-continue` itself.
  16371. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16372. std::atomic<bool> body_sent{false};
  16373. Client cli(HOST, port_);
  16374. auto res = cli.Post(
  16375. "/pre-request", length,
  16376. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16377. body_sent = true;
  16378. std::string chunk(len, 'x');
  16379. sink.write(chunk.data(), chunk.size());
  16380. return true;
  16381. },
  16382. "application/octet-stream");
  16383. ASSERT_TRUE(res);
  16384. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16385. EXPECT_FALSE(body_sent);
  16386. }
  16387. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16388. Server svr;
  16389. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16390. return StatusCode::ExpectationFailed_417;
  16391. });
  16392. svr.Post("/p", [](const Request &, Response &res) {
  16393. res.set_content("ok", "text/plain");
  16394. });
  16395. auto port = svr.bind_to_any_port(HOST);
  16396. thread t = thread([&] { svr.listen_after_bind(); });
  16397. auto se = detail::scope_exit([&] {
  16398. svr.stop();
  16399. t.join();
  16400. });
  16401. svr.wait_until_ready();
  16402. std::string resp;
  16403. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16404. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16405. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16406. // Exactly one response: the route handler must not run after the 417.
  16407. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16408. }
  16409. #ifndef _WIN32
  16410. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16411. static constexpr char reject[] = "Unauthorized";
  16412. static constexpr char accept[] = "Upload accepted";
  16413. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16414. Server svr;
  16415. svr.set_expect_100_continue_handler(
  16416. [](const Request & /*req*/, Response &res) {
  16417. res.status = StatusCode::Unauthorized_401;
  16418. res.set_content(reject, "text/plain");
  16419. return res.status;
  16420. });
  16421. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16422. res.set_content(accept, "text/plain");
  16423. });
  16424. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16425. auto se = detail::scope_exit([&] {
  16426. svr.stop();
  16427. thread.join();
  16428. ASSERT_FALSE(svr.is_running());
  16429. });
  16430. svr.wait_until_ready();
  16431. {
  16432. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16433. curl_easy_init(), &curl_easy_cleanup};
  16434. ASSERT_NE(curl, nullptr);
  16435. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16436. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16437. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16438. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16439. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16440. &curl_slist_free_all};
  16441. ASSERT_NE(list, nullptr);
  16442. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16443. struct read_data {
  16444. size_t read_size;
  16445. size_t total_size;
  16446. } data = {0, total_size};
  16447. using read_callback_t =
  16448. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16449. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16450. void *userdata) -> size_t {
  16451. read_data *d = (read_data *)userdata;
  16452. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16453. std::fill_n(ptr, size * nmemb, 'A');
  16454. d->read_size += size * nmemb;
  16455. return size * nmemb;
  16456. };
  16457. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16458. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16459. std::vector<char> buffer;
  16460. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16461. using write_callback_t =
  16462. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16463. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16464. void *userdata) -> size_t {
  16465. std::vector<char> *buf = (std::vector<char> *)userdata;
  16466. buf->reserve(buf->size() + size * nmemb + 1);
  16467. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16468. return size * nmemb;
  16469. };
  16470. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16471. {
  16472. const auto res = curl_easy_perform(curl.get());
  16473. ASSERT_EQ(res, CURLE_OK);
  16474. }
  16475. {
  16476. auto response_code = long{};
  16477. const auto res =
  16478. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16479. ASSERT_EQ(res, CURLE_OK);
  16480. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16481. }
  16482. {
  16483. auto dl = curl_off_t{};
  16484. const auto res =
  16485. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16486. ASSERT_EQ(res, CURLE_OK);
  16487. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16488. }
  16489. {
  16490. buffer.push_back('\0');
  16491. ASSERT_STRCASEEQ(buffer.data(), reject);
  16492. }
  16493. }
  16494. }
  16495. #endif
  16496. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16497. // Regression test for #2458.
  16498. //
  16499. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16500. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16501. // ticket can make the client socket spuriously readable during the
  16502. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16503. // the client withholds the body and then blocks reading a response that never
  16504. // comes, failing with `Failed to read connection`.
  16505. //
  16506. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16507. // within the timeout. This raw OpenSSL server deliberately never sends
  16508. // `100 Continue`; the client must still deliver the body and receive 200.
  16509. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16510. signal(SIGPIPE, SIG_IGN);
  16511. const auto port = PORT + 4;
  16512. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16513. ASSERT_NE(srv, INVALID_SOCKET);
  16514. int opt = 1;
  16515. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16516. sockaddr_in addr{};
  16517. addr.sin_family = AF_INET;
  16518. addr.sin_port = htons(static_cast<uint16_t>(port));
  16519. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16520. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16521. ASSERT_EQ(0, ::listen(srv, 1));
  16522. std::atomic<size_t> server_body_bytes{0};
  16523. auto server_thread = std::thread([&] {
  16524. sockaddr_in cli_addr{};
  16525. socklen_t cli_len = sizeof(cli_addr);
  16526. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16527. if (cli == INVALID_SOCKET) { return; }
  16528. // Bound the lifetime of the server side so a buggy client (which never
  16529. // sends the body) cannot make this thread block forever on join.
  16530. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16531. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16532. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16533. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16534. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16535. SSL *ssl = SSL_new(ctx);
  16536. SSL_set_fd(ssl, static_cast<int>(cli));
  16537. if (SSL_accept(ssl) > 0) {
  16538. // Read the request headers. Reading here also flushes the TLS 1.3
  16539. // session tickets to the client. Deliberately do NOT send
  16540. // `100 Continue`.
  16541. std::string buf;
  16542. char tmp[1024];
  16543. while (buf.find("\r\n\r\n") == std::string::npos) {
  16544. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16545. if (n <= 0) { break; }
  16546. buf.append(tmp, static_cast<size_t>(n));
  16547. }
  16548. // A correct client sends the body now; count what arrives.
  16549. auto pos = buf.find("\r\n\r\n");
  16550. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16551. while (body < 4096) {
  16552. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16553. if (n <= 0) { break; }
  16554. body += static_cast<size_t>(n);
  16555. }
  16556. server_body_bytes = body;
  16557. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16558. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16559. SSL_shutdown(ssl);
  16560. }
  16561. SSL_free(ssl);
  16562. detail::close_socket(cli);
  16563. SSL_CTX_free(ctx);
  16564. });
  16565. auto se = detail::scope_exit([&] {
  16566. server_thread.join();
  16567. detail::close_socket(srv);
  16568. });
  16569. SSLClient cli("127.0.0.1", port);
  16570. cli.enable_server_certificate_verification(false);
  16571. cli.set_connection_timeout(5, 0);
  16572. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16573. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16574. std::string body(4096, 'A');
  16575. auto res = cli.Put("/api/test", body, "application/json");
  16576. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16577. EXPECT_EQ(StatusCode::OK_200, res->status);
  16578. EXPECT_EQ(body.size(), server_body_bytes.load());
  16579. }
  16580. #endif
  16581. template <typename S, typename C>
  16582. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16583. svr.Get("/stream", [&](const Request &, Response &res) {
  16584. auto data = new std::string("01234567890123456789");
  16585. res.set_content_provider(
  16586. data->size(), "text/plain",
  16587. [&, data](size_t offset, size_t length, DataSink &sink) {
  16588. const size_t DATA_CHUNK_SIZE = 4;
  16589. const auto &d = *data;
  16590. std::this_thread::sleep_for(std::chrono::seconds(1));
  16591. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16592. return true;
  16593. },
  16594. [data](bool success) {
  16595. EXPECT_FALSE(success);
  16596. delete data;
  16597. });
  16598. });
  16599. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16600. auto i = new size_t(0);
  16601. res.set_content_provider(
  16602. "text/plain",
  16603. [i](size_t, DataSink &sink) {
  16604. if (*i < 5) {
  16605. std::this_thread::sleep_for(std::chrono::seconds(1));
  16606. sink.write("abcd", 4);
  16607. (*i)++;
  16608. } else {
  16609. sink.done();
  16610. }
  16611. return true;
  16612. },
  16613. [i](bool success) {
  16614. EXPECT_FALSE(success);
  16615. delete i;
  16616. });
  16617. });
  16618. svr.Get("/chunked", [&](const Request &, Response &res) {
  16619. auto i = new size_t(0);
  16620. res.set_chunked_content_provider(
  16621. "text/plain",
  16622. [i](size_t, DataSink &sink) {
  16623. if (*i < 5) {
  16624. std::this_thread::sleep_for(std::chrono::seconds(1));
  16625. sink.os << "abcd";
  16626. (*i)++;
  16627. } else {
  16628. sink.done();
  16629. }
  16630. return true;
  16631. },
  16632. [i](bool success) {
  16633. EXPECT_FALSE(success);
  16634. delete i;
  16635. });
  16636. });
  16637. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16638. auto se = detail::scope_exit([&] {
  16639. svr.stop();
  16640. listen_thread.join();
  16641. ASSERT_FALSE(svr.is_running());
  16642. });
  16643. svr.wait_until_ready();
  16644. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16645. {
  16646. auto start = std::chrono::steady_clock::now();
  16647. auto res = cli.Get("/stream");
  16648. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16649. std::chrono::steady_clock::now() - start)
  16650. .count();
  16651. ASSERT_FALSE(res);
  16652. EXPECT_EQ(Error::Read, res.error());
  16653. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16654. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16655. }
  16656. {
  16657. auto start = std::chrono::steady_clock::now();
  16658. auto res = cli.Get("/stream_without_length");
  16659. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16660. std::chrono::steady_clock::now() - start)
  16661. .count();
  16662. ASSERT_FALSE(res);
  16663. EXPECT_EQ(Error::Read, res.error());
  16664. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16665. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16666. }
  16667. {
  16668. auto start = std::chrono::steady_clock::now();
  16669. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16670. EXPECT_EQ("abcd", string(data, data_length));
  16671. return true;
  16672. });
  16673. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16674. std::chrono::steady_clock::now() - start)
  16675. .count();
  16676. ASSERT_FALSE(res);
  16677. EXPECT_EQ(Error::Read, res.error());
  16678. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16679. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16680. }
  16681. }
  16682. TEST(MaxTimeoutTest, ContentStream) {
  16683. time_t timeout = 2000;
  16684. time_t threshold = 200;
  16685. Server svr;
  16686. Client cli("localhost", PORT);
  16687. max_timeout_test(svr, cli, timeout, threshold);
  16688. }
  16689. #ifdef CPPHTTPLIB_SSL_ENABLED
  16690. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16691. time_t timeout = 2000;
  16692. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16694. SSLClient cli("localhost", PORT);
  16695. cli.enable_server_certificate_verification(false);
  16696. max_timeout_test(svr, cli, timeout, threshold);
  16697. }
  16698. #endif
  16699. class EventDispatcher {
  16700. public:
  16701. EventDispatcher() {}
  16702. bool wait_event(DataSink *sink) {
  16703. unique_lock<mutex> lk(m_);
  16704. int id = id_;
  16705. // Wait with timeout to prevent hanging if client disconnects
  16706. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16707. [&] { return cid_ == id; })) {
  16708. return false; // Timeout occurred
  16709. }
  16710. sink->write(message_.data(), message_.size());
  16711. return true;
  16712. }
  16713. void send_event(const string &message) {
  16714. lock_guard<mutex> lk(m_);
  16715. cid_ = id_++;
  16716. message_ = message;
  16717. cv_.notify_all();
  16718. }
  16719. private:
  16720. mutex m_;
  16721. condition_variable cv_;
  16722. atomic_int id_{0};
  16723. atomic_int cid_{-1};
  16724. string message_;
  16725. };
  16726. TEST(ClientInThreadTest, Issue2068) {
  16727. EventDispatcher ed;
  16728. Server svr;
  16729. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16730. res.set_chunked_content_provider("text/event-stream",
  16731. [&](size_t /*offset*/, DataSink &sink) {
  16732. return ed.wait_event(&sink);
  16733. });
  16734. });
  16735. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16736. svr.wait_until_ready();
  16737. thread event_thread([&] {
  16738. int id = 0;
  16739. while (svr.is_running()) {
  16740. this_thread::sleep_for(chrono::milliseconds(500));
  16741. std::stringstream ss;
  16742. ss << "data: " << id << "\n\n";
  16743. ed.send_event(ss.str());
  16744. id++;
  16745. }
  16746. });
  16747. auto se = detail::scope_exit([&] {
  16748. svr.stop();
  16749. listen_thread.join();
  16750. event_thread.join();
  16751. ASSERT_FALSE(svr.is_running());
  16752. });
  16753. {
  16754. auto client = detail::make_unique<Client>(HOST, PORT);
  16755. client->set_read_timeout(std::chrono::minutes(10));
  16756. std::atomic<bool> stop{false};
  16757. std::thread t([&] {
  16758. client->Get("/event1",
  16759. [&](const char *, size_t) -> bool { return !stop; });
  16760. });
  16761. std::this_thread::sleep_for(std::chrono::seconds(2));
  16762. stop = true;
  16763. client->stop();
  16764. t.join();
  16765. // Reset client after thread has finished
  16766. client.reset();
  16767. }
  16768. }
  16769. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16770. auto handled = false;
  16771. Server svr;
  16772. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16773. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16774. auto se = detail::scope_exit([&] {
  16775. svr.stop();
  16776. t.join();
  16777. ASSERT_FALSE(svr.is_running());
  16778. ASSERT_FALSE(handled);
  16779. });
  16780. svr.wait_until_ready();
  16781. // Two Content-Length headers with different values — must be rejected
  16782. auto req = "POST /test HTTP/1.1\r\n"
  16783. "Content-Length: 5\r\n"
  16784. "Content-Length: 10\r\n"
  16785. "\r\n"
  16786. "hello";
  16787. std::string response;
  16788. ASSERT_TRUE(send_request(1, req, &response));
  16789. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16790. response.substr(0, response.find("\r\n")));
  16791. }
  16792. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16793. auto handled = false;
  16794. Server svr;
  16795. svr.Post("/test", [&](const Request &, Response &res) {
  16796. handled = true;
  16797. res.set_content("ok", "text/plain");
  16798. });
  16799. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16800. auto se = detail::scope_exit([&] {
  16801. svr.stop();
  16802. t.join();
  16803. ASSERT_FALSE(svr.is_running());
  16804. ASSERT_TRUE(handled);
  16805. });
  16806. svr.wait_until_ready();
  16807. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16808. auto req = "POST /test HTTP/1.1\r\n"
  16809. "Content-Length: 5\r\n"
  16810. "Content-Length: 5\r\n"
  16811. "\r\n"
  16812. "hello";
  16813. std::string response;
  16814. ASSERT_TRUE(send_request(1, req, &response));
  16815. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16816. }
  16817. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16818. Server svr;
  16819. svr.Get("/test", [](const Request &, Response &res) {
  16820. res.set_content("ok", "text/plain");
  16821. });
  16822. auto port = svr.bind_to_any_port(HOST);
  16823. thread t = thread([&] { svr.listen_after_bind(); });
  16824. auto se = detail::scope_exit([&] {
  16825. svr.stop();
  16826. t.join();
  16827. ASSERT_FALSE(svr.is_running());
  16828. });
  16829. svr.wait_until_ready();
  16830. auto status_line = [&](const std::string &host_lines) {
  16831. std::string res;
  16832. send_request(
  16833. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16834. &res, port);
  16835. return res.substr(0, res.find("\r\n"));
  16836. };
  16837. const char *accepted[] = {
  16838. "Host: localhost\r\n",
  16839. "Host: a.example:8080\r\n",
  16840. "Host: my_service\r\n",
  16841. "Host: [::1]:8080\r\n",
  16842. "Host: [fe80::1%25eth0]\r\n",
  16843. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16844. };
  16845. for (auto host_lines : accepted) {
  16846. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16847. }
  16848. const char *rejected[] = {
  16849. "Host: a.example\r\nHost: b.example\r\n",
  16850. "Host: a.example\r\nHost: a.example\r\n",
  16851. "Host: a@b.example\r\n",
  16852. "Host: a.example/b\r\n",
  16853. "Host: a.example\\b\r\n",
  16854. "Host: a.example?b\r\n",
  16855. "Host: a.example#b\r\n",
  16856. "Host: a.example b.example\r\n",
  16857. };
  16858. for (auto host_lines : rejected) {
  16859. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16860. << host_lines;
  16861. }
  16862. }
  16863. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16864. Server svr;
  16865. svr.Get("/", [](const Request &req, Response &res) {
  16866. EXPECT_EQ(2U, req.trailers.size());
  16867. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16868. // Denied
  16869. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16870. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16871. // Accepted
  16872. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16873. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16874. EXPECT_TRUE(req.has_trailer("X-World"));
  16875. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16876. res.set_content("ok", "text/plain");
  16877. });
  16878. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16879. auto se = detail::scope_exit([&] {
  16880. svr.stop();
  16881. t.join();
  16882. ASSERT_FALSE(svr.is_running());
  16883. });
  16884. svr.wait_until_ready();
  16885. const std::string req = "GET / HTTP/1.1\r\n"
  16886. "Transfer-Encoding: chunked\r\n"
  16887. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16888. "\r\n"
  16889. "0\r\n"
  16890. "Content-Length: 10\r\n"
  16891. "Host: internal.local\r\n"
  16892. "Content-Type: malicious/content\r\n"
  16893. "Cookie: any\r\n"
  16894. "Set-Cookie: any\r\n"
  16895. "X-Forwarded-For: attacker.com\r\n"
  16896. "X-Real-Ip: 1.1.1.1\r\n"
  16897. "X-Hello: hello\r\n"
  16898. "X-World: world\r\n"
  16899. "\r\n";
  16900. std::string res;
  16901. ASSERT_TRUE(send_request(1, req, &res));
  16902. }
  16903. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16904. // several field lines, and the combined value is what has to be parsed. A
  16905. // Trailer field split across lines therefore declares every name it lists;
  16906. // reading only the first line silently drops the trailers the later lines
  16907. // declare. The prohibited-trailer filter still applies to every line.
  16908. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16909. Server svr;
  16910. size_t observed_trailer_count = 0;
  16911. std::string observed_hello;
  16912. std::string observed_world;
  16913. bool observed_content_length = true;
  16914. svr.Get("/", [&](const Request &req, Response &res) {
  16915. observed_trailer_count = req.trailers.size();
  16916. observed_hello = req.get_trailer_value("X-Hello");
  16917. observed_world = req.get_trailer_value("X-World");
  16918. observed_content_length = req.has_trailer("Content-Length");
  16919. res.set_content("ok", "text/plain");
  16920. });
  16921. auto port = svr.bind_to_any_port(HOST);
  16922. thread t = thread([&]() { svr.listen_after_bind(); });
  16923. auto se = detail::scope_exit([&] {
  16924. svr.stop();
  16925. t.join();
  16926. ASSERT_FALSE(svr.is_running());
  16927. });
  16928. svr.wait_until_ready();
  16929. const std::string req = "GET / HTTP/1.1\r\n"
  16930. "Transfer-Encoding: chunked\r\n"
  16931. "Trailer: X-Hello\r\n"
  16932. "Trailer: X-World, Content-Length\r\n"
  16933. "\r\n"
  16934. "0\r\n"
  16935. "X-Hello: hello\r\n"
  16936. "X-World: world\r\n"
  16937. "Content-Length: 10\r\n"
  16938. "\r\n";
  16939. std::string res;
  16940. ASSERT_TRUE(send_request(1, req, &res, port));
  16941. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16942. // Accepted: both field lines contribute to the declared set
  16943. EXPECT_EQ(2U, observed_trailer_count);
  16944. EXPECT_EQ(observed_hello, "hello");
  16945. EXPECT_EQ(observed_world, "world");
  16946. // Denied: a prohibited name stays prohibited on a later field line
  16947. EXPECT_FALSE(observed_content_length);
  16948. }
  16949. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16950. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16951. // unbounded run of fields that are never declared, because the counter would
  16952. // only advance for declared fields.
  16953. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16954. Server svr;
  16955. bool handler_called = false;
  16956. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16957. handler_called = true;
  16958. res.set_content("ok", "text/plain");
  16959. });
  16960. auto port = svr.bind_to_any_port(HOST);
  16961. thread t = thread([&]() { svr.listen_after_bind(); });
  16962. auto se = detail::scope_exit([&] {
  16963. svr.stop();
  16964. t.join();
  16965. ASSERT_FALSE(svr.is_running());
  16966. });
  16967. svr.wait_until_ready();
  16968. // Declare nothing, then send far more undeclared trailer fields than the
  16969. // header-count limit. Parsing must stop and reject the request rather than
  16970. // read every line.
  16971. std::string req = "GET / HTTP/1.1\r\n"
  16972. "Transfer-Encoding: chunked\r\n"
  16973. "\r\n"
  16974. "0\r\n";
  16975. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16976. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16977. }
  16978. req += "\r\n";
  16979. std::string res;
  16980. ASSERT_TRUE(send_request(1, req, &res, port));
  16981. // The request is rejected before the handler runs.
  16982. EXPECT_FALSE(handler_called);
  16983. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16984. }
  16985. // The set of declared trailer names is capped so a peer cannot grow it without
  16986. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16987. // declared past the cap is not honored, even if the field is actually sent.
  16988. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16989. Server svr;
  16990. // One name inside the cap and one past it, so the test tracks the cap rather
  16991. // than a fixed count.
  16992. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16993. const std::string within_cap_name = "X-T-0";
  16994. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16995. bool observed_within_cap = false;
  16996. bool observed_past_cap = false;
  16997. svr.Get("/", [&](const Request &req, Response &res) {
  16998. observed_within_cap = req.has_trailer(within_cap_name);
  16999. observed_past_cap = req.has_trailer(past_cap_name);
  17000. res.set_content("ok", "text/plain");
  17001. });
  17002. auto port = svr.bind_to_any_port(HOST);
  17003. thread t = thread([&]() { svr.listen_after_bind(); });
  17004. auto se = detail::scope_exit([&] {
  17005. svr.stop();
  17006. t.join();
  17007. ASSERT_FALSE(svr.is_running());
  17008. });
  17009. svr.wait_until_ready();
  17010. // Declare more trailer names than the cap in a single Trailer field, then
  17011. // actually send the first (within the cap) and the last (past it).
  17012. std::string trailer_decl = "Trailer: ";
  17013. for (int i = 0; i < declared_count; i++) {
  17014. if (i != 0) { trailer_decl += ", "; }
  17015. trailer_decl += "X-T-" + std::to_string(i);
  17016. }
  17017. trailer_decl += "\r\n";
  17018. const std::string req = "GET / HTTP/1.1\r\n"
  17019. "Transfer-Encoding: chunked\r\n" +
  17020. trailer_decl +
  17021. "\r\n"
  17022. "0\r\n" +
  17023. within_cap_name + ": a\r\n" + past_cap_name +
  17024. ": b\r\n"
  17025. "\r\n";
  17026. std::string res;
  17027. ASSERT_TRUE(send_request(1, req, &res, port));
  17028. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17029. // A name within the cap is honored; one declared past the cap is dropped.
  17030. EXPECT_TRUE(observed_within_cap);
  17031. EXPECT_FALSE(observed_past_cap);
  17032. }
  17033. // A direct client that is not listed in trusted_proxies must not be able to
  17034. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17035. // the peer address on the actual TCP connection determines whether the
  17036. // header is honored.
  17037. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17038. Server svr;
  17039. // Deliberately does NOT include the loopback address the test client
  17040. // actually connects from, so the direct connection is not a trusted proxy.
  17041. svr.set_trusted_proxies({"203.0.113.66"});
  17042. std::string observed_remote_addr;
  17043. svr.Get("/ip", [&](const Request &req, Response &res) {
  17044. observed_remote_addr = req.remote_addr;
  17045. res.set_content("ok", "text/plain");
  17046. });
  17047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17048. auto se = detail::scope_exit([&] {
  17049. svr.stop();
  17050. t.join();
  17051. ASSERT_FALSE(svr.is_running());
  17052. });
  17053. svr.wait_until_ready();
  17054. Client cli(HOST, PORT);
  17055. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17057. EXPECT_EQ(StatusCode::OK_200, res->status);
  17058. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17059. // ignored entirely and the real connection-level address retained.
  17060. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17061. observed_remote_addr == "127.0.0.1");
  17062. }
  17063. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17064. Server svr;
  17065. std::string observed_remote_addr;
  17066. std::string observed_xff;
  17067. svr.Get("/ip", [&](const Request &req, Response &res) {
  17068. observed_remote_addr = req.remote_addr;
  17069. observed_xff = req.get_header_value("X-Forwarded-For");
  17070. res.set_content("ok", "text/plain");
  17071. });
  17072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17073. auto se = detail::scope_exit([&] {
  17074. svr.stop();
  17075. t.join();
  17076. ASSERT_FALSE(svr.is_running());
  17077. });
  17078. svr.wait_until_ready();
  17079. Client cli(HOST, PORT);
  17080. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17082. EXPECT_EQ(StatusCode::OK_200, res->status);
  17083. EXPECT_EQ(observed_xff, "203.0.113.66");
  17084. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17085. observed_remote_addr == "127.0.0.1");
  17086. }
  17087. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17088. Server svr;
  17089. svr.set_trusted_proxies({"203.0.113.66"});
  17090. std::string observed_remote_addr;
  17091. std::string observed_xff;
  17092. svr.Get("/ip", [&](const Request &req, Response &res) {
  17093. observed_remote_addr = req.remote_addr;
  17094. observed_xff = req.get_header_value("X-Forwarded-For");
  17095. res.set_content("ok", "text/plain");
  17096. });
  17097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17098. auto se = detail::scope_exit([&] {
  17099. svr.stop();
  17100. t.join();
  17101. ASSERT_FALSE(svr.is_running());
  17102. });
  17103. svr.wait_until_ready();
  17104. Client cli(HOST, PORT);
  17105. auto res = cli.Get("/ip");
  17106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17107. EXPECT_EQ(StatusCode::OK_200, res->status);
  17108. EXPECT_EQ(observed_xff, "");
  17109. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17110. observed_remote_addr == "127.0.0.1");
  17111. }
  17112. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17113. Server svr;
  17114. // Include the loopback address the test client actually connects from, so
  17115. // the direct connection itself is recognized as the trusted proxy hop.
  17116. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17117. std::string observed_remote_addr;
  17118. std::string observed_xff;
  17119. svr.Get("/ip", [&](const Request &req, Response &res) {
  17120. observed_remote_addr = req.remote_addr;
  17121. observed_xff = req.get_header_value("X-Forwarded-For");
  17122. res.set_content("ok", "text/plain");
  17123. });
  17124. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17125. auto se = detail::scope_exit([&] {
  17126. svr.stop();
  17127. t.join();
  17128. ASSERT_FALSE(svr.is_running());
  17129. });
  17130. svr.wait_until_ready();
  17131. Client cli(HOST, PORT);
  17132. auto res = cli.Get(
  17133. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17135. EXPECT_EQ(StatusCode::OK_200, res->status);
  17136. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17137. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17138. }
  17139. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17140. Server svr;
  17141. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17142. std::string observed_remote_addr;
  17143. std::string observed_xff;
  17144. svr.Get("/ip", [&](const Request &req, Response &res) {
  17145. observed_remote_addr = req.remote_addr;
  17146. observed_xff = req.get_header_value("X-Forwarded-For");
  17147. res.set_content("ok", "text/plain");
  17148. });
  17149. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17150. auto se = detail::scope_exit([&] {
  17151. svr.stop();
  17152. t.join();
  17153. ASSERT_FALSE(svr.is_running());
  17154. });
  17155. svr.wait_until_ready();
  17156. Client cli(HOST, PORT);
  17157. auto res = cli.Get(
  17158. "/ip",
  17159. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17161. EXPECT_EQ(StatusCode::OK_200, res->status);
  17162. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17163. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17164. }
  17165. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17166. Server svr;
  17167. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17168. std::string observed_remote_addr;
  17169. std::string observed_xff;
  17170. svr.Get("/ip", [&](const Request &req, Response &res) {
  17171. observed_remote_addr = req.remote_addr;
  17172. observed_xff = req.get_header_value("X-Forwarded-For");
  17173. res.set_content("ok", "text/plain");
  17174. });
  17175. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17176. auto se = detail::scope_exit([&] {
  17177. svr.stop();
  17178. t.join();
  17179. ASSERT_FALSE(svr.is_running());
  17180. });
  17181. svr.wait_until_ready();
  17182. Client cli(HOST, PORT);
  17183. auto res = cli.Get(
  17184. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17186. EXPECT_EQ(StatusCode::OK_200, res->status);
  17187. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17188. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17189. // and must not be selected.
  17190. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17191. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17192. }
  17193. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17194. Server svr;
  17195. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17196. std::string observed_remote_addr;
  17197. svr.Get("/ip", [&](const Request &req, Response &res) {
  17198. observed_remote_addr = req.remote_addr;
  17199. res.set_content("ok", "text/plain");
  17200. });
  17201. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17202. auto se = detail::scope_exit([&] {
  17203. svr.stop();
  17204. t.join();
  17205. ASSERT_FALSE(svr.is_running());
  17206. });
  17207. svr.wait_until_ready();
  17208. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17209. // a forged address and the trusted proxy's own address; the forged value must
  17210. // not win over the address the trusted proxy actually recorded.
  17211. Client cli(HOST, PORT);
  17212. auto res = cli.Get(
  17213. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17215. EXPECT_EQ(StatusCode::OK_200, res->status);
  17216. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17217. }
  17218. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17219. Server svr;
  17220. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17221. std::string observed_remote_addr;
  17222. std::string observed_xff;
  17223. svr.Get("/ip", [&](const Request &req, Response &res) {
  17224. observed_remote_addr = req.remote_addr;
  17225. observed_xff = req.get_header_value("X-Forwarded-For");
  17226. res.set_content("ok", "text/plain");
  17227. });
  17228. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17229. auto se = detail::scope_exit([&] {
  17230. svr.stop();
  17231. t.join();
  17232. ASSERT_FALSE(svr.is_running());
  17233. });
  17234. svr.wait_until_ready();
  17235. Client cli(HOST, PORT);
  17236. auto res = cli.Get(
  17237. "/ip",
  17238. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17240. EXPECT_EQ(StatusCode::OK_200, res->status);
  17241. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17242. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17243. }
  17244. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17245. Server svr;
  17246. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17247. std::string observed_remote_addr;
  17248. std::string observed_xff;
  17249. svr.Get("/ip", [&](const Request &req, Response &res) {
  17250. observed_remote_addr = req.remote_addr;
  17251. observed_xff = req.get_header_value("X-Forwarded-For");
  17252. res.set_content("ok", "text/plain");
  17253. });
  17254. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17255. auto se = detail::scope_exit([&] {
  17256. svr.stop();
  17257. t.join();
  17258. ASSERT_FALSE(svr.is_running());
  17259. });
  17260. svr.wait_until_ready();
  17261. std::string raw_req =
  17262. "GET /ip HTTP/1.1\r\n"
  17263. "Host: localhost\r\n"
  17264. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17265. "Connection: close\r\n"
  17266. "\r\n";
  17267. std::string out;
  17268. ASSERT_TRUE(send_request(5, raw_req, &out));
  17269. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17270. // Header parser trims surrounding whitespace of the header value
  17271. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17272. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17273. }
  17274. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17275. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17276. // their own X-Forwarded-For as a separate field line rather than extending the
  17277. // one the client sent, so every occurrence has to be taken into account.
  17278. // Reading only the first one hands back the address the client chose.
  17279. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17280. Server svr;
  17281. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17282. std::string observed_remote_addr;
  17283. size_t observed_xff_count = 0;
  17284. svr.Get("/ip", [&](const Request &req, Response &res) {
  17285. observed_remote_addr = req.remote_addr;
  17286. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17287. res.set_content("ok", "text/plain");
  17288. });
  17289. auto port = svr.bind_to_any_port(HOST);
  17290. thread t = thread([&]() { svr.listen_after_bind(); });
  17291. auto se = detail::scope_exit([&] {
  17292. svr.stop();
  17293. t.join();
  17294. ASSERT_FALSE(svr.is_running());
  17295. });
  17296. svr.wait_until_ready();
  17297. // The client supplies the first field line; the trusted proxy appends the
  17298. // address it observed as a second one.
  17299. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17300. "Host: localhost\r\n"
  17301. "X-Forwarded-For: 1.2.3.4\r\n"
  17302. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17303. "Connection: close\r\n"
  17304. "\r\n";
  17305. std::string out;
  17306. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17307. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17308. EXPECT_EQ(observed_xff_count, 2U);
  17309. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17310. // The same chain spread over one field line per hop derives the same client
  17311. // address, i.e. the split and the comma-joined representations agree.
  17312. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17313. "Host: localhost\r\n"
  17314. "X-Forwarded-For: 1.2.3.4\r\n"
  17315. "X-Forwarded-For: 198.51.100.23\r\n"
  17316. "X-Forwarded-For: 192.0.2.45\r\n"
  17317. "Connection: close\r\n"
  17318. "\r\n";
  17319. out.clear();
  17320. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17321. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17322. EXPECT_EQ(observed_xff_count, 3U);
  17323. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17324. }
  17325. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17326. // crash the server (it used to call front() on an empty vector inside
  17327. // get_client_ip). The connection-level remote address must be retained instead.
  17328. static void run_malformed_xff_test(const std::string &xff_value) {
  17329. Server svr;
  17330. svr.set_trusted_proxies({"192.0.2.45"});
  17331. std::string observed_remote_addr;
  17332. svr.Get("/ip", [&](const Request &req, Response &res) {
  17333. observed_remote_addr = req.remote_addr;
  17334. res.set_content("ok", "text/plain");
  17335. });
  17336. int port = 0;
  17337. thread t = thread([&]() {
  17338. port = svr.bind_to_any_port(HOST);
  17339. svr.listen_after_bind();
  17340. });
  17341. auto se = detail::scope_exit([&] {
  17342. svr.stop();
  17343. t.join();
  17344. ASSERT_FALSE(svr.is_running());
  17345. });
  17346. svr.wait_until_ready();
  17347. Client cli(HOST, port);
  17348. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17350. EXPECT_EQ(StatusCode::OK_200, res->status);
  17351. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17352. observed_remote_addr == "127.0.0.1");
  17353. }
  17354. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17355. run_malformed_xff_test("");
  17356. }
  17357. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17358. run_malformed_xff_test(",");
  17359. }
  17360. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17361. run_malformed_xff_test(", , ,");
  17362. }
  17363. // The same rule applies to Accept: a request whose acceptable types are spread
  17364. // over several field lines must be negotiated against all of them.
  17365. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17366. // case-insensitive connection options. Comparing the whole field value against
  17367. // one option misses a client that sends several of them, and misses every
  17368. // casing but the one written in the comparison.
  17369. //
  17370. // Sends req, reads the response, then reuses the same socket for a second
  17371. // request to find out whether the server kept the connection.
  17372. static void probe_connection_reuse(int port, const std::string &req,
  17373. bool *announced_close, bool *reusable) {
  17374. auto error = Error::Success;
  17375. auto sock = detail::create_client_socket(
  17376. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17377. /*connection_timeout_sec=*/5, 0,
  17378. /*read_timeout_sec=*/1, 0,
  17379. /*write_timeout_sec=*/5, 0, std::string(), error);
  17380. ASSERT_NE(sock, INVALID_SOCKET);
  17381. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17382. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17383. "Host: localhost\r\n"
  17384. "Connection: close\r\n"
  17385. "\r\n";
  17386. std::string first_response;
  17387. std::string second_response;
  17388. detail::process_client_socket(
  17389. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17390. [&](Stream &strm) {
  17391. if (strm.write(req.data(), req.size()) !=
  17392. static_cast<ssize_t>(req.size())) {
  17393. return false;
  17394. }
  17395. char buf[512];
  17396. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17397. // Headers plus the two-byte body of the handler below
  17398. while (reader.getline()) {
  17399. first_response += reader.ptr();
  17400. if (first_response.find("ok") != std::string::npos) { break; }
  17401. }
  17402. if (strm.write(second.data(), second.size()) !=
  17403. static_cast<ssize_t>(second.size())) {
  17404. return true;
  17405. }
  17406. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17407. while (reader2.getline()) {
  17408. second_response += reader2.ptr();
  17409. if (second_response.find("ok") != std::string::npos) { break; }
  17410. }
  17411. return true;
  17412. });
  17413. *announced_close =
  17414. first_response.find("Connection: close") != std::string::npos;
  17415. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17416. }
  17417. class ConnectionTokenTest : public ::testing::Test {
  17418. protected:
  17419. void SetUp() override {
  17420. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17421. res.set_content("ok", "text/plain");
  17422. });
  17423. port_ = svr_.bind_to_any_port(HOST);
  17424. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17425. svr_.wait_until_ready();
  17426. }
  17427. void TearDown() override {
  17428. svr_.stop();
  17429. if (thread_.joinable()) { thread_.join(); }
  17430. }
  17431. Server svr_;
  17432. int port_ = 0;
  17433. thread thread_;
  17434. };
  17435. // "close" alongside another option still closes the connection, and the
  17436. // response says so rather than leaving the peer to discover it.
  17437. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17438. bool announced_close = false;
  17439. bool reusable = true;
  17440. probe_connection_reuse(port_,
  17441. "GET /keepalive HTTP/1.1\r\n"
  17442. "Host: localhost\r\n"
  17443. "Connection: keep-alive, close\r\n"
  17444. "\r\n",
  17445. &announced_close, &reusable);
  17446. EXPECT_TRUE(announced_close);
  17447. EXPECT_FALSE(reusable);
  17448. }
  17449. // "close" split over two field lines is the same list, so it is honored too.
  17450. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17451. bool announced_close = false;
  17452. bool reusable = true;
  17453. probe_connection_reuse(port_,
  17454. "GET /keepalive HTTP/1.1\r\n"
  17455. "Host: localhost\r\n"
  17456. "Connection: keep-alive\r\n"
  17457. "Connection: close\r\n"
  17458. "\r\n",
  17459. &announced_close, &reusable);
  17460. EXPECT_TRUE(announced_close);
  17461. EXPECT_FALSE(reusable);
  17462. }
  17463. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17464. // keep-alive in the spelling everyone actually sends keeps its connection.
  17465. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17466. bool announced_close = false;
  17467. bool reusable = false;
  17468. probe_connection_reuse(port_,
  17469. "GET /keepalive HTTP/1.0\r\n"
  17470. "Host: localhost\r\n"
  17471. "Connection: keep-alive\r\n"
  17472. "\r\n",
  17473. &announced_close, &reusable);
  17474. EXPECT_FALSE(announced_close);
  17475. EXPECT_TRUE(reusable);
  17476. }
  17477. // A token the value merely contains is not the token itself.
  17478. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17479. bool announced_close = false;
  17480. bool reusable = false;
  17481. probe_connection_reuse(port_,
  17482. "GET /keepalive HTTP/1.1\r\n"
  17483. "Host: localhost\r\n"
  17484. "Connection: notclose\r\n"
  17485. "\r\n",
  17486. &announced_close, &reusable);
  17487. EXPECT_FALSE(announced_close);
  17488. EXPECT_TRUE(reusable);
  17489. }
  17490. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17491. Server svr;
  17492. std::vector<std::string> observed_types;
  17493. svr.Get("/", [&](const Request &req, Response &res) {
  17494. observed_types = req.accept_content_types;
  17495. res.set_content("ok", "text/plain");
  17496. });
  17497. auto port = svr.bind_to_any_port(HOST);
  17498. thread t = thread([&]() { svr.listen_after_bind(); });
  17499. auto se = detail::scope_exit([&] {
  17500. svr.stop();
  17501. t.join();
  17502. ASSERT_FALSE(svr.is_running());
  17503. });
  17504. svr.wait_until_ready();
  17505. Client cli(HOST, port);
  17506. Headers headers;
  17507. headers.emplace("Accept", "text/plain;q=0.5");
  17508. headers.emplace("Accept", "application/json");
  17509. auto res = cli.Get("/", headers);
  17510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17511. EXPECT_EQ(StatusCode::OK_200, res->status);
  17512. // Sorted by q-value, so the second field line's type comes first
  17513. ASSERT_EQ(2U, observed_types.size());
  17514. EXPECT_EQ("application/json", observed_types[0]);
  17515. EXPECT_EQ("text/plain", observed_types[1]);
  17516. }
  17517. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17518. // empty field line must not contribute a bare comma to the combined value.
  17519. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17520. Server svr;
  17521. std::vector<std::string> observed_types;
  17522. svr.Get("/", [&](const Request &req, Response &res) {
  17523. observed_types = req.accept_content_types;
  17524. res.set_content("ok", "text/plain");
  17525. });
  17526. auto port = svr.bind_to_any_port(HOST);
  17527. thread t = thread([&]() { svr.listen_after_bind(); });
  17528. auto se = detail::scope_exit([&] {
  17529. svr.stop();
  17530. t.join();
  17531. ASSERT_FALSE(svr.is_running());
  17532. });
  17533. svr.wait_until_ready();
  17534. // Empty first field line, then a real one
  17535. std::string raw_req = "GET / HTTP/1.1\r\n"
  17536. "Host: localhost\r\n"
  17537. "Accept:\r\n"
  17538. "Accept: application/json\r\n"
  17539. "Connection: close\r\n"
  17540. "\r\n";
  17541. std::string out;
  17542. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17543. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17544. ASSERT_EQ(1U, observed_types.size());
  17545. EXPECT_EQ("application/json", observed_types[0]);
  17546. }
  17547. // The skip in get_combined_header_value() is what keeps an empty field line
  17548. // from contributing a bare comma. Only a trailing empty field line exercises
  17549. // it: a leading one is already covered by the "combined is still empty" check,
  17550. // and parse_accept_header() now ignores the empty element either way, so the
  17551. // request-level test above can no longer tell the two apart.
  17552. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17553. Headers headers;
  17554. headers.emplace("Accept", "text/html");
  17555. headers.emplace("Accept", "");
  17556. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17557. headers.clear();
  17558. headers.emplace("Accept", "");
  17559. headers.emplace("Accept", "application/json");
  17560. EXPECT_EQ("application/json",
  17561. detail::get_combined_header_value(headers, "Accept"));
  17562. }
  17563. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17564. // An encoding offered on a later Accept-Encoding field line is still offered.
  17565. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17566. Server svr;
  17567. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17568. res.set_content(std::string(1024, 'x'), "text/plain");
  17569. });
  17570. auto port = svr.bind_to_any_port(HOST);
  17571. thread t = thread([&]() { svr.listen_after_bind(); });
  17572. auto se = detail::scope_exit([&] {
  17573. svr.stop();
  17574. t.join();
  17575. ASSERT_FALSE(svr.is_running());
  17576. });
  17577. svr.wait_until_ready();
  17578. Client cli(HOST, port);
  17579. cli.set_decompress(false);
  17580. Headers headers;
  17581. headers.emplace("Accept-Encoding", "identity");
  17582. headers.emplace("Accept-Encoding", "gzip");
  17583. auto res = cli.Get("/", headers);
  17584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17585. EXPECT_EQ(StatusCode::OK_200, res->status);
  17586. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17587. }
  17588. #endif
  17589. #ifndef _WIN32
  17590. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17591. Server svr;
  17592. svr.Post("/post", [&](const Request &req, Response &res) {
  17593. res.set_content(req.body, "text/plain");
  17594. });
  17595. svr.Put("/put", [&](const Request &req, Response &res) {
  17596. res.set_content(req.body, "text/plain");
  17597. });
  17598. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17599. res.set_content(req.body, "text/plain");
  17600. });
  17601. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17602. res.set_content(req.body, "text/plain");
  17603. });
  17604. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17605. auto se = detail::scope_exit([&] {
  17606. svr.stop();
  17607. t.join();
  17608. ASSERT_FALSE(svr.is_running());
  17609. });
  17610. svr.wait_until_ready();
  17611. std::string resp;
  17612. // POST without Content-Length
  17613. ASSERT_TRUE(send_request(5,
  17614. "POST /post HTTP/1.1\r\n"
  17615. "Host: localhost\r\n"
  17616. "Connection: close\r\n"
  17617. "\r\n",
  17618. &resp));
  17619. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17620. // PUT without Content-Length
  17621. resp.clear();
  17622. ASSERT_TRUE(send_request(5,
  17623. "PUT /put HTTP/1.1\r\n"
  17624. "Host: localhost\r\n"
  17625. "Connection: close\r\n"
  17626. "\r\n",
  17627. &resp));
  17628. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17629. // PATCH without Content-Length
  17630. resp.clear();
  17631. ASSERT_TRUE(send_request(5,
  17632. "PATCH /patch HTTP/1.1\r\n"
  17633. "Host: localhost\r\n"
  17634. "Connection: close\r\n"
  17635. "\r\n",
  17636. &resp));
  17637. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17638. // DELETE without Content-Length
  17639. resp.clear();
  17640. ASSERT_TRUE(send_request(5,
  17641. "DELETE /delete HTTP/1.1\r\n"
  17642. "Host: localhost\r\n"
  17643. "Connection: close\r\n"
  17644. "\r\n",
  17645. &resp));
  17646. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17647. }
  17648. #endif
  17649. //==============================================================================
  17650. // open_stream() Tests
  17651. //==============================================================================
  17652. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17653. std::string result;
  17654. char buf[8192];
  17655. ssize_t n;
  17656. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17657. result.append(buf, static_cast<size_t>(n));
  17658. }
  17659. return result;
  17660. }
  17661. // Mock stream for unit tests
  17662. class MockStream : public Stream {
  17663. public:
  17664. std::string data;
  17665. size_t pos = 0;
  17666. ssize_t error_after = -1; // -1 = no error
  17667. explicit MockStream(const std::string &d, ssize_t err = -1)
  17668. : data(d), error_after(err) {}
  17669. bool is_readable() const override { return true; }
  17670. bool wait_readable() const override { return true; }
  17671. bool wait_writable() const override { return true; }
  17672. ssize_t read(char *ptr, size_t size) override {
  17673. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17674. if (pos >= data.size()) return 0;
  17675. size_t limit =
  17676. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17677. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17678. std::memcpy(ptr, data.data() + pos, to_read);
  17679. pos += to_read;
  17680. return static_cast<ssize_t>(to_read);
  17681. }
  17682. ssize_t write(const char *, size_t) override { return -1; }
  17683. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17684. ip = "127.0.0.1";
  17685. port = 0;
  17686. }
  17687. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17688. ip = "127.0.0.1";
  17689. port = 0;
  17690. }
  17691. socket_t socket() const override { return INVALID_SOCKET; }
  17692. time_t duration() const override { return 0; }
  17693. };
  17694. TEST(StreamHandleTest, Basic) {
  17695. ClientImpl::StreamHandle handle;
  17696. EXPECT_FALSE(handle.is_valid());
  17697. handle.response = detail::make_unique<Response>();
  17698. handle.error = Error::Connection;
  17699. EXPECT_FALSE(handle.is_valid());
  17700. handle.error = Error::Success;
  17701. EXPECT_TRUE(handle.is_valid());
  17702. }
  17703. TEST(BodyReaderTest, Basic) {
  17704. MockStream stream("Hello, World!");
  17705. detail::BodyReader reader;
  17706. reader.stream = &stream;
  17707. reader.content_length = 13;
  17708. char buf[32];
  17709. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17710. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17711. EXPECT_TRUE(reader.eof);
  17712. }
  17713. TEST(BodyReaderTest, NoStream) {
  17714. detail::BodyReader reader;
  17715. char buf[32];
  17716. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17717. EXPECT_EQ(Error::Connection, reader.last_error);
  17718. }
  17719. TEST(BodyReaderTest, Error) {
  17720. MockStream stream("Hello, World!", 5);
  17721. detail::BodyReader reader;
  17722. reader.stream = &stream;
  17723. reader.content_length = 13;
  17724. char buf[32];
  17725. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17726. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17727. EXPECT_EQ(Error::Read, reader.last_error);
  17728. }
  17729. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17730. // Mock-based StreamHandle tests relying on private internals are removed.
  17731. class OpenStreamTest : public ::testing::Test {
  17732. protected:
  17733. void SetUp() override {
  17734. svr_.Get("/hello", [](const Request &, Response &res) {
  17735. res.set_content("Hello World!", "text/plain");
  17736. });
  17737. svr_.Get("/large", [](const Request &, Response &res) {
  17738. res.set_content(std::string(10000, 'X'), "text/plain");
  17739. });
  17740. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17741. res.set_content("Hello World!", "image/jpeg");
  17742. res.set_header("Content-Encoding", "UTF-8");
  17743. });
  17744. svr_.Get("/chunked", [](const Request &, Response &res) {
  17745. res.set_chunked_content_provider("text/plain",
  17746. [](size_t offset, DataSink &sink) {
  17747. if (offset < 15) {
  17748. sink.write("chunk", 5);
  17749. return true;
  17750. }
  17751. sink.done();
  17752. return true;
  17753. });
  17754. });
  17755. svr_.Get("/compressible", [](const Request &, Response &res) {
  17756. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17757. DataSink &sink) {
  17758. if (offset < 100 * 1024) {
  17759. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17760. sink.write(chunk.data(), chunk.size());
  17761. return true;
  17762. }
  17763. sink.done();
  17764. return true;
  17765. });
  17766. });
  17767. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17768. [](const Request & /*req*/, Response &res) {
  17769. auto i = new int(0);
  17770. res.set_header("Trailer", "Content-Length, X-Allowed");
  17771. res.set_chunked_content_provider(
  17772. "text/plain",
  17773. [i](size_t /*offset*/, DataSink &sink) {
  17774. switch (*i) {
  17775. case 0: sink.os << "123"; break;
  17776. case 1: sink.os << "456"; break;
  17777. case 2: sink.os << "789"; break;
  17778. case 3: {
  17779. sink.done_with_trailer(
  17780. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17781. } break;
  17782. }
  17783. (*i)++;
  17784. return true;
  17785. },
  17786. [i](bool success) {
  17787. EXPECT_TRUE(success);
  17788. delete i;
  17789. });
  17790. });
  17791. // Echo headers endpoint for header-related tests
  17792. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17793. std::string body;
  17794. for (const auto &h : req.headers) {
  17795. body.append(h.first);
  17796. body.push_back(':');
  17797. body.append(h.second);
  17798. body.push_back('\n');
  17799. }
  17800. res.set_content(body, "text/plain");
  17801. });
  17802. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17803. std::string body;
  17804. for (const auto &h : req.headers) {
  17805. body.append(h.first);
  17806. body.push_back(':');
  17807. body.append(h.second);
  17808. body.push_back('\n');
  17809. }
  17810. res.set_content(body, "text/plain");
  17811. });
  17812. port_ = svr_.bind_to_any_port("127.0.0.1");
  17813. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17814. svr_.wait_until_ready();
  17815. }
  17816. void TearDown() override {
  17817. svr_.stop();
  17818. if (thread_.joinable()) thread_.join();
  17819. }
  17820. Server svr_;
  17821. std::thread thread_;
  17822. int port_ = 0;
  17823. };
  17824. TEST_F(OpenStreamTest, Basic) {
  17825. Client cli("127.0.0.1", port_);
  17826. auto handle = cli.open_stream("GET", "/hello");
  17827. EXPECT_TRUE(handle.is_valid());
  17828. EXPECT_EQ("Hello World!", read_all(handle));
  17829. }
  17830. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17831. Client cli("127.0.0.1", port_);
  17832. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17833. ASSERT_TRUE(handle.is_valid());
  17834. EXPECT_EQ("Hello World!", read_all(handle));
  17835. }
  17836. TEST_F(OpenStreamTest, SmallBuffer) {
  17837. Client cli("127.0.0.1", port_);
  17838. auto handle = cli.open_stream("GET", "/hello");
  17839. std::string result;
  17840. char buf[4];
  17841. ssize_t n;
  17842. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17843. result.append(buf, static_cast<size_t>(n));
  17844. EXPECT_EQ("Hello World!", result);
  17845. }
  17846. TEST_F(OpenStreamTest, DefaultHeaders) {
  17847. Client cli("127.0.0.1", port_);
  17848. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17849. {
  17850. auto handle = cli.open_stream("GET", "/echo-headers");
  17851. ASSERT_TRUE(handle.is_valid());
  17852. auto body = read_all(handle);
  17853. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17854. std::string::npos);
  17855. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17856. std::string::npos);
  17857. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17858. }
  17859. // open_stream POST with body and no explicit content_type should NOT add
  17860. // text/plain Content-Type (behavior differs from non-streaming path), but
  17861. // should include Content-Length
  17862. {
  17863. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17864. ASSERT_TRUE(handle.is_valid());
  17865. auto body = read_all(handle);
  17866. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17867. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17868. }
  17869. // open_stream POST with explicit Content-Type should preserve it
  17870. {
  17871. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17872. {{"Content-Type", "application/custom"}},
  17873. "{}", "application/custom");
  17874. ASSERT_TRUE(handle.is_valid());
  17875. auto body = read_all(handle);
  17876. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17877. }
  17878. // User-specified User-Agent must not be overwritten for stream API
  17879. {
  17880. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17881. {{"User-Agent", "MyAgent/1.2"}});
  17882. ASSERT_TRUE(handle.is_valid());
  17883. auto body = read_all(handle);
  17884. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17885. }
  17886. }
  17887. TEST_F(OpenStreamTest, Large) {
  17888. Client cli("127.0.0.1", port_);
  17889. auto handle = cli.open_stream("GET", "/large");
  17890. EXPECT_EQ(10000u, read_all(handle).size());
  17891. }
  17892. TEST_F(OpenStreamTest, ConnectionError) {
  17893. Client cli("127.0.0.1", 9999);
  17894. auto handle = cli.open_stream("GET", "/hello");
  17895. EXPECT_FALSE(handle.is_valid());
  17896. }
  17897. TEST_F(OpenStreamTest, Chunked) {
  17898. Client cli("127.0.0.1", port_);
  17899. auto handle = cli.open_stream("GET", "/chunked");
  17900. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17901. "Transfer-Encoding") == "chunked");
  17902. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17903. }
  17904. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17905. Client cli("127.0.0.1", port_);
  17906. auto handle =
  17907. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17908. ASSERT_TRUE(handle.is_valid());
  17909. // Consume body to allow trailers to be received/parsed
  17910. auto body = read_all(handle);
  17911. // Explicitly parse trailers (ensure trailers are available for assertion)
  17912. handle.parse_trailers_if_needed();
  17913. EXPECT_EQ(std::string("123456789"), body);
  17914. // The response should include a Trailer header declaring both names
  17915. ASSERT_TRUE(handle.response);
  17916. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17917. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17918. handle.response->get_header_value("Trailer"));
  17919. // Prohibited trailer must not be present
  17920. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17921. // Allowed trailer should be present
  17922. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17923. EXPECT_EQ(std::string("yes"),
  17924. handle.response->get_trailer_value("X-Allowed"));
  17925. // Verify trailers are NOT present as regular headers
  17926. EXPECT_EQ(std::string(""),
  17927. handle.response->get_header_value("Content-Length"));
  17928. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17929. }
  17930. static std::thread serve_single_response(std::promise<int> &port_promise,
  17931. const std::string &response) {
  17932. return std::thread([&port_promise, response] {
  17933. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17934. default_socket_options(srv);
  17935. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17936. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17937. sockaddr_in addr{};
  17938. addr.sin_family = AF_INET;
  17939. addr.sin_port = htons(0); // Let OS assign a free port
  17940. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17941. int opt = 1;
  17942. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17943. #ifdef _WIN32
  17944. reinterpret_cast<const char *>(&opt),
  17945. #else
  17946. &opt,
  17947. #endif
  17948. sizeof(opt));
  17949. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17950. ::listen(srv, 1) != 0) {
  17951. port_promise.set_value(-1);
  17952. detail::close_socket(srv);
  17953. return;
  17954. }
  17955. socklen_t addr_len = sizeof(addr);
  17956. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17957. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17958. sockaddr_in cli_addr{};
  17959. socklen_t cli_len = sizeof(cli_addr);
  17960. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17961. if (cli != INVALID_SOCKET) {
  17962. // Read the complete HTTP request (until the blank line that terminates
  17963. // headers) before sending the response. If the server closes the socket
  17964. // while the client's request data is still unread in the kernel receive
  17965. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17966. // connection on both sides: it discards the client's receive buffer
  17967. // (which already holds our response) and causes any in-progress write on
  17968. // the client to fail with ECONNRESET. Reading all request data first
  17969. // ensures close() emits a graceful FIN.
  17970. {
  17971. char rbuf[256];
  17972. std::string req;
  17973. while (req.find("\r\n\r\n") == std::string::npos) {
  17974. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17975. if (n <= 0) { break; }
  17976. req.append(rbuf, static_cast<size_t>(n));
  17977. }
  17978. }
  17979. ::send(cli,
  17980. #ifdef _WIN32
  17981. static_cast<const char *>(response.c_str()),
  17982. static_cast<int>(response.size()),
  17983. #else
  17984. response.c_str(), response.size(),
  17985. #endif
  17986. 0);
  17987. detail::close_socket(cli);
  17988. }
  17989. detail::close_socket(srv);
  17990. });
  17991. }
  17992. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  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 =
  17999. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18000. "Content-Type: text/plain\r\n"
  18001. "Content-Length: not-a-number\r\n"
  18002. "Connection: close\r\n"
  18003. "\r\n"
  18004. "hello");
  18005. auto port = port_future.get();
  18006. ASSERT_GT(port, 0);
  18007. Client cli("127.0.0.1", port);
  18008. auto handle = cli.open_stream("GET", "/");
  18009. EXPECT_FALSE(handle.is_valid());
  18010. server_thread.join();
  18011. }
  18012. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18013. #ifndef _WIN32
  18014. signal(SIGPIPE, SIG_IGN);
  18015. #endif
  18016. std::promise<int> port_promise;
  18017. auto port_future = port_promise.get_future();
  18018. auto server_thread = serve_single_response(
  18019. port_promise, "HTTP/1.1 200 OK\r\n"
  18020. "Content-Type: text/plain\r\n"
  18021. "Content-Length: 99999999999999999999999999\r\n"
  18022. "Connection: close\r\n"
  18023. "\r\n"
  18024. "hello");
  18025. auto port = port_future.get();
  18026. ASSERT_GT(port, 0);
  18027. // Historically std::stoull would throw std::out_of_range here and crash
  18028. // the process, then parsing silently clamped to a bogus framing length and
  18029. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18030. // so the stream fails to open, matching the not-a-number case above. The
  18031. // process still must NOT terminate.
  18032. Client cli("127.0.0.1", port);
  18033. auto handle = cli.open_stream("GET", "/");
  18034. EXPECT_FALSE(handle.is_valid());
  18035. server_thread.join();
  18036. }
  18037. // Serves `response` to the single request `fn` makes with a fresh client.
  18038. template <typename Fn>
  18039. static void with_single_response(const std::string &response, Fn fn) {
  18040. #ifndef _WIN32
  18041. signal(SIGPIPE, SIG_IGN);
  18042. #endif
  18043. std::promise<int> port_promise;
  18044. auto port_future = port_promise.get_future();
  18045. auto server_thread = serve_single_response(port_promise, response);
  18046. auto se = detail::scope_exit([&] { server_thread.join(); });
  18047. auto port = port_future.get();
  18048. ASSERT_GT(port, 0);
  18049. Client cli("127.0.0.1", port);
  18050. fn(cli);
  18051. }
  18052. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18053. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18054. // the chunked coding and drop Content-Length, so a front-end that trusts
  18055. // Content-Length would disagree about where the body ends (response
  18056. // smuggling). The client must reject such a response.
  18057. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18058. for (const char *te : {"chunked", "gzip, chunked"}) {
  18059. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18060. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18061. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18062. "5\r\nhello\r\n0\r\n\r\n";
  18063. with_single_response(response, [&](Client &cli) {
  18064. auto res = cli.Get("/");
  18065. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18066. EXPECT_EQ(Error::Read, res.error()) << te;
  18067. });
  18068. with_single_response(response, [&](Client &cli) {
  18069. auto handle = cli.open_stream("GET", "/");
  18070. EXPECT_FALSE(handle.is_valid()) << te;
  18071. EXPECT_EQ(Error::Read, handle.error) << te;
  18072. });
  18073. }
  18074. }
  18075. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18076. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18077. // closing the connection (unlike a request, which must be rejected).
  18078. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18079. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18080. "Transfer-Encoding: chunked\r\n"
  18081. "Connection: close\r\n"
  18082. "\r\n"
  18083. "5\r\nhello\r\n0\r\n\r\n",
  18084. "HTTP/1.1 200 OK\r\n"
  18085. "Transfer-Encoding: gzip\r\n"
  18086. "Connection: close\r\n"
  18087. "\r\n"
  18088. "hello"}) {
  18089. with_single_response(response, [&](Client &cli) {
  18090. auto res = cli.Get("/");
  18091. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18092. EXPECT_EQ("hello", res->body);
  18093. });
  18094. with_single_response(response, [&](Client &cli) {
  18095. auto handle = cli.open_stream("GET", "/");
  18096. ASSERT_TRUE(handle.is_valid()) << response;
  18097. EXPECT_EQ("hello", read_all(handle));
  18098. });
  18099. }
  18100. }
  18101. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18102. // framing headers describe nothing to read and must not be rejected.
  18103. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18104. const std::string framing = "Content-Length: 5\r\n"
  18105. "Transfer-Encoding: chunked\r\n"
  18106. "Connection: close\r\n"
  18107. "\r\n";
  18108. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18109. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18110. });
  18111. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18112. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18113. });
  18114. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18115. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18116. with_single_response(response, [&](Client &cli) {
  18117. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18118. });
  18119. with_single_response(response, [&](Client &cli) {
  18120. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18121. });
  18122. }
  18123. }
  18124. // A payload max length of 0 means no limit, however the body is framed.
  18125. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18126. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18127. "Transfer-Encoding: chunked\r\n"
  18128. "\r\n"
  18129. "5\r\nhello\r\n0\r\n\r\n",
  18130. "HTTP/1.1 200 OK\r\n"
  18131. "Connection: close\r\n"
  18132. "\r\n"
  18133. "hello"}) {
  18134. with_single_response(response, [&](Client &cli) {
  18135. cli.set_payload_max_length(0);
  18136. auto res = cli.Get("/");
  18137. ASSERT_TRUE(res) << response;
  18138. EXPECT_EQ("hello", res->body) << response;
  18139. });
  18140. }
  18141. }
  18142. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18143. Server svr;
  18144. svr.set_payload_max_length(0);
  18145. svr.Post("/echo", [](const Request &req, Response &res) {
  18146. res.set_content(req.body, "text/plain");
  18147. });
  18148. auto port = svr.bind_to_any_port(HOST);
  18149. thread t = thread([&] { svr.listen_after_bind(); });
  18150. auto se = detail::scope_exit([&] {
  18151. svr.stop();
  18152. t.join();
  18153. ASSERT_FALSE(svr.is_running());
  18154. });
  18155. svr.wait_until_ready();
  18156. Client cli(HOST, port);
  18157. auto res = cli.Post(
  18158. "/echo",
  18159. [](size_t /*offset*/, DataSink &sink) {
  18160. sink.write("hello", 5);
  18161. sink.done();
  18162. return true;
  18163. },
  18164. "text/plain");
  18165. ASSERT_TRUE(res);
  18166. EXPECT_EQ(StatusCode::OK_200, res->status);
  18167. EXPECT_EQ("hello", res->body);
  18168. }
  18169. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18170. TEST_F(OpenStreamTest, Gzip) {
  18171. Client cli("127.0.0.1", port_);
  18172. auto handle = cli.open_stream("GET", "/compressible", {},
  18173. {{"Accept-Encoding", "gzip"}});
  18174. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18175. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18176. }
  18177. #endif
  18178. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18179. TEST_F(OpenStreamTest, Brotli) {
  18180. Client cli("127.0.0.1", port_);
  18181. auto handle =
  18182. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18183. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18184. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18185. }
  18186. #endif
  18187. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18188. TEST_F(OpenStreamTest, Zstd) {
  18189. Client cli("127.0.0.1", port_);
  18190. auto handle = cli.open_stream("GET", "/compressible", {},
  18191. {{"Accept-Encoding", "zstd"}});
  18192. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18193. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18194. }
  18195. #endif
  18196. #ifdef CPPHTTPLIB_SSL_ENABLED
  18197. class SSLOpenStreamTest : public ::testing::Test {
  18198. protected:
  18199. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18200. void SetUp() override {
  18201. svr_.Get("/hello", [](const Request &, Response &res) {
  18202. res.set_content("Hello SSL World!", "text/plain");
  18203. });
  18204. svr_.Get("/chunked", [](const Request &, Response &res) {
  18205. res.set_chunked_content_provider("text/plain",
  18206. [](size_t offset, DataSink &sink) {
  18207. if (offset < 15) {
  18208. sink.write("chunk", 5);
  18209. return true;
  18210. }
  18211. sink.done();
  18212. return true;
  18213. });
  18214. });
  18215. svr_.Post("/echo", [](const Request &req, Response &res) {
  18216. res.set_content(req.body, req.get_header_value("Content-Type"));
  18217. });
  18218. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18219. std::string body = req.body;
  18220. res.set_chunked_content_provider(
  18221. "text/plain", [body](size_t offset, DataSink &sink) {
  18222. if (offset < body.size()) {
  18223. sink.write(body.data() + offset, body.size() - offset);
  18224. }
  18225. sink.done();
  18226. return true;
  18227. });
  18228. });
  18229. port_ = svr_.bind_to_any_port("127.0.0.1");
  18230. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18231. svr_.wait_until_ready();
  18232. }
  18233. void TearDown() override {
  18234. svr_.stop();
  18235. if (thread_.joinable()) thread_.join();
  18236. }
  18237. SSLServer svr_;
  18238. std::thread thread_;
  18239. int port_ = 0;
  18240. };
  18241. TEST_F(SSLOpenStreamTest, Basic) {
  18242. SSLClient cli("127.0.0.1", port_);
  18243. cli.enable_server_certificate_verification(false);
  18244. auto handle = cli.open_stream("GET", "/hello");
  18245. ASSERT_TRUE(handle.is_valid());
  18246. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18247. }
  18248. TEST_F(SSLOpenStreamTest, Chunked) {
  18249. SSLClient cli("127.0.0.1", port_);
  18250. cli.enable_server_certificate_verification(false);
  18251. auto handle = cli.open_stream("GET", "/chunked");
  18252. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18253. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18254. "Transfer-Encoding") == "chunked");
  18255. auto body = read_all(handle);
  18256. EXPECT_EQ("chunkchunkchunk", body);
  18257. }
  18258. TEST_F(SSLOpenStreamTest, Post) {
  18259. SSLClient cli("127.0.0.1", port_);
  18260. cli.enable_server_certificate_verification(false);
  18261. auto handle =
  18262. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18263. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18264. EXPECT_EQ(200, handle.response->status);
  18265. auto body = read_all(handle);
  18266. EXPECT_EQ("Hello SSL POST", body);
  18267. }
  18268. TEST_F(SSLOpenStreamTest, PostChunked) {
  18269. SSLClient cli("127.0.0.1", port_);
  18270. cli.enable_server_certificate_verification(false);
  18271. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18272. "Chunked SSL Data", "text/plain");
  18273. ASSERT_TRUE(handle.is_valid());
  18274. EXPECT_EQ(200, handle.response->status);
  18275. auto body = read_all(handle);
  18276. EXPECT_EQ("Chunked SSL Data", body);
  18277. }
  18278. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18279. // Content-Length is terminated by the server closing the connection. When the
  18280. // SSL peer sends a close_notify after the body, the client must treat it as a
  18281. // clean EOF and return a successful response rather than an error.
  18282. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18283. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18284. ASSERT_TRUE(svr.is_valid());
  18285. svr.set_keep_alive_max_count(1);
  18286. const std::string expected_body = "Hello from connection-close response!";
  18287. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18288. res.set_content_provider("text/plain",
  18289. [&](size_t offset, DataSink &sink) -> bool {
  18290. if (offset < expected_body.size()) {
  18291. sink.write(expected_body.data() + offset,
  18292. expected_body.size() - offset);
  18293. }
  18294. sink.done();
  18295. return true;
  18296. });
  18297. });
  18298. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18299. auto se = detail::scope_exit([&] {
  18300. svr.stop();
  18301. listen_thread.join();
  18302. ASSERT_FALSE(svr.is_running());
  18303. });
  18304. svr.wait_until_ready();
  18305. SSLClient cli(HOST, PORT);
  18306. cli.enable_server_certificate_verification(false);
  18307. auto res = cli.Get("/no-content-length");
  18308. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18309. EXPECT_EQ(StatusCode::OK_200, res->status);
  18310. EXPECT_EQ(expected_body, res->body);
  18311. }
  18312. #endif // CPPHTTPLIB_SSL_ENABLED
  18313. //==============================================================================
  18314. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18315. // results for various scenarios.
  18316. //==============================================================================
  18317. TEST(ParityTest, GetVsOpenStream) {
  18318. Server svr;
  18319. const std::string path = "/parity";
  18320. const std::string content = "Parity test content: hello world";
  18321. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18322. res.set_content(content, "text/plain");
  18323. });
  18324. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18325. auto se = detail::scope_exit([&] {
  18326. svr.stop();
  18327. t.join();
  18328. ASSERT_FALSE(svr.is_running());
  18329. });
  18330. svr.wait_until_ready();
  18331. Client cli(HOST, PORT);
  18332. // Non-stream path
  18333. auto r1 = cli.Get(path);
  18334. ASSERT_TRUE(r1);
  18335. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18336. // Stream path
  18337. auto h = cli.open_stream("GET", path);
  18338. ASSERT_TRUE(h.is_valid());
  18339. EXPECT_EQ(r1->body, read_all(h));
  18340. }
  18341. // Helper to compress data with provided compressor type T
  18342. template <typename Compressor>
  18343. static std::string compress_payload_for_parity(const std::string &in) {
  18344. std::string out;
  18345. Compressor compressor;
  18346. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18347. [&](const char *data, size_t n) {
  18348. out.append(data, n);
  18349. return true;
  18350. });
  18351. EXPECT_TRUE(ok);
  18352. return out;
  18353. }
  18354. // Helper function for compression parity tests
  18355. template <typename Compressor>
  18356. static void test_compression_parity(const std::string &original,
  18357. const std::string &path,
  18358. const std::string &encoding) {
  18359. const std::string compressed =
  18360. compress_payload_for_parity<Compressor>(original);
  18361. Server svr;
  18362. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18363. res.set_content(compressed, "application/octet-stream");
  18364. res.set_header("Content-Encoding", encoding);
  18365. });
  18366. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18367. auto se = detail::scope_exit([&] {
  18368. svr.stop();
  18369. t.join();
  18370. ASSERT_FALSE(svr.is_running());
  18371. });
  18372. svr.wait_until_ready();
  18373. Client cli(HOST, PORT);
  18374. // Non-streaming
  18375. {
  18376. auto res = cli.Get(path);
  18377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18378. EXPECT_EQ(StatusCode::OK_200, res->status);
  18379. EXPECT_EQ(original, res->body);
  18380. }
  18381. // Streaming
  18382. {
  18383. auto h = cli.open_stream("GET", path);
  18384. ASSERT_TRUE(h.is_valid());
  18385. EXPECT_EQ(original, read_all(h));
  18386. }
  18387. }
  18388. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18389. TEST(ParityTest, Gzip) {
  18390. test_compression_parity<detail::gzip_compressor>(
  18391. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18392. }
  18393. #endif
  18394. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18395. TEST(ParityTest, Brotli) {
  18396. test_compression_parity<detail::brotli_compressor>(
  18397. "Hello, brotli parity test payload", "/parity-br", "br");
  18398. }
  18399. #endif
  18400. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18401. TEST(ParityTest, Zstd) {
  18402. test_compression_parity<detail::zstd_compressor>(
  18403. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18404. }
  18405. #endif
  18406. //==============================================================================
  18407. // New Stream API Tests
  18408. //==============================================================================
  18409. inline std::string read_body(httplib::stream::Result &result) {
  18410. std::string body;
  18411. while (result.next()) {
  18412. body.append(result.data(), result.size());
  18413. }
  18414. return body;
  18415. }
  18416. TEST(ClientConnectionTest, Basic) {
  18417. httplib::ClientConnection conn;
  18418. EXPECT_FALSE(conn.is_open());
  18419. conn.sock = 1;
  18420. EXPECT_TRUE(conn.is_open());
  18421. httplib::ClientConnection conn2(std::move(conn));
  18422. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18423. conn2.sock = INVALID_SOCKET;
  18424. }
  18425. // Unified test server for all stream::* tests
  18426. class StreamApiTest : public ::testing::Test {
  18427. protected:
  18428. void SetUp() override {
  18429. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18430. res.set_content("Hello World!", "text/plain");
  18431. });
  18432. svr_.Get("/echo-params",
  18433. [](const httplib::Request &req, httplib::Response &res) {
  18434. std::string r;
  18435. for (const auto &p : req.params) {
  18436. if (!r.empty()) r += "&";
  18437. r += p.first + "=" + p.second;
  18438. }
  18439. res.set_content(r, "text/plain");
  18440. });
  18441. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18442. res.set_content(req.body, req.get_header_value("Content-Type"));
  18443. });
  18444. svr_.Post("/echo-headers",
  18445. [](const httplib::Request &req, httplib::Response &res) {
  18446. std::string r;
  18447. for (const auto &h : req.headers)
  18448. r += h.first + ": " + h.second + "\n";
  18449. res.set_content(r, "text/plain");
  18450. });
  18451. svr_.Post("/echo-params",
  18452. [](const httplib::Request &req, httplib::Response &res) {
  18453. std::string r = "params:";
  18454. for (const auto &p : req.params)
  18455. r += p.first + "=" + p.second + ";";
  18456. res.set_content(r + " body:" + req.body, "text/plain");
  18457. });
  18458. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18459. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18460. });
  18461. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18462. res.set_content("PUT:" + req.body, "text/plain");
  18463. });
  18464. svr_.Patch("/echo",
  18465. [](const httplib::Request &req, httplib::Response &res) {
  18466. res.set_content("PATCH:" + req.body, "text/plain");
  18467. });
  18468. svr_.Delete(
  18469. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18470. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18471. "text/plain");
  18472. });
  18473. svr_.Get("/head-test",
  18474. [](const httplib::Request &, httplib::Response &res) {
  18475. res.set_content("body for HEAD", "text/plain");
  18476. });
  18477. svr_.Options("/options",
  18478. [](const httplib::Request &, httplib::Response &res) {
  18479. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18480. });
  18481. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18482. svr_.wait_until_ready();
  18483. }
  18484. void TearDown() override {
  18485. svr_.stop();
  18486. if (thread_.joinable()) thread_.join();
  18487. }
  18488. httplib::Server svr_;
  18489. std::thread thread_;
  18490. };
  18491. // stream::Get tests
  18492. TEST_F(StreamApiTest, GetBasic) {
  18493. httplib::Client cli(HOST, PORT);
  18494. auto result = httplib::stream::Get(cli, "/hello");
  18495. ASSERT_TRUE(result.is_valid());
  18496. EXPECT_EQ(200, result.status());
  18497. EXPECT_EQ("Hello World!", read_body(result));
  18498. }
  18499. TEST_F(StreamApiTest, GetWithParams) {
  18500. httplib::Client cli(HOST, PORT);
  18501. httplib::Params params{{"foo", "bar"}};
  18502. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18503. ASSERT_TRUE(result.is_valid());
  18504. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18505. }
  18506. TEST_F(StreamApiTest, GetConnectionError) {
  18507. httplib::Client cli(HOST, 9999);
  18508. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18509. }
  18510. TEST_F(StreamApiTest, Get404) {
  18511. httplib::Client cli(HOST, PORT);
  18512. auto result = httplib::stream::Get(cli, "/nonexistent");
  18513. EXPECT_TRUE(result.is_valid());
  18514. EXPECT_EQ(404, result.status());
  18515. }
  18516. // stream::Post tests
  18517. TEST_F(StreamApiTest, PostBasic) {
  18518. httplib::Client cli(HOST, PORT);
  18519. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18520. "application/json");
  18521. ASSERT_TRUE(result.is_valid());
  18522. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18523. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18524. }
  18525. TEST_F(StreamApiTest, PostWithHeaders) {
  18526. httplib::Client cli(HOST, PORT);
  18527. httplib::Headers headers{{"X-Custom", "value"}};
  18528. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18529. "text/plain");
  18530. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18531. }
  18532. TEST_F(StreamApiTest, PostWithParams) {
  18533. httplib::Client cli(HOST, PORT);
  18534. httplib::Params params{{"k", "v"}};
  18535. auto result =
  18536. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18537. auto body = read_body(result);
  18538. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18539. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18540. }
  18541. TEST_F(StreamApiTest, PostLarge) {
  18542. httplib::Client cli(HOST, PORT);
  18543. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18544. size_t total = 0;
  18545. while (result.next()) {
  18546. total += result.size();
  18547. }
  18548. EXPECT_EQ(100u * 1024u, total);
  18549. }
  18550. // stream::Put/Patch tests
  18551. TEST_F(StreamApiTest, PutAndPatch) {
  18552. httplib::Client cli(HOST, PORT);
  18553. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18554. EXPECT_EQ("PUT:test", read_body(put));
  18555. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18556. EXPECT_EQ("PATCH:test", read_body(patch));
  18557. }
  18558. // stream::Delete tests
  18559. TEST_F(StreamApiTest, Delete) {
  18560. httplib::Client cli(HOST, PORT);
  18561. auto del1 = httplib::stream::Delete(cli, "/resource");
  18562. EXPECT_EQ("Deleted", read_body(del1));
  18563. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18564. EXPECT_EQ("Deleted:data", read_body(del2));
  18565. }
  18566. // stream::Head/Options tests
  18567. TEST_F(StreamApiTest, HeadAndOptions) {
  18568. httplib::Client cli(HOST, PORT);
  18569. auto head = httplib::stream::Head(cli, "/head-test");
  18570. EXPECT_TRUE(head.is_valid());
  18571. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18572. auto opts = httplib::stream::Options(cli, "/options");
  18573. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18574. }
  18575. // SSL stream::* tests
  18576. #ifdef CPPHTTPLIB_SSL_ENABLED
  18577. class SSLStreamApiTest : public ::testing::Test {
  18578. protected:
  18579. void SetUp() override {
  18580. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18581. res.set_content("Hello SSL!", "text/plain");
  18582. });
  18583. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18584. res.set_content(req.body, "text/plain");
  18585. });
  18586. port_ = svr_.bind_to_any_port("127.0.0.1");
  18587. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18588. svr_.wait_until_ready();
  18589. }
  18590. void TearDown() override {
  18591. svr_.stop();
  18592. if (thread_.joinable()) thread_.join();
  18593. }
  18594. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18595. std::thread thread_;
  18596. int port_ = 0;
  18597. };
  18598. TEST_F(SSLStreamApiTest, GetAndPost) {
  18599. httplib::SSLClient cli("127.0.0.1", port_);
  18600. cli.enable_server_certificate_verification(false);
  18601. auto get = httplib::stream::Get(cli, "/hello");
  18602. EXPECT_EQ("Hello SSL!", read_body(get));
  18603. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18604. EXPECT_EQ("test", read_body(post));
  18605. }
  18606. #endif
  18607. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18608. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18609. // BodyReader
  18610. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18611. // Test that read timeout during streaming is detected
  18612. // Use a large content-length response where server delays mid-stream
  18613. Server svr;
  18614. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18615. // Send a large response with delay in the middle
  18616. res.set_content_provider(
  18617. 1000, // content_length
  18618. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18619. if (offset < 100) {
  18620. // Send first 100 bytes immediately
  18621. std::string data(100, 'A');
  18622. sink.write(data.c_str(), data.size());
  18623. return true;
  18624. }
  18625. // Then delay longer than client timeout
  18626. std::this_thread::sleep_for(std::chrono::seconds(3));
  18627. std::string data(900, 'B');
  18628. sink.write(data.c_str(), data.size());
  18629. return true;
  18630. });
  18631. });
  18632. auto port = 8091;
  18633. std::thread t([&]() { svr.listen("localhost", port); });
  18634. svr.wait_until_ready();
  18635. Client cli("localhost", port);
  18636. cli.set_read_timeout(1, 0); // 1 second timeout
  18637. auto handle = cli.open_stream("GET", "/slow-stream");
  18638. ASSERT_TRUE(handle.is_valid());
  18639. char buf[256];
  18640. ssize_t total = 0;
  18641. ssize_t n;
  18642. bool got_error = false;
  18643. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18644. total += n;
  18645. }
  18646. if (n < 0) {
  18647. got_error = true;
  18648. // Should be timeout or read error
  18649. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18650. handle.get_read_error() == Error::Read)
  18651. << "Actual error: " << to_string(handle.get_read_error());
  18652. }
  18653. // Either we got an error, or we got less data than expected
  18654. EXPECT_TRUE(got_error || total < 1000)
  18655. << "Expected timeout but got all " << total << " bytes";
  18656. svr.stop();
  18657. t.join();
  18658. }
  18659. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18660. // Test connection closed detection via BodyReader
  18661. Server svr;
  18662. std::atomic<bool> close_now{false};
  18663. svr.Get("/will-close", [&](const Request &, Response &res) {
  18664. res.set_content_provider(
  18665. 10000, // Large content_length that we won't fully send
  18666. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18667. if (offset < 100) {
  18668. std::string data(100, 'X');
  18669. sink.write(data.c_str(), data.size());
  18670. return true;
  18671. }
  18672. // Wait for signal then abort
  18673. while (!close_now) {
  18674. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18675. }
  18676. return false; // Abort - server will close connection
  18677. });
  18678. });
  18679. auto port = 8092;
  18680. std::thread t([&]() { svr.listen("localhost", port); });
  18681. svr.wait_until_ready();
  18682. Client cli("localhost", port);
  18683. auto handle = cli.open_stream("GET", "/will-close");
  18684. ASSERT_TRUE(handle.is_valid());
  18685. char buf[256];
  18686. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18687. EXPECT_GT(n, 0) << "First read should succeed";
  18688. // Signal server to close
  18689. close_now = true;
  18690. // Keep reading until error or EOF
  18691. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18692. // Keep reading
  18693. }
  18694. // Should get an error since content_length wasn't satisfied
  18695. if (n < 0) {
  18696. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18697. handle.get_read_error() == Error::Read)
  18698. << "Actual error: " << to_string(handle.get_read_error());
  18699. }
  18700. svr.stop();
  18701. t.join();
  18702. }
  18703. #ifdef CPPHTTPLIB_SSL_ENABLED
  18704. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18705. // Test that read timeout during SSL streaming is detected
  18706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18707. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18708. res.set_content_provider(
  18709. 1000, "text/plain",
  18710. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18711. if (offset < 100) {
  18712. std::string data(100, 'A');
  18713. sink.write(data.c_str(), data.size());
  18714. return true;
  18715. }
  18716. std::this_thread::sleep_for(std::chrono::seconds(3));
  18717. std::string data(900, 'B');
  18718. sink.write(data.c_str(), data.size());
  18719. return true;
  18720. });
  18721. });
  18722. auto port = 8093;
  18723. std::thread t([&]() { svr.listen("localhost", port); });
  18724. svr.wait_until_ready();
  18725. SSLClient cli("localhost", port);
  18726. cli.enable_server_certificate_verification(false);
  18727. cli.set_read_timeout(1, 0); // 1 second timeout
  18728. auto handle = cli.open_stream("GET", "/slow-stream");
  18729. ASSERT_TRUE(handle.is_valid());
  18730. char buf[256];
  18731. ssize_t total = 0;
  18732. ssize_t n;
  18733. bool got_error = false;
  18734. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18735. total += n;
  18736. }
  18737. if (n < 0) {
  18738. got_error = true;
  18739. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18740. handle.get_read_error() == Error::Read)
  18741. << "Actual error: " << to_string(handle.get_read_error());
  18742. }
  18743. EXPECT_TRUE(got_error || total < 1000)
  18744. << "Expected timeout but got all " << total << " bytes";
  18745. svr.stop();
  18746. t.join();
  18747. }
  18748. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18749. // Test SSL connection closed detection
  18750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18751. std::atomic<bool> close_now{false};
  18752. svr.Get("/will-close", [&](const Request &, Response &res) {
  18753. res.set_content_provider(
  18754. 10000, "text/plain",
  18755. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18756. if (offset < 100) {
  18757. std::string data(100, 'X');
  18758. sink.write(data.c_str(), data.size());
  18759. return true;
  18760. }
  18761. while (!close_now) {
  18762. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18763. }
  18764. return false;
  18765. });
  18766. });
  18767. auto port = 8094;
  18768. std::thread t([&]() { svr.listen("localhost", port); });
  18769. svr.wait_until_ready();
  18770. SSLClient cli("localhost", port);
  18771. cli.enable_server_certificate_verification(false);
  18772. auto handle = cli.open_stream("GET", "/will-close");
  18773. ASSERT_TRUE(handle.is_valid());
  18774. char buf[256];
  18775. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18776. EXPECT_GT(n, 0);
  18777. // Signal server to close
  18778. close_now = true;
  18779. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18780. // Keep reading
  18781. }
  18782. if (n < 0) {
  18783. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18784. handle.get_read_error() == Error::Read)
  18785. << "Actual error: " << to_string(handle.get_read_error());
  18786. }
  18787. svr.stop();
  18788. t.join();
  18789. }
  18790. #endif
  18791. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18792. using namespace httplib;
  18793. // Create a test file
  18794. const char *fname = "etag_testfile.txt";
  18795. const char *content = "etag-content";
  18796. {
  18797. std::ofstream ofs(fname);
  18798. ofs << content;
  18799. ASSERT_TRUE(ofs.good());
  18800. }
  18801. Server svr;
  18802. svr.set_mount_point("/static", ".");
  18803. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18804. svr.wait_until_ready();
  18805. Client cli(HOST, PORT);
  18806. // First request: should get 200 with ETag header
  18807. auto res1 = cli.Get("/static/etag_testfile.txt");
  18808. ASSERT_TRUE(res1);
  18809. ASSERT_EQ(200, res1->status);
  18810. ASSERT_TRUE(res1->has_header("ETag"));
  18811. std::string etag = res1->get_header_value("ETag");
  18812. EXPECT_FALSE(etag.empty());
  18813. // Verify ETag format: W/"hex-hex"
  18814. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18815. EXPECT_EQ('W', etag[0]);
  18816. EXPECT_EQ('/', etag[1]);
  18817. EXPECT_EQ('"', etag[2]);
  18818. EXPECT_EQ('"', etag.back());
  18819. // Exact match: expect 304 Not Modified
  18820. Headers h2 = {{"If-None-Match", etag}};
  18821. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18822. ASSERT_TRUE(res2);
  18823. EXPECT_EQ(304, res2->status);
  18824. // Wildcard match: expect 304 Not Modified
  18825. Headers h3 = {{"If-None-Match", "*"}};
  18826. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18827. ASSERT_TRUE(res3);
  18828. EXPECT_EQ(304, res3->status);
  18829. // Non-matching ETag: expect 200
  18830. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18831. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18832. ASSERT_TRUE(res4);
  18833. EXPECT_EQ(200, res4->status);
  18834. // Multiple ETags with one matching: expect 304
  18835. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18836. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18837. ASSERT_TRUE(res5);
  18838. EXPECT_EQ(304, res5->status);
  18839. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18840. // that equivalent to the single comma-separated list above, so the match on
  18841. // the second line must still be found.
  18842. Headers h6;
  18843. h6.emplace("If-None-Match", "W/\"other\"");
  18844. h6.emplace("If-None-Match", etag);
  18845. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18846. ASSERT_TRUE(res6);
  18847. EXPECT_EQ(304, res6->status);
  18848. svr.stop();
  18849. t.join();
  18850. std::remove(fname);
  18851. }
  18852. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18853. using namespace httplib;
  18854. Server svr;
  18855. svr.set_mount_point("/static", ".");
  18856. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18857. svr.wait_until_ready();
  18858. Client cli(HOST, PORT);
  18859. // Send If-None-Match: * to a non-existent file
  18860. Headers h = {{"If-None-Match", "*"}};
  18861. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18863. EXPECT_EQ(404, res->status);
  18864. svr.stop();
  18865. t.join();
  18866. }
  18867. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18868. using namespace httplib;
  18869. // Create a test file
  18870. const char *fname = "etag_boundary_testfile.txt";
  18871. const char *content = "boundary-test";
  18872. {
  18873. std::ofstream ofs(fname);
  18874. ofs << content;
  18875. ASSERT_TRUE(ofs.good());
  18876. }
  18877. Server svr;
  18878. svr.set_mount_point("/static", ".");
  18879. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18880. svr.wait_until_ready();
  18881. Client cli(HOST, PORT);
  18882. // Get the actual ETag
  18883. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18884. ASSERT_TRUE(res1);
  18885. ASSERT_EQ(200, res1->status);
  18886. ASSERT_TRUE(res1->has_header("ETag"));
  18887. std::string etag = res1->get_header_value("ETag");
  18888. // Test 1: Very long ETag value (longer than actual ETag)
  18889. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18890. Headers h1 = {{"If-None-Match", "W/"
  18891. "\"very-long-etag-value-that-is-much-longer-"
  18892. "than-the-actual-etag-value\""}};
  18893. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18894. ASSERT_TRUE(res2);
  18895. EXPECT_EQ(200, res2->status); // Should not match
  18896. // Test 2: Long string followed by wildcard
  18897. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18898. // string)
  18899. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18900. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18901. ASSERT_TRUE(res3);
  18902. EXPECT_EQ(304, res3->status); // Should match on "*"
  18903. // Test 3: Wildcard followed by long string
  18904. // Should match on "*" immediately and return 304
  18905. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18906. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18907. ASSERT_TRUE(res4);
  18908. EXPECT_EQ(304, res4->status); // Should match on "*"
  18909. // Test 4: Multiple long non-matching values
  18910. // Should NOT match and return 200 (test that all comparisons are safe)
  18911. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18912. "W/\"second-long-non-matching-value\", "
  18913. "W/\"third-long-non-matching-value\""}};
  18914. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18915. ASSERT_TRUE(res5);
  18916. EXPECT_EQ(200, res5->status); // Should not match
  18917. // Test 5: Single character that is not "*" (edge case)
  18918. Headers h5 = {{"If-None-Match", "X"}};
  18919. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18920. ASSERT_TRUE(res6);
  18921. EXPECT_EQ(200, res6->status); // Should not match
  18922. svr.stop();
  18923. t.join();
  18924. std::remove(fname);
  18925. }
  18926. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18927. using namespace httplib;
  18928. // Create a test file
  18929. const char *fname = "ims_testfile.txt";
  18930. const char *content = "if-modified-since-test";
  18931. {
  18932. std::ofstream ofs(fname);
  18933. ofs << content;
  18934. ASSERT_TRUE(ofs.good());
  18935. }
  18936. Server svr;
  18937. svr.set_mount_point("/static", ".");
  18938. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18939. svr.wait_until_ready();
  18940. Client cli(HOST, PORT);
  18941. // First request: should get 200 with Last-Modified header
  18942. auto res1 = cli.Get("/static/ims_testfile.txt");
  18943. ASSERT_TRUE(res1);
  18944. ASSERT_EQ(200, res1->status);
  18945. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18946. std::string last_modified = res1->get_header_value("Last-Modified");
  18947. EXPECT_FALSE(last_modified.empty());
  18948. // If-Modified-Since with same time: expect 304
  18949. Headers h2 = {{"If-Modified-Since", last_modified}};
  18950. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18951. ASSERT_TRUE(res2);
  18952. EXPECT_EQ(304, res2->status);
  18953. // If-Modified-Since with future time: expect 304
  18954. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18955. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18956. ASSERT_TRUE(res3);
  18957. EXPECT_EQ(304, res3->status);
  18958. // If-Modified-Since with past time: expect 200
  18959. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18960. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18961. ASSERT_TRUE(res4);
  18962. EXPECT_EQ(200, res4->status);
  18963. // If-None-Match takes precedence over If-Modified-Since
  18964. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18965. ASSERT_TRUE(res1->has_header("ETag"));
  18966. std::string etag = res1->get_header_value("ETag");
  18967. Headers h5 = {{"If-None-Match", etag},
  18968. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18969. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18970. ASSERT_TRUE(res5);
  18971. EXPECT_EQ(304, res5->status);
  18972. svr.stop();
  18973. t.join();
  18974. std::remove(fname);
  18975. }
  18976. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18977. using namespace httplib;
  18978. Server svr;
  18979. // Endpoint that returns compressible content
  18980. svr.Get("/compressible", [](const Request &, Response &res) {
  18981. // Return a large enough body to trigger compression
  18982. std::string body(1000, 'a');
  18983. res.set_content(body, "text/plain");
  18984. });
  18985. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18986. svr.wait_until_ready();
  18987. Client cli(HOST, PORT);
  18988. // Request with gzip support: should get Vary header when compressed
  18989. cli.set_compress(true);
  18990. auto res1 = cli.Get("/compressible");
  18991. ASSERT_TRUE(res1);
  18992. EXPECT_EQ(200, res1->status);
  18993. // If Content-Encoding is set, Vary should also be set
  18994. if (res1->has_header("Content-Encoding")) {
  18995. EXPECT_TRUE(res1->has_header("Vary"));
  18996. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18997. }
  18998. // Request without Accept-Encoding header: should not have compression
  18999. Headers h_no_compress;
  19000. auto res2 = cli.Get("/compressible", h_no_compress);
  19001. ASSERT_TRUE(res2);
  19002. EXPECT_EQ(200, res2->status);
  19003. // Verify Vary header is present when compression is applied
  19004. // (the exact behavior depends on server configuration)
  19005. svr.stop();
  19006. t.join();
  19007. }
  19008. TEST(ETagTest, IfRangeWithETag) {
  19009. using namespace httplib;
  19010. // Create a test file with known content
  19011. const char *fname = "if_range_testfile.txt";
  19012. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19013. {
  19014. std::ofstream ofs(fname);
  19015. ofs << content;
  19016. ASSERT_TRUE(ofs.good());
  19017. }
  19018. Server svr;
  19019. svr.set_mount_point("/static", ".");
  19020. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19021. svr.wait_until_ready();
  19022. Client cli(HOST, PORT);
  19023. // First request: get ETag
  19024. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19025. ASSERT_TRUE(res1);
  19026. ASSERT_EQ(200, res1->status);
  19027. ASSERT_TRUE(res1->has_header("ETag"));
  19028. std::string etag = res1->get_header_value("ETag");
  19029. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19030. // Since our server generates weak ETags (W/"..."), If-Range with our
  19031. // ETag should NOT result in partial content - it should return full content.
  19032. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19033. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19034. ASSERT_TRUE(res2);
  19035. // Weak ETag in If-Range -> full content (200), not partial (206)
  19036. EXPECT_EQ(200, res2->status);
  19037. EXPECT_EQ(content, res2->body);
  19038. EXPECT_FALSE(res2->has_header("Content-Range"));
  19039. // Range request with non-matching If-Range (ETag): should get 200 (full
  19040. // content)
  19041. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19042. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19043. ASSERT_TRUE(res3);
  19044. EXPECT_EQ(200, res3->status);
  19045. EXPECT_EQ(content, res3->body);
  19046. EXPECT_FALSE(res3->has_header("Content-Range"));
  19047. // Range request with strong ETag (hypothetical - our server doesn't generate
  19048. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19049. // should return full content)
  19050. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19051. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19052. ASSERT_TRUE(res4);
  19053. EXPECT_EQ(200, res4->status);
  19054. EXPECT_EQ(content, res4->body);
  19055. EXPECT_FALSE(res4->has_header("Content-Range"));
  19056. svr.stop();
  19057. t.join();
  19058. std::remove(fname);
  19059. }
  19060. TEST(ETagTest, IfRangeWithDate) {
  19061. using namespace httplib;
  19062. // Create a test file
  19063. const char *fname = "if_range_date_testfile.txt";
  19064. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19065. {
  19066. std::ofstream ofs(fname);
  19067. ofs << content;
  19068. ASSERT_TRUE(ofs.good());
  19069. }
  19070. Server svr;
  19071. svr.set_mount_point("/static", ".");
  19072. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19073. svr.wait_until_ready();
  19074. Client cli(HOST, PORT);
  19075. // First request: get Last-Modified
  19076. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19077. ASSERT_TRUE(res1);
  19078. ASSERT_EQ(200, res1->status);
  19079. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19080. std::string last_modified = res1->get_header_value("Last-Modified");
  19081. // Range request with matching If-Range (date): should get 206
  19082. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19083. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19084. ASSERT_TRUE(res2);
  19085. EXPECT_EQ(206, res2->status);
  19086. EXPECT_EQ("FGHIJ", res2->body);
  19087. // Range request with old If-Range date: should get 200 (full content)
  19088. Headers h3 = {{"Range", "bytes=5-9"},
  19089. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19090. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19091. ASSERT_TRUE(res3);
  19092. EXPECT_EQ(200, res3->status);
  19093. EXPECT_EQ(content, res3->body);
  19094. // Range request with future If-Range date: should get 206
  19095. Headers h4 = {{"Range", "bytes=0-4"},
  19096. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19097. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19098. ASSERT_TRUE(res4);
  19099. EXPECT_EQ(206, res4->status);
  19100. EXPECT_EQ("ABCDE", res4->body);
  19101. svr.stop();
  19102. t.join();
  19103. std::remove(fname);
  19104. }
  19105. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19106. using namespace httplib;
  19107. const char *fname = "etag_malformed.txt";
  19108. const char *content = "malformed-etag";
  19109. {
  19110. std::ofstream ofs(fname);
  19111. ofs << content;
  19112. ASSERT_TRUE(ofs.good());
  19113. }
  19114. Server svr;
  19115. svr.set_mount_point("/static", ".");
  19116. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19117. svr.wait_until_ready();
  19118. Client cli(HOST, PORT);
  19119. // baseline: should get 200 and an ETag
  19120. auto res1 = cli.Get("/static/etag_malformed.txt");
  19121. ASSERT_TRUE(res1);
  19122. ASSERT_EQ(200, res1->status);
  19123. ASSERT_TRUE(res1->has_header("ETag"));
  19124. // Malformed ETag value (missing quotes) should be treated as non-matching
  19125. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19126. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19127. ASSERT_TRUE(res_bad);
  19128. EXPECT_EQ(200, res_bad->status);
  19129. // Whitespace-only header value should be considered invalid / non-matching
  19130. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19131. "Host: localhost\r\n"
  19132. "If-None-Match: \r\n"
  19133. "Connection: close\r\n"
  19134. "\r\n";
  19135. std::string out;
  19136. ASSERT_TRUE(send_request(5, raw_req, &out));
  19137. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19138. svr.stop();
  19139. t.join();
  19140. std::remove(fname);
  19141. }
  19142. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19143. using namespace httplib;
  19144. const char *fname = "ims_invalid_format.txt";
  19145. const char *content = "ims-bad-format";
  19146. {
  19147. std::ofstream ofs(fname);
  19148. ofs << content;
  19149. ASSERT_TRUE(ofs.good());
  19150. }
  19151. Server svr;
  19152. svr.set_mount_point("/static", ".");
  19153. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19154. svr.wait_until_ready();
  19155. Client cli(HOST, PORT);
  19156. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19157. ASSERT_TRUE(res1);
  19158. ASSERT_EQ(200, res1->status);
  19159. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19160. // If-Modified-Since with invalid format should not result in 304
  19161. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19162. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19163. ASSERT_TRUE(res_bad);
  19164. EXPECT_EQ(200, res_bad->status);
  19165. // If-Range with invalid date format should be treated as mismatch -> full
  19166. // content (200)
  19167. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19168. {"If-Range", "invalid-date"}};
  19169. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19170. ASSERT_TRUE(res_ifrange);
  19171. EXPECT_EQ(200, res_ifrange->status);
  19172. svr.stop();
  19173. t.join();
  19174. std::remove(fname);
  19175. }
  19176. TEST(ETagTest, IfRangeWithMalformedETag) {
  19177. using namespace httplib;
  19178. const char *fname = "ifrange_malformed.txt";
  19179. const std::string content = "0123456789";
  19180. {
  19181. std::ofstream ofs(fname);
  19182. ofs << content;
  19183. ASSERT_TRUE(ofs.good());
  19184. }
  19185. Server svr;
  19186. svr.set_mount_point("/static", ".");
  19187. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19188. svr.wait_until_ready();
  19189. Client cli(HOST, PORT);
  19190. // First request: get ETag
  19191. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19192. ASSERT_TRUE(res1);
  19193. ASSERT_EQ(200, res1->status);
  19194. ASSERT_TRUE(res1->has_header("ETag"));
  19195. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19196. // full content (200)
  19197. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19198. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19199. ASSERT_TRUE(res2);
  19200. EXPECT_EQ(200, res2->status);
  19201. EXPECT_EQ(content, res2->body);
  19202. svr.stop();
  19203. t.join();
  19204. std::remove(fname);
  19205. }
  19206. TEST(ETagTest, ExtremeLargeDateValues) {
  19207. using namespace httplib;
  19208. const char *fname = "ims_extreme_date.txt";
  19209. const char *content = "ims-extreme-date";
  19210. {
  19211. std::ofstream ofs(fname);
  19212. ofs << content;
  19213. ASSERT_TRUE(ofs.good());
  19214. }
  19215. Server svr;
  19216. svr.set_mount_point("/static", ".");
  19217. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19218. svr.wait_until_ready();
  19219. Client cli(HOST, PORT);
  19220. auto res1 = cli.Get(std::string("/static/") + fname);
  19221. ASSERT_TRUE(res1);
  19222. ASSERT_EQ(200, res1->status);
  19223. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19224. // Extremely large year that may overflow date parsing routines.
  19225. Headers h_large_date = {
  19226. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19227. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19228. ASSERT_TRUE(res_bad);
  19229. // Expect server to treat this as invalid/mismatch and return full content
  19230. EXPECT_EQ(200, res_bad->status);
  19231. // If-Range with extremely large date should be treated as mismatch -> full
  19232. // content (200)
  19233. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19234. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19235. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19236. ASSERT_TRUE(res_ifrange);
  19237. EXPECT_EQ(200, res_ifrange->status);
  19238. svr.stop();
  19239. t.join();
  19240. std::remove(fname);
  19241. }
  19242. TEST(ETagTest, NegativeFileModificationTime) {
  19243. using namespace httplib;
  19244. const char *fname = "ims_negative_mtime.txt";
  19245. const std::string content = "negative-mtime";
  19246. {
  19247. std::ofstream ofs(fname);
  19248. ofs << content;
  19249. ASSERT_TRUE(ofs.good());
  19250. }
  19251. // Try to set file mtime to a negative value. This may fail on some
  19252. // platforms/filesystems; if it fails, the test will still verify server
  19253. // behaves safely by performing a regular conditional request.
  19254. #if defined(__APPLE__) || defined(__linux__)
  19255. bool set_negative = false;
  19256. do {
  19257. struct timeval times[2];
  19258. // access time: now
  19259. times[0].tv_sec = time(nullptr);
  19260. times[0].tv_usec = 0;
  19261. // modification time: negative (e.g., -1)
  19262. times[1].tv_sec = -1;
  19263. times[1].tv_usec = 0;
  19264. if (utimes(fname, times) == 0) { set_negative = true; }
  19265. } while (0);
  19266. #else
  19267. bool set_negative = false;
  19268. #endif
  19269. Server svr;
  19270. svr.set_mount_point("/static", ".");
  19271. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19272. svr.wait_until_ready();
  19273. Client cli(HOST, PORT);
  19274. auto res1 = cli.Get(std::string("/static/") + fname);
  19275. ASSERT_TRUE(res1);
  19276. ASSERT_EQ(200, res1->status);
  19277. bool has_last_modified = res1->has_header("Last-Modified");
  19278. std::string last_modified;
  19279. if (has_last_modified) {
  19280. last_modified = res1->get_header_value("Last-Modified");
  19281. }
  19282. if (set_negative) {
  19283. // If we successfully set a negative mtime, ensure server returns a
  19284. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19285. // with an old date and ensure server handles it without crash.
  19286. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19287. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19288. ASSERT_TRUE(res2);
  19289. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19290. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19291. } else {
  19292. // Could not set negative mtime on this platform; fall back to verifying
  19293. // that normal invalid/malformed dates are treated safely (non-304).
  19294. Headers h_bad_date = {
  19295. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19296. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19297. ASSERT_TRUE(res_bad);
  19298. EXPECT_EQ(200, res_bad->status);
  19299. }
  19300. svr.stop();
  19301. t.join();
  19302. std::remove(fname);
  19303. }
  19304. //==============================================================================
  19305. // Integration Tests with Server
  19306. //==============================================================================
  19307. class SSEIntegrationTest : public ::testing::Test {
  19308. protected:
  19309. void SetUp() override {
  19310. stop_server_.store(false);
  19311. events_.clear();
  19312. server_ = httplib::detail::make_unique<Server>();
  19313. setup_server();
  19314. start_server();
  19315. }
  19316. void TearDown() override {
  19317. stop_server_.store(true);
  19318. event_cv_.notify_all();
  19319. server_->stop();
  19320. if (server_thread_.joinable()) { server_thread_.join(); }
  19321. }
  19322. void setup_server() {
  19323. // Simple SSE endpoint
  19324. server_->Get("/events", [this](const Request &req, Response &res) {
  19325. auto last_id = req.get_header_value("Last-Event-ID");
  19326. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19327. res.set_chunked_content_provider(
  19328. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19329. std::unique_lock<std::mutex> lock(event_mutex_);
  19330. if (event_cv_.wait_for(
  19331. lock, std::chrono::milliseconds(200), [this] {
  19332. return !events_.empty() || stop_server_.load();
  19333. })) {
  19334. if (stop_server_.load()) { return false; }
  19335. if (!events_.empty()) {
  19336. std::string event = events_.front();
  19337. events_.erase(events_.begin());
  19338. sink.write(event.data(), event.size());
  19339. return true;
  19340. }
  19341. }
  19342. return !stop_server_.load();
  19343. });
  19344. });
  19345. // Endpoint that returns error
  19346. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19347. res.status = 500;
  19348. res.set_content("Internal Server Error", "text/plain");
  19349. });
  19350. // Endpoint for custom event types
  19351. server_->Get("/custom-events", [](const Request &, Response &res) {
  19352. res.set_chunked_content_provider(
  19353. "text/event-stream", [](size_t offset, DataSink &sink) {
  19354. if (offset == 0) {
  19355. std::string event = "event: update\ndata: updated\n\n"
  19356. "event: delete\ndata: deleted\n\n";
  19357. sink.write(event.data(), event.size());
  19358. }
  19359. return false; // End stream after sending
  19360. });
  19361. });
  19362. }
  19363. void start_server() {
  19364. port_ = server_->bind_to_any_port(HOST);
  19365. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19366. // Wait for server to start
  19367. while (!server_->is_running()) {
  19368. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19369. }
  19370. }
  19371. int get_port() const { return port_; }
  19372. void send_event(const std::string &event) {
  19373. std::lock_guard<std::mutex> lock(event_mutex_);
  19374. events_.push_back(event);
  19375. event_cv_.notify_all();
  19376. }
  19377. std::unique_ptr<Server> server_;
  19378. std::thread server_thread_;
  19379. std::mutex event_mutex_;
  19380. std::condition_variable event_cv_;
  19381. std::vector<std::string> events_;
  19382. std::atomic<bool> stop_server_{false};
  19383. std::string last_received_event_id_;
  19384. int port_ = 0;
  19385. };
  19386. //==============================================================================
  19387. // SSE Parsing Tests
  19388. //==============================================================================
  19389. class SSEParsingTest : public SSEIntegrationTest {
  19390. protected:
  19391. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19392. // A trailing sentinel event tells when the whole stream has been parsed.
  19393. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19394. auto body = stream + "event: end\ndata: end\n\n";
  19395. server_->Get("/parse", [body](const Request &, Response &res) {
  19396. res.set_content(body, "text/event-stream");
  19397. });
  19398. return collect("/parse");
  19399. }
  19400. // Runs SSEClient against path until an "end" event arrives and returns the
  19401. // messages dispatched before it
  19402. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19403. Client client(HOST, get_port());
  19404. sse::SSEClient sse(client, path);
  19405. std::mutex mutex;
  19406. std::condition_variable cv;
  19407. std::vector<sse::SSEMessage> messages;
  19408. auto done = false;
  19409. sse.on_message([&](const sse::SSEMessage &msg) {
  19410. std::lock_guard<std::mutex> lock(mutex);
  19411. // Ignore a replay from a reconnect that races with stop()
  19412. if (!done) { messages.push_back(msg); }
  19413. });
  19414. sse.on_event("end", [&](const sse::SSEMessage &) {
  19415. std::lock_guard<std::mutex> lock(mutex);
  19416. done = true;
  19417. cv.notify_all();
  19418. });
  19419. sse.set_reconnect_interval(100);
  19420. sse.start_async();
  19421. {
  19422. std::unique_lock<std::mutex> lock(mutex);
  19423. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19424. }
  19425. sse.stop();
  19426. EXPECT_TRUE(done);
  19427. return messages;
  19428. }
  19429. };
  19430. TEST_F(SSEParsingTest, SingleLineData) {
  19431. auto msgs = parse("data: hello\n\n");
  19432. ASSERT_EQ(msgs.size(), 1u);
  19433. EXPECT_EQ(msgs[0].data, "hello");
  19434. EXPECT_EQ(msgs[0].event, "message");
  19435. }
  19436. TEST_F(SSEParsingTest, MultiLineData) {
  19437. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19438. ASSERT_EQ(msgs.size(), 1u);
  19439. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19440. }
  19441. TEST_F(SSEParsingTest, CustomEventType) {
  19442. auto msgs = parse("event: update\ndata: payload\n\n");
  19443. ASSERT_EQ(msgs.size(), 1u);
  19444. EXPECT_EQ(msgs[0].event, "update");
  19445. EXPECT_EQ(msgs[0].data, "payload");
  19446. }
  19447. TEST_F(SSEParsingTest, EventIdHandling) {
  19448. auto msgs = parse("id: 12345\ndata: test\n\n");
  19449. ASSERT_EQ(msgs.size(), 1u);
  19450. EXPECT_EQ(msgs[0].id, "12345");
  19451. }
  19452. TEST_F(SSEParsingTest, EmptyEventId) {
  19453. auto msgs = parse("id:\ndata: test\n\n");
  19454. ASSERT_EQ(msgs.size(), 1u);
  19455. EXPECT_EQ(msgs[0].id, "");
  19456. }
  19457. TEST_F(SSEParsingTest, CommentsIgnored) {
  19458. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19459. ASSERT_EQ(msgs.size(), 1u);
  19460. EXPECT_EQ(msgs[0].data, "hello");
  19461. EXPECT_EQ(msgs[0].event, "message");
  19462. }
  19463. TEST_F(SSEParsingTest, ColonInValue) {
  19464. auto msgs = parse("data: hello:world:test\n\n");
  19465. ASSERT_EQ(msgs.size(), 1u);
  19466. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19467. }
  19468. TEST_F(SSEParsingTest, FieldNameOnly) {
  19469. // A line without a colon is a field name with an empty value
  19470. auto msgs = parse("data\n\n");
  19471. ASSERT_EQ(msgs.size(), 1u);
  19472. EXPECT_EQ(msgs[0].data, "");
  19473. }
  19474. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19475. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19476. ASSERT_EQ(msgs.size(), 1u);
  19477. EXPECT_EQ(msgs[0].event, "update");
  19478. EXPECT_EQ(msgs[0].data, "hello");
  19479. }
  19480. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19481. auto msgs = parse("data\r\n\r\n");
  19482. ASSERT_EQ(msgs.size(), 1u);
  19483. EXPECT_EQ(msgs[0].data, "");
  19484. }
  19485. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19486. auto msgs = parse("event: update\rdata: hello\r\r");
  19487. ASSERT_EQ(msgs.size(), 1u);
  19488. EXPECT_EQ(msgs[0].event, "update");
  19489. EXPECT_EQ(msgs[0].data, "hello");
  19490. }
  19491. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19492. // Chunk boundaries fall inside every \r\n and right before the first one
  19493. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19494. "\n\r", "\nevent: end\ndata: end\n\n"};
  19495. server_->Get("/split", [chunks](const Request &, Response &res) {
  19496. auto i = std::make_shared<size_t>(0);
  19497. res.set_chunked_content_provider(
  19498. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19499. if (*i == chunks.size()) {
  19500. sink.done();
  19501. } else {
  19502. sink.write(chunks[*i].data(), chunks[*i].size());
  19503. (*i)++;
  19504. }
  19505. return true;
  19506. });
  19507. });
  19508. auto msgs = collect("/split");
  19509. ASSERT_EQ(msgs.size(), 1u);
  19510. EXPECT_EQ(msgs[0].event, "update");
  19511. EXPECT_EQ(msgs[0].data, "hello");
  19512. }
  19513. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19514. // Only a BOM at the start of the stream is ignored
  19515. auto msgs = parse("\xEF\xBB\xBF"
  19516. "data: first\n\n"
  19517. "\xEF\xBB\xBF"
  19518. "data: second\n\n");
  19519. ASSERT_EQ(msgs.size(), 1u);
  19520. EXPECT_EQ(msgs[0].data, "first");
  19521. }
  19522. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19523. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19524. ASSERT_EQ(msgs.size(), 1u);
  19525. EXPECT_EQ(msgs[0].data, "hello");
  19526. EXPECT_EQ(msgs[0].event, "message");
  19527. }
  19528. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19529. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19530. ASSERT_EQ(msgs.size(), 2u);
  19531. EXPECT_EQ(msgs[0].data, "hello");
  19532. EXPECT_EQ(msgs[1].data, "hello");
  19533. }
  19534. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19535. // An event without data is not dispatched, and its type must not leak
  19536. // into the next event
  19537. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19538. ASSERT_EQ(msgs.size(), 1u);
  19539. EXPECT_EQ(msgs[0].event, "message");
  19540. EXPECT_EQ(msgs[0].data, "hello");
  19541. }
  19542. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19543. // The first connection sends only an id; the second echoes back the
  19544. // Last-Event-ID it was reconnected with
  19545. std::atomic<int> connection_count{0};
  19546. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19547. if (connection_count++ == 0) {
  19548. res.set_content("id: 42\n\n", "text/event-stream");
  19549. } else {
  19550. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19551. "\n\nevent: end\ndata: end\n\n",
  19552. "text/event-stream");
  19553. }
  19554. });
  19555. auto msgs = collect("/id-only");
  19556. ASSERT_EQ(msgs.size(), 1u);
  19557. EXPECT_EQ(msgs[0].data, "42");
  19558. }
  19559. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19560. // The first connection sets an id and then clears it with an empty one; the
  19561. // second reports whether it was reconnected with a Last-Event-ID
  19562. std::atomic<int> connection_count{0};
  19563. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19564. if (connection_count++ == 0) {
  19565. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19566. "text/event-stream");
  19567. } else {
  19568. res.set_content(
  19569. std::string("data: ") +
  19570. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19571. "\n\nevent: end\ndata: end\n\n",
  19572. "text/event-stream");
  19573. }
  19574. });
  19575. auto msgs = collect("/id-clear");
  19576. ASSERT_EQ(msgs.size(), 3u);
  19577. EXPECT_EQ(msgs[0].id, "1");
  19578. EXPECT_EQ(msgs[1].id, "");
  19579. EXPECT_EQ(msgs[2].data, "not sent");
  19580. }
  19581. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19582. // The first connection sets an id and then sends ids that cannot be carried
  19583. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19584. // with
  19585. std::atomic<int> connection_count{0};
  19586. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19587. if (connection_count++ == 0) {
  19588. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19589. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19590. "text/event-stream");
  19591. } else {
  19592. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19593. "\n\nevent: end\ndata: end\n\n",
  19594. "text/event-stream");
  19595. }
  19596. });
  19597. auto msgs = collect("/id-unsendable");
  19598. ASSERT_EQ(msgs.size(), 1u);
  19599. EXPECT_EQ(msgs[0].data, "42");
  19600. }
  19601. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19602. auto msgs = parse("event: notification\nid: evt-42\n"
  19603. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19604. ASSERT_EQ(msgs.size(), 1u);
  19605. EXPECT_EQ(msgs[0].event, "notification");
  19606. EXPECT_EQ(msgs[0].id, "evt-42");
  19607. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19608. }
  19609. TEST(SSEMessageTest, Clear) {
  19610. sse::SSEMessage msg;
  19611. msg.event = "custom";
  19612. msg.data = "some data";
  19613. msg.id = "123";
  19614. msg.clear();
  19615. EXPECT_EQ(msg.event, "message");
  19616. EXPECT_EQ(msg.data, "");
  19617. EXPECT_EQ(msg.id, "");
  19618. }
  19619. //==============================================================================
  19620. // SSE Integration Tests
  19621. //==============================================================================
  19622. // Test: Successful connection and on_open callback
  19623. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19624. // Add a simple endpoint that sends one event and closes
  19625. server_->Get("/simple-event", [](const Request &, Response &res) {
  19626. res.set_chunked_content_provider(
  19627. "text/event-stream", [](size_t offset, DataSink &sink) {
  19628. if (offset == 0) {
  19629. std::string event = "data: hello\n\n";
  19630. sink.write(event.data(), event.size());
  19631. }
  19632. return false; // Close stream after sending
  19633. });
  19634. });
  19635. Client client("localhost", get_port());
  19636. sse::SSEClient sse(client, "/simple-event");
  19637. std::atomic<bool> open_called{false};
  19638. std::atomic<bool> message_received{false};
  19639. sse.on_open([&open_called]() { open_called.store(true); });
  19640. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19641. if (msg.data == "hello") { message_received.store(true); }
  19642. });
  19643. sse.set_reconnect_interval(100);
  19644. sse.set_max_reconnect_attempts(1);
  19645. // Start async
  19646. sse.start_async();
  19647. // Wait for message to be processed
  19648. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19649. sse.stop();
  19650. EXPECT_TRUE(open_called.load());
  19651. EXPECT_TRUE(message_received.load());
  19652. }
  19653. // Test: on_message callback
  19654. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19655. // Endpoint that sends multiple events then closes
  19656. server_->Get("/multi-event", [](const Request &, Response &res) {
  19657. res.set_chunked_content_provider(
  19658. "text/event-stream", [](size_t offset, DataSink &sink) {
  19659. if (offset == 0) {
  19660. std::string events = "data: message1\n\ndata: message2\n\n";
  19661. sink.write(events.data(), events.size());
  19662. }
  19663. return false;
  19664. });
  19665. });
  19666. Client client("localhost", get_port());
  19667. sse::SSEClient sse(client, "/multi-event");
  19668. std::vector<std::string> received_messages;
  19669. std::mutex messages_mutex;
  19670. sse.on_message([&](const sse::SSEMessage &msg) {
  19671. std::lock_guard<std::mutex> lock(messages_mutex);
  19672. received_messages.push_back(msg.data);
  19673. });
  19674. sse.set_reconnect_interval(100);
  19675. sse.set_max_reconnect_attempts(1);
  19676. sse.start_async();
  19677. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19678. sse.stop();
  19679. std::lock_guard<std::mutex> lock(messages_mutex);
  19680. EXPECT_GE(received_messages.size(), 2u);
  19681. if (received_messages.size() >= 2) {
  19682. EXPECT_EQ(received_messages[0], "message1");
  19683. EXPECT_EQ(received_messages[1], "message2");
  19684. }
  19685. }
  19686. // Test: on_event for specific types
  19687. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19688. Client client("localhost", get_port());
  19689. sse::SSEClient sse(client, "/custom-events");
  19690. std::atomic<bool> update_received{false};
  19691. std::atomic<bool> delete_received{false};
  19692. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19693. if (msg.data == "updated") { update_received.store(true); }
  19694. });
  19695. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19696. if (msg.data == "deleted") { delete_received.store(true); }
  19697. });
  19698. sse.set_max_reconnect_attempts(1);
  19699. sse.start_async();
  19700. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19701. sse.stop();
  19702. EXPECT_TRUE(update_received.load());
  19703. EXPECT_TRUE(delete_received.load());
  19704. }
  19705. // Test: on_error callback on connection failure
  19706. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19707. // Connect to a non-existent port
  19708. Client client("localhost", 59999);
  19709. sse::SSEClient sse(client, "/events");
  19710. std::atomic<bool> error_called{false};
  19711. Error received_error = Error::Success;
  19712. sse.on_error([&](Error err) {
  19713. error_called.store(true);
  19714. received_error = err;
  19715. });
  19716. sse.set_reconnect_interval(50);
  19717. sse.set_max_reconnect_attempts(1);
  19718. sse.start_async();
  19719. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19720. sse.stop();
  19721. EXPECT_TRUE(error_called.load());
  19722. EXPECT_NE(received_error, Error::Success);
  19723. }
  19724. // Test: Last-Event-ID header sent on reconnect
  19725. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19726. // Endpoint that sends event with ID
  19727. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19728. res.set_chunked_content_provider(
  19729. "text/event-stream", [](size_t offset, DataSink &sink) {
  19730. if (offset == 0) {
  19731. std::string event = "id: evt-123\ndata: test\n\n";
  19732. sink.write(event.data(), event.size());
  19733. }
  19734. return false;
  19735. });
  19736. });
  19737. Client client("localhost", get_port());
  19738. sse::SSEClient sse(client, "/event-with-id");
  19739. std::atomic<bool> id_received{false};
  19740. sse.on_message([&](const sse::SSEMessage &msg) {
  19741. if (!msg.id.empty()) { id_received.store(true); }
  19742. });
  19743. sse.set_reconnect_interval(100);
  19744. sse.set_max_reconnect_attempts(1);
  19745. sse.start_async();
  19746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19747. sse.stop();
  19748. EXPECT_TRUE(id_received.load());
  19749. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19750. }
  19751. // Test: Manual stop
  19752. TEST_F(SSEIntegrationTest, ManualStop) {
  19753. // Endpoint that sends one event and stays open briefly
  19754. std::atomic<bool> handler_running{true};
  19755. server_->Get("/stay-open", [&handler_running](const Request &,
  19756. Response &res) {
  19757. res.set_chunked_content_provider(
  19758. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19759. if (offset == 0) {
  19760. std::string event = "data: connected\n\n";
  19761. sink.write(event.data(), event.size());
  19762. }
  19763. // Keep connection open while handler_running is true
  19764. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19765. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19766. }
  19767. return false;
  19768. });
  19769. });
  19770. Client client("localhost", get_port());
  19771. sse::SSEClient sse(client, "/stay-open");
  19772. std::atomic<bool> connected{false};
  19773. sse.on_open([&connected]() { connected.store(true); });
  19774. sse.set_reconnect_interval(100);
  19775. sse.set_max_reconnect_attempts(1);
  19776. sse.start_async();
  19777. // Wait for connection to establish
  19778. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19779. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19780. }
  19781. EXPECT_TRUE(connected.load());
  19782. EXPECT_TRUE(sse.is_connected());
  19783. // Signal handler to stop
  19784. handler_running.store(false);
  19785. // Stop SSE client
  19786. sse.stop();
  19787. EXPECT_FALSE(sse.is_connected());
  19788. }
  19789. // Test: SSEClient with custom headers
  19790. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19791. // Setup a server endpoint that checks for custom header
  19792. std::atomic<bool> header_received{false};
  19793. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19794. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19795. header_received.store(true);
  19796. }
  19797. res.set_chunked_content_provider("text/event-stream",
  19798. [](size_t, DataSink &) { return false; });
  19799. });
  19800. Client client("localhost", get_port());
  19801. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19802. sse::SSEClient sse(client, "/header-check", headers);
  19803. sse.set_max_reconnect_attempts(1);
  19804. sse.start_async();
  19805. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19806. sse.stop();
  19807. EXPECT_TRUE(header_received.load());
  19808. }
  19809. // Test: Reconnect interval configuration
  19810. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19811. Client client("localhost", get_port());
  19812. sse::SSEClient sse(client, "/events");
  19813. auto &result = sse.set_reconnect_interval(500);
  19814. // Builder pattern should return reference to self
  19815. EXPECT_EQ(&result, &sse);
  19816. }
  19817. // Test: Max reconnect attempts
  19818. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19819. // Connect to non-existent port to force reconnects
  19820. Client client("localhost", 59998);
  19821. sse::SSEClient sse(client, "/events");
  19822. std::atomic<int> error_count{0};
  19823. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19824. sse.set_reconnect_interval(50);
  19825. sse.set_max_reconnect_attempts(2);
  19826. auto start = std::chrono::steady_clock::now();
  19827. sse.start(); // Blocking call
  19828. auto end = std::chrono::steady_clock::now();
  19829. // Should have stopped after 2 failed attempts
  19830. EXPECT_GE(error_count.load(), 2);
  19831. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19832. auto duration =
  19833. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19834. #ifdef _WIN32
  19835. // Windows is much slower for socket connection failures
  19836. EXPECT_LT(duration.count(), 7000);
  19837. #else
  19838. EXPECT_LT(duration.count(), 1000);
  19839. #endif
  19840. }
  19841. // Test: Multi-line data in integration
  19842. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19843. // Endpoint with multi-line data
  19844. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19845. res.set_chunked_content_provider(
  19846. "text/event-stream", [](size_t offset, DataSink &sink) {
  19847. if (offset == 0) {
  19848. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19849. sink.write(event.data(), event.size());
  19850. }
  19851. return false;
  19852. });
  19853. });
  19854. Client client("localhost", get_port());
  19855. sse::SSEClient sse(client, "/multiline-data");
  19856. std::string received_data;
  19857. std::mutex data_mutex;
  19858. sse.on_message([&](const sse::SSEMessage &msg) {
  19859. std::lock_guard<std::mutex> lock(data_mutex);
  19860. received_data = msg.data;
  19861. });
  19862. sse.set_reconnect_interval(100);
  19863. sse.set_max_reconnect_attempts(1);
  19864. sse.start_async();
  19865. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19866. sse.stop();
  19867. std::lock_guard<std::mutex> lock(data_mutex);
  19868. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19869. }
  19870. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19871. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19872. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19873. DataSink &sink) {
  19874. if (offset == 0) {
  19875. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19876. sink.write(events.data(), events.size());
  19877. }
  19878. return false;
  19879. });
  19880. });
  19881. Client client("localhost", get_port());
  19882. sse::SSEClient sse(client, "/empty-data-lines");
  19883. std::mutex mutex;
  19884. std::condition_variable cv;
  19885. std::vector<std::string> received;
  19886. sse.on_message([&](const sse::SSEMessage &msg) {
  19887. std::lock_guard<std::mutex> lock(mutex);
  19888. received.push_back(msg.data);
  19889. cv.notify_all();
  19890. });
  19891. sse.set_max_reconnect_attempts(1);
  19892. sse.start_async();
  19893. {
  19894. std::unique_lock<std::mutex> lock(mutex);
  19895. cv.wait_for(lock, std::chrono::seconds(2),
  19896. [&] { return received.size() >= 3; });
  19897. }
  19898. sse.stop();
  19899. ASSERT_GE(received.size(), 3u);
  19900. EXPECT_EQ(received[0], "");
  19901. EXPECT_EQ(received[1], "\nhello");
  19902. EXPECT_EQ(received[2], "");
  19903. }
  19904. // Test: Auto-reconnect after server disconnection
  19905. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19906. std::atomic<int> connection_count{0};
  19907. std::atomic<int> message_count{0};
  19908. // Endpoint that sends one event and closes, forcing reconnect
  19909. server_->Get("/reconnect-test",
  19910. [&connection_count](const Request &, Response &res) {
  19911. connection_count.fetch_add(1);
  19912. res.set_chunked_content_provider(
  19913. "text/event-stream", [](size_t offset, DataSink &sink) {
  19914. if (offset == 0) {
  19915. std::string event = "data: hello\n\n";
  19916. sink.write(event.data(), event.size());
  19917. }
  19918. return false; // Close connection after sending
  19919. });
  19920. });
  19921. Client client("localhost", get_port());
  19922. sse::SSEClient sse(client, "/reconnect-test");
  19923. sse.on_message([&message_count](const sse::SSEMessage &) {
  19924. message_count.fetch_add(1);
  19925. });
  19926. sse.set_reconnect_interval(100);
  19927. sse.set_max_reconnect_attempts(3);
  19928. sse.start_async();
  19929. // Wait long enough for multiple reconnects
  19930. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19931. sse.stop();
  19932. // Should have connected multiple times (initial + reconnects)
  19933. EXPECT_GE(connection_count.load(), 2);
  19934. // Should have received messages from multiple connections
  19935. EXPECT_GE(message_count.load(), 2);
  19936. }
  19937. // Test: A retry field that is not all ASCII digits is ignored
  19938. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19939. std::atomic<int> connection_count{0};
  19940. server_->Get("/bad-retry",
  19941. [&connection_count](const Request &, Response &res) {
  19942. connection_count.fetch_add(1);
  19943. res.set_chunked_content_provider(
  19944. "text/event-stream", [](size_t offset, DataSink &sink) {
  19945. if (offset == 0) {
  19946. std::string event = "retry: -1\ndata: hello\n\n";
  19947. sink.write(event.data(), event.size());
  19948. }
  19949. return false;
  19950. });
  19951. });
  19952. Client client("localhost", get_port());
  19953. sse::SSEClient sse(client, "/bad-retry");
  19954. sse.set_reconnect_interval(10000);
  19955. sse.start_async();
  19956. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19957. sse.stop();
  19958. EXPECT_EQ(connection_count.load(), 1);
  19959. }
  19960. // Test: A retry field of all ASCII digits sets the reconnection time
  19961. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19962. std::mutex mutex;
  19963. std::condition_variable cv;
  19964. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19965. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19966. {
  19967. std::lock_guard<std::mutex> lock(mutex);
  19968. connected_at.push_back(std::chrono::steady_clock::now());
  19969. cv.notify_all();
  19970. }
  19971. res.set_chunked_content_provider(
  19972. "text/event-stream", [](size_t offset, DataSink &sink) {
  19973. if (offset == 0) {
  19974. std::string event = "retry: 0\ndata: hello\n\n";
  19975. sink.write(event.data(), event.size());
  19976. }
  19977. return false;
  19978. });
  19979. });
  19980. Client client("localhost", get_port());
  19981. sse::SSEClient sse(client, "/zero-retry");
  19982. sse.set_reconnect_interval(10000);
  19983. sse.start_async();
  19984. {
  19985. std::unique_lock<std::mutex> lock(mutex);
  19986. cv.wait_for(lock, std::chrono::seconds(5),
  19987. [&] { return connected_at.size() >= 2; });
  19988. }
  19989. sse.stop();
  19990. // The server-supplied interval is applied, but never below 100ms, so
  19991. // "retry: 0" does not cause a busy reconnect loop
  19992. std::lock_guard<std::mutex> lock(mutex);
  19993. ASSERT_GE(connected_at.size(), 2u);
  19994. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  19995. connected_at[1] - connected_at[0])
  19996. .count();
  19997. EXPECT_GE(interval_ms, 100);
  19998. }
  19999. // Test: Last-Event-ID sent on reconnect
  20000. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20001. std::atomic<int> connection_count{0};
  20002. std::vector<std::string> received_last_event_ids;
  20003. std::mutex id_mutex;
  20004. // Endpoint that checks Last-Event-ID header and sends event with ID
  20005. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20006. int conn = connection_count.fetch_add(1);
  20007. // Capture the Last-Event-ID header from each connection
  20008. {
  20009. std::lock_guard<std::mutex> lock(id_mutex);
  20010. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20011. }
  20012. res.set_chunked_content_provider(
  20013. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20014. if (offset == 0) {
  20015. std::string event =
  20016. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20017. sink.write(event.data(), event.size());
  20018. }
  20019. return false;
  20020. });
  20021. });
  20022. Client client("localhost", get_port());
  20023. sse::SSEClient sse(client, "/reconnect-with-id");
  20024. sse.set_reconnect_interval(100);
  20025. sse.set_max_reconnect_attempts(3);
  20026. sse.start_async();
  20027. // Wait for at least 2 connections
  20028. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20029. sse.stop();
  20030. // Verify behavior
  20031. std::lock_guard<std::mutex> lock(id_mutex);
  20032. EXPECT_GE(received_last_event_ids.size(), 2u);
  20033. // First connection should have no Last-Event-ID
  20034. if (!received_last_event_ids.empty()) {
  20035. EXPECT_EQ(received_last_event_ids[0], "");
  20036. }
  20037. // Second connection should have Last-Event-ID from first connection
  20038. if (received_last_event_ids.size() >= 2) {
  20039. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20040. }
  20041. }
  20042. // Test: set_headers updates headers used on reconnect
  20043. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20044. std::vector<std::string> received_tokens;
  20045. std::mutex token_mutex;
  20046. // Endpoint that captures Authorization header
  20047. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20048. {
  20049. std::lock_guard<std::mutex> lock(token_mutex);
  20050. received_tokens.push_back(req.get_header_value("Authorization"));
  20051. }
  20052. res.set_chunked_content_provider(
  20053. "text/event-stream", [](size_t offset, DataSink &sink) {
  20054. if (offset == 0) {
  20055. std::string event = "data: hello\n\n";
  20056. sink.write(event.data(), event.size());
  20057. }
  20058. return false; // Close connection to trigger reconnect
  20059. });
  20060. });
  20061. Client client("localhost", get_port());
  20062. Headers headers = {{"Authorization", "Bearer old-token"}};
  20063. sse::SSEClient sse(client, "/auth-check", headers);
  20064. // Update headers on each successful connection
  20065. sse.on_open(
  20066. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20067. sse.set_reconnect_interval(100);
  20068. sse.set_max_reconnect_attempts(3);
  20069. sse.start_async();
  20070. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20071. sse.stop();
  20072. std::lock_guard<std::mutex> lock(token_mutex);
  20073. ASSERT_GE(received_tokens.size(), 2u);
  20074. // First connection uses original header
  20075. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20076. // Second connection uses updated header from set_headers
  20077. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20078. }
  20079. // Test: 401 allows reconnection (so on_error can refresh headers)
  20080. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20081. std::atomic<int> connection_count{0};
  20082. // Endpoint: returns 401 on first attempt, 200 on second
  20083. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20084. int conn = connection_count.fetch_add(1);
  20085. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20086. res.status = StatusCode::Unauthorized_401;
  20087. res.set_content("Unauthorized", "text/plain");
  20088. return;
  20089. }
  20090. res.set_chunked_content_provider(
  20091. "text/event-stream", [](size_t offset, DataSink &sink) {
  20092. if (offset == 0) {
  20093. std::string event = "data: authenticated\n\n";
  20094. sink.write(event.data(), event.size());
  20095. }
  20096. return false;
  20097. });
  20098. });
  20099. Client client("localhost", get_port());
  20100. Headers headers = {{"Authorization", "Bearer expired"}};
  20101. sse::SSEClient sse(client, "/auth-retry", headers);
  20102. std::atomic<bool> message_received{false};
  20103. // Refresh token on error
  20104. sse.on_error(
  20105. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20106. sse.on_message([&](const sse::SSEMessage &msg) {
  20107. if (msg.data == "authenticated") { message_received.store(true); }
  20108. });
  20109. sse.set_reconnect_interval(100);
  20110. sse.set_max_reconnect_attempts(3);
  20111. sse.start_async();
  20112. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20113. sse.stop();
  20114. // Should have reconnected after 401 and succeeded with new token
  20115. EXPECT_GE(connection_count.load(), 2);
  20116. EXPECT_TRUE(message_received.load());
  20117. }
  20118. TEST(Issue2318Test, EmptyHostString) {
  20119. {
  20120. httplib::Client cli_empty("", PORT);
  20121. auto res = cli_empty.Get("/");
  20122. ASSERT_FALSE(res);
  20123. EXPECT_EQ(httplib::Error::Connection, res.error());
  20124. }
  20125. {
  20126. httplib::Client cli(" ", PORT);
  20127. auto res = cli.Get("/");
  20128. ASSERT_FALSE(res);
  20129. EXPECT_EQ(httplib::Error::Connection, res.error());
  20130. }
  20131. }
  20132. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20133. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20134. Server svr;
  20135. // Set a small payload limit (1KB)
  20136. svr.set_payload_max_length(1024);
  20137. svr.Post("/test", [&](const Request &req, Response &res) {
  20138. res.set_content("Body size: " + std::to_string(req.body.size()),
  20139. "text/plain");
  20140. });
  20141. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20142. auto se = detail::scope_exit([&] {
  20143. svr.stop();
  20144. listen_thread.join();
  20145. });
  20146. svr.wait_until_ready();
  20147. // Create data that compresses well but exceeds limit when decompressed
  20148. // 8KB of repeated null bytes compresses to a very small size
  20149. std::string original_data(8 * 1024, '\0');
  20150. // Compress the data using gzip
  20151. std::string compressed_data;
  20152. detail::gzip_compressor compressor;
  20153. compressor.compress(original_data.data(), original_data.size(), true,
  20154. [&](const char *data, size_t size) {
  20155. compressed_data.append(data, size);
  20156. return true;
  20157. });
  20158. // Verify compression worked (compressed should be much smaller)
  20159. ASSERT_LT(compressed_data.size(), original_data.size());
  20160. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20161. // Send compressed data with Content-Encoding: gzip
  20162. Client cli(HOST, PORT);
  20163. Headers headers = {{"Content-Encoding", "gzip"}};
  20164. auto res =
  20165. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20166. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20168. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20169. }
  20170. #endif
  20171. // ============================================================================
  20172. // OpenSSL-Specific Tests
  20173. // ============================================================================
  20174. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20175. X509 *readCertificate(const std::string &strFileName) {
  20176. std::ifstream inStream(strFileName);
  20177. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20178. std::istreambuf_iterator<char>());
  20179. if (strCertPEM.empty()) return (nullptr);
  20180. BIO *pbCert = BIO_new(BIO_s_mem());
  20181. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20182. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20183. BIO_free(pbCert);
  20184. return (pCert);
  20185. }
  20186. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20187. std::ifstream inStream(strFileName);
  20188. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20189. std::istreambuf_iterator<char>());
  20190. if (strPrivateKeyPEM.empty()) return (nullptr);
  20191. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20192. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20193. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20194. BIO_free(pbPrivKey);
  20195. return (pPrivateKey);
  20196. }
  20197. TEST(BindServerTest, UpdateCerts) {
  20198. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20199. int port = svr.bind_to_any_port("0.0.0.0");
  20200. ASSERT_TRUE(svr.is_valid());
  20201. ASSERT_TRUE(port > 0);
  20202. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20203. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20204. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20205. ASSERT_TRUE(cert != nullptr);
  20206. ASSERT_TRUE(ca_cert != nullptr);
  20207. ASSERT_TRUE(key != nullptr);
  20208. X509_STORE *cert_store = X509_STORE_new();
  20209. X509_STORE_add_cert(cert_store, ca_cert);
  20210. // svr.update_certs(cert, key, cert_store); // deprecated
  20211. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20212. CLIENT_CA_CERT_FILE);
  20213. ASSERT_TRUE(svr.is_valid());
  20214. svr.stop();
  20215. X509_STORE_free(cert_store);
  20216. X509_free(cert);
  20217. X509_free(ca_cert);
  20218. EVP_PKEY_free(key);
  20219. }
  20220. // Test that update_certs() updates client CA list correctly
  20221. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20222. // Start with file-based constructor
  20223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20224. ASSERT_TRUE(svr.is_valid());
  20225. // Initially no client CA list should be set
  20226. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20227. ASSERT_TRUE(ssl_ctx != nullptr);
  20228. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20229. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20230. EXPECT_EQ(0, count_before);
  20231. // Now update with client CA (PEM string)
  20232. std::string cert_pem, key_pem, ca_pem;
  20233. read_file(SERVER_CERT_FILE, cert_pem);
  20234. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20235. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20236. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20237. ASSERT_TRUE(svr.is_valid());
  20238. // Now client CA list should be set
  20239. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20240. ASSERT_TRUE(ca_list_after != nullptr);
  20241. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20242. }
  20243. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20244. // Test that the file-path SSLServer constructor properly sets the client CA
  20245. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20246. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20247. ASSERT_TRUE(svr.is_valid());
  20248. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20249. ASSERT_TRUE(ssl_ctx != nullptr);
  20250. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20251. ASSERT_TRUE(ca_list != nullptr);
  20252. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20253. }
  20254. #endif
  20255. // ============================================================================
  20256. // MbedTLS-Specific Tests
  20257. // ============================================================================
  20258. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20259. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20260. using namespace httplib::tls;
  20261. // Track if callback was invoked
  20262. bool callback_invoked = false;
  20263. // The callback receives void* ctx which is actually MbedTlsContext*
  20264. // We can access the mbedtls_ssl_config via the context
  20265. auto setup_callback = [&callback_invoked](void *ctx) {
  20266. callback_invoked = true;
  20267. // Cast to MbedTlsContext* to access the ssl config
  20268. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20269. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20270. // Use static variables to hold certificate data (simplified for test)
  20271. static mbedtls_x509_crt own_cert;
  20272. static mbedtls_pk_context own_key;
  20273. static mbedtls_x509_crt ca_chain;
  20274. static bool initialized = false;
  20275. if (!initialized) {
  20276. mbedtls_x509_crt_init(&own_cert);
  20277. mbedtls_pk_init(&own_key);
  20278. mbedtls_x509_crt_init(&ca_chain);
  20279. // Load server certificate
  20280. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20281. return false;
  20282. }
  20283. // Load server private key.
  20284. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20285. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20286. #if MBEDTLS_VERSION_MAJOR == 3
  20287. ,
  20288. mbedtls_ctr_drbg_random, nullptr
  20289. #endif
  20290. ) != 0) {
  20291. return false;
  20292. }
  20293. // Load CA chain for client verification
  20294. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20295. return false;
  20296. }
  20297. initialized = true;
  20298. }
  20299. // Configure the SSL config
  20300. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20301. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20302. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20303. // Set minimum TLS version using mbedTLS native API
  20304. #if MBEDTLS_VERSION_MAJOR >= 3
  20305. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20306. #else
  20307. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20308. MBEDTLS_SSL_MINOR_VERSION_3);
  20309. #endif
  20310. return true;
  20311. };
  20312. SSLServer svr(setup_callback);
  20313. ASSERT_TRUE(svr.is_valid());
  20314. ASSERT_TRUE(callback_invoked);
  20315. svr.Get("/test", [&](const Request &req, Response &res) {
  20316. res.set_content("test", "text/plain");
  20317. auto cert = req.peer_cert();
  20318. ASSERT_TRUE(static_cast<bool>(cert));
  20319. auto common_name = cert.subject_cn();
  20320. EXPECT_EQ("Common Name", common_name);
  20321. });
  20322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20323. auto se = detail::scope_exit([&] {
  20324. svr.stop();
  20325. t.join();
  20326. ASSERT_FALSE(svr.is_running());
  20327. });
  20328. svr.wait_until_ready();
  20329. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20330. cli.enable_server_certificate_verification(false);
  20331. cli.set_connection_timeout(30);
  20332. auto res = cli.Get("/test");
  20333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20334. ASSERT_EQ(StatusCode::OK_200, res->status);
  20335. }
  20336. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20337. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20338. // keep-alive SSL session, which reads through that config in
  20339. // mbedtls_ssl_close_notify.
  20340. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20341. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20342. ASSERT_TRUE(svr.is_valid());
  20343. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20344. res.set_content("test", "text/plain");
  20345. });
  20346. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20347. auto se = detail::scope_exit([&] {
  20348. svr.stop();
  20349. t.join();
  20350. ASSERT_FALSE(svr.is_running());
  20351. });
  20352. svr.wait_until_ready();
  20353. {
  20354. SSLClient cli(HOST, PORT);
  20355. cli.enable_server_certificate_verification(false);
  20356. cli.set_keep_alive(true);
  20357. auto res = cli.Get("/test");
  20358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20359. ASSERT_EQ(StatusCode::OK_200, res->status);
  20360. // cli is destructed here with the keep-alive SSL session still open.
  20361. }
  20362. }
  20363. #endif
  20364. // WebSocket Tests
  20365. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20366. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20367. // defining the meaning of these bits has been negotiated.
  20368. auto make_frame = [](uint8_t first_byte) {
  20369. std::string frame;
  20370. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20371. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20372. frame += "Hello";
  20373. return frame;
  20374. };
  20375. // RSV1 set (0x40)
  20376. {
  20377. detail::BufferStream strm;
  20378. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20379. ws::Opcode opcode;
  20380. std::string payload;
  20381. bool fin;
  20382. EXPECT_EQ(
  20383. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20384. ws::impl::FrameRead::Fail);
  20385. }
  20386. // RSV2 set (0x20)
  20387. {
  20388. detail::BufferStream strm;
  20389. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20390. ws::Opcode opcode;
  20391. std::string payload;
  20392. bool fin;
  20393. EXPECT_EQ(
  20394. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20395. ws::impl::FrameRead::Fail);
  20396. }
  20397. // RSV3 set (0x10)
  20398. {
  20399. detail::BufferStream strm;
  20400. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20401. ws::Opcode opcode;
  20402. std::string payload;
  20403. bool fin;
  20404. EXPECT_EQ(
  20405. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20406. ws::impl::FrameRead::Fail);
  20407. }
  20408. // No RSV bits set - should succeed
  20409. {
  20410. detail::BufferStream strm;
  20411. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20412. ws::Opcode opcode;
  20413. std::string payload;
  20414. bool fin;
  20415. EXPECT_EQ(
  20416. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20417. ws::impl::FrameRead::Ok);
  20418. EXPECT_EQ(ws::Opcode::Text, opcode);
  20419. EXPECT_EQ("Hello", payload);
  20420. EXPECT_TRUE(fin);
  20421. }
  20422. }
  20423. TEST(WebSocketTest, ControlFrameValidation) {
  20424. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20425. // payload length <= 125.
  20426. // Ping with FIN=0 - must be rejected
  20427. {
  20428. detail::BufferStream strm;
  20429. std::string frame;
  20430. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20431. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20432. strm.write(frame.data(), frame.size());
  20433. ws::Opcode opcode;
  20434. std::string payload;
  20435. bool fin;
  20436. EXPECT_EQ(
  20437. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20438. ws::impl::FrameRead::Fail);
  20439. }
  20440. // Close with FIN=0 - must be rejected
  20441. {
  20442. detail::BufferStream strm;
  20443. std::string frame;
  20444. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20445. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20446. strm.write(frame.data(), frame.size());
  20447. ws::Opcode opcode;
  20448. std::string payload;
  20449. bool fin;
  20450. EXPECT_EQ(
  20451. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20452. ws::impl::FrameRead::Fail);
  20453. }
  20454. // Ping with payload_len=126 (extended length) - must be rejected
  20455. {
  20456. detail::BufferStream strm;
  20457. std::string frame;
  20458. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20459. frame += static_cast<char>(126); // payload_len=126 (>125)
  20460. frame += static_cast<char>(0x00); // extended length high byte
  20461. frame += static_cast<char>(126); // extended length low byte
  20462. frame += std::string(126, 'x');
  20463. strm.write(frame.data(), frame.size());
  20464. ws::Opcode opcode;
  20465. std::string payload;
  20466. bool fin;
  20467. EXPECT_EQ(
  20468. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20469. ws::impl::FrameRead::Fail);
  20470. }
  20471. // Ping with FIN=1 and payload_len=125 - should succeed
  20472. {
  20473. detail::BufferStream strm;
  20474. std::string frame;
  20475. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20476. frame += static_cast<char>(125); // payload_len=125
  20477. frame += std::string(125, 'x');
  20478. strm.write(frame.data(), frame.size());
  20479. ws::Opcode opcode;
  20480. std::string payload;
  20481. bool fin;
  20482. EXPECT_EQ(
  20483. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20484. ws::impl::FrameRead::Ok);
  20485. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20486. EXPECT_EQ(125u, payload.size());
  20487. EXPECT_TRUE(fin);
  20488. }
  20489. }
  20490. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20491. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20492. // length MUST be 0.
  20493. // MSB set - must be rejected
  20494. {
  20495. detail::BufferStream strm;
  20496. std::string frame;
  20497. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20498. frame += static_cast<char>(127); // 64-bit extended length
  20499. frame += static_cast<char>(0x80); // MSB set (invalid)
  20500. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20501. strm.write(frame.data(), frame.size());
  20502. ws::Opcode opcode;
  20503. std::string payload;
  20504. bool fin;
  20505. EXPECT_EQ(
  20506. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20507. ws::impl::FrameRead::Fail);
  20508. }
  20509. // MSB clear - should pass length parsing (will be rejected by max_len,
  20510. // but that's a different check; use a small length to verify)
  20511. {
  20512. detail::BufferStream strm;
  20513. std::string frame;
  20514. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20515. frame += static_cast<char>(127); // 64-bit extended length
  20516. frame += std::string(7, '\0'); // high bytes = 0
  20517. frame += static_cast<char>(0x03); // length = 3
  20518. frame += "abc";
  20519. strm.write(frame.data(), frame.size());
  20520. ws::Opcode opcode;
  20521. std::string payload;
  20522. bool fin;
  20523. EXPECT_EQ(
  20524. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20525. ws::impl::FrameRead::Ok);
  20526. EXPECT_EQ(ws::Opcode::Text, opcode);
  20527. EXPECT_EQ("abc", payload);
  20528. }
  20529. }
  20530. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20531. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20532. // Valid UTF-8
  20533. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20534. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20535. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20536. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20537. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20538. // Invalid UTF-8
  20539. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20540. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20541. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20542. EXPECT_FALSE(
  20543. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20544. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20545. }
  20546. TEST(WebSocketTest, ConnectAndDisconnect) {
  20547. Server svr;
  20548. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20549. std::string msg;
  20550. while (ws.read(msg)) {}
  20551. });
  20552. auto port = svr.bind_to_any_port(HOST);
  20553. std::thread t([&]() { svr.listen_after_bind(); });
  20554. svr.wait_until_ready();
  20555. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20556. auto res = client.connect();
  20557. ASSERT_TRUE(res);
  20558. EXPECT_EQ(Error::Success, res.error());
  20559. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20560. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20561. EXPECT_TRUE(client.is_open());
  20562. client.close();
  20563. EXPECT_FALSE(client.is_open());
  20564. svr.stop();
  20565. t.join();
  20566. }
  20567. TEST(WebSocketTest, ValidURL) {
  20568. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20569. EXPECT_TRUE(ws1.is_valid());
  20570. ws::WebSocketClient ws2("ws://example.com/path");
  20571. EXPECT_TRUE(ws2.is_valid());
  20572. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20573. EXPECT_TRUE(ws3.is_valid());
  20574. #ifdef CPPHTTPLIB_SSL_ENABLED
  20575. ws::WebSocketClient wss1("wss://example.com/path");
  20576. EXPECT_TRUE(wss1.is_valid());
  20577. ws::WebSocketClient wss2("wss://example.com:443/path");
  20578. EXPECT_TRUE(wss2.is_valid());
  20579. #endif
  20580. }
  20581. TEST(WebSocketTest, InvalidURL) {
  20582. // No scheme
  20583. ws::WebSocketClient ws1("localhost:8080/path");
  20584. EXPECT_FALSE(ws1.is_valid());
  20585. // No path
  20586. ws::WebSocketClient ws2("ws://localhost:8080");
  20587. EXPECT_FALSE(ws2.is_valid());
  20588. // Empty string
  20589. ws::WebSocketClient ws3("");
  20590. EXPECT_FALSE(ws3.is_valid());
  20591. // Missing host
  20592. ws::WebSocketClient ws4("ws://:8080/path");
  20593. EXPECT_FALSE(ws4.is_valid());
  20594. // Port number overflow — should not crash
  20595. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20596. EXPECT_FALSE(ws5.is_valid());
  20597. // Port out of range
  20598. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20599. EXPECT_FALSE(ws6.is_valid());
  20600. }
  20601. TEST(WebSocketTest, UnsupportedScheme) {
  20602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20603. ws::WebSocketClient ws1("http://localhost:8080/path");
  20604. EXPECT_FALSE(ws1.is_valid());
  20605. ws::WebSocketClient ws2("https://localhost:8080/path");
  20606. EXPECT_FALSE(ws2.is_valid());
  20607. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20608. EXPECT_FALSE(ws3.is_valid());
  20609. #else
  20610. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20611. std::invalid_argument);
  20612. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20613. std::invalid_argument);
  20614. #endif
  20615. }
  20616. TEST(WebSocketTest, ConnectWhenInvalid) {
  20617. ws::WebSocketClient ws("not a valid url");
  20618. EXPECT_FALSE(ws.is_valid());
  20619. auto res = ws.connect();
  20620. EXPECT_FALSE(res);
  20621. EXPECT_EQ(Error::Connection, res.error());
  20622. EXPECT_EQ(-1, res.status());
  20623. }
  20624. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20625. // Grab a port that is free, then close it again so nothing listens there
  20626. Server svr;
  20627. auto port = svr.bind_to_any_port(HOST);
  20628. svr.stop();
  20629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20630. auto res = client.connect();
  20631. ASSERT_FALSE(res);
  20632. EXPECT_EQ(Error::Connection, res.error());
  20633. EXPECT_EQ(-1, res.status());
  20634. }
  20635. TEST(WebSocketTest, DefaultPort) {
  20636. ws::WebSocketClient ws1("ws://example.com/path");
  20637. EXPECT_TRUE(ws1.is_valid());
  20638. // ws:// defaults to port 80 (verified by successful parse)
  20639. #ifdef CPPHTTPLIB_SSL_ENABLED
  20640. ws::WebSocketClient ws2("wss://example.com/path");
  20641. EXPECT_TRUE(ws2.is_valid());
  20642. // wss:// defaults to port 443 (verified by successful parse)
  20643. #endif
  20644. }
  20645. TEST(WebSocketTest, IPv6LiteralAddress) {
  20646. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20647. EXPECT_TRUE(ws1.is_valid());
  20648. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20649. EXPECT_TRUE(ws2.is_valid());
  20650. }
  20651. TEST(WebSocketTest, ComplexPath) {
  20652. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20653. EXPECT_TRUE(ws1.is_valid());
  20654. ws::WebSocketClient ws2("ws://localhost:8080/");
  20655. EXPECT_TRUE(ws2.is_valid());
  20656. }
  20657. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20658. Server svr;
  20659. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20660. std::string msg;
  20661. while (ws.read(msg)) {}
  20662. });
  20663. auto port = svr.bind_to_any_port(HOST);
  20664. std::thread t([&]() { svr.listen_after_bind(); });
  20665. svr.wait_until_ready();
  20666. auto another_host = "example.com";
  20667. auto wrong_ip = "192.0.2.1";
  20668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20669. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20670. ASSERT_TRUE(client.connect());
  20671. EXPECT_TRUE(client.is_open());
  20672. client.close();
  20673. svr.stop();
  20674. t.join();
  20675. }
  20676. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20677. Server svr;
  20678. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20679. std::string msg;
  20680. while (ws.read(msg)) {}
  20681. });
  20682. auto port = svr.bind_to_any_port(HOST);
  20683. std::thread t([&]() { svr.listen_after_bind(); });
  20684. svr.wait_until_ready();
  20685. auto wrong_ip = "192.0.2.1";
  20686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20687. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20688. client.set_connection_timeout(1);
  20689. client.set_read_timeout(1);
  20690. client.set_write_timeout(1);
  20691. EXPECT_FALSE(client.connect());
  20692. EXPECT_FALSE(client.is_open());
  20693. svr.stop();
  20694. t.join();
  20695. }
  20696. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20697. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20698. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20699. // (RFC 6761) is only a map key and the Host header value.
  20700. auto host = "target.invalid";
  20701. Server svr;
  20702. std::string received_host;
  20703. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20704. received_host = req.get_header_value("Host");
  20705. std::string msg;
  20706. while (ws.read(msg)) {}
  20707. });
  20708. auto port = svr.bind_to_any_port(HOST);
  20709. std::thread t([&]() { svr.listen_after_bind(); });
  20710. // ASSERT_* below returns from the test body, which would leave t joinable
  20711. // and make ~thread call std::terminate.
  20712. auto se = detail::scope_exit([&] {
  20713. svr.stop();
  20714. if (t.joinable()) { t.join(); }
  20715. });
  20716. svr.wait_until_ready();
  20717. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20718. std::to_string(port) + "/ws");
  20719. client.set_hostname_addr_map({{host, HOST}});
  20720. ASSERT_TRUE(client.connect());
  20721. EXPECT_TRUE(client.is_open());
  20722. client.close();
  20723. svr.stop();
  20724. t.join();
  20725. // The mapping only redirects the connection; the identity stays host_.
  20726. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20727. }
  20728. class WebSocketIntegrationTest : public ::testing::Test {
  20729. protected:
  20730. void SetUp() override {
  20731. server_ = httplib::detail::make_unique<Server>();
  20732. setup_server();
  20733. start_server();
  20734. }
  20735. void TearDown() override {
  20736. server_->stop();
  20737. if (server_thread_.joinable()) { server_thread_.join(); }
  20738. }
  20739. void setup_server() {
  20740. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20741. std::string msg;
  20742. ws::ReadResult ret;
  20743. while ((ret = ws.read(msg))) {
  20744. if (ret == ws::Binary) {
  20745. ws.send(msg.data(), msg.size());
  20746. } else {
  20747. ws.send(msg);
  20748. }
  20749. }
  20750. });
  20751. server_->WebSocket("/ws-echo-string",
  20752. [](const Request &, ws::WebSocket &ws) {
  20753. std::string msg;
  20754. while (ws.read(msg)) {
  20755. ws.send("echo: " + msg);
  20756. }
  20757. });
  20758. server_->WebSocket(
  20759. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20760. // Echo back request metadata
  20761. ws.send("path:" + req.path);
  20762. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20763. std::string msg;
  20764. while (ws.read(msg)) {}
  20765. });
  20766. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20767. std::string msg;
  20768. ws.read(msg); // wait for a message
  20769. ws.close();
  20770. });
  20771. server_->WebSocket("/ws-close-status",
  20772. [](const Request &, ws::WebSocket &ws) {
  20773. std::string msg;
  20774. ws.read(msg); // wait for a message
  20775. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20776. });
  20777. server_->WebSocket(
  20778. "/ws-subprotocol",
  20779. [](const Request &, ws::WebSocket &ws) {
  20780. std::string msg;
  20781. while (ws.read(msg)) {
  20782. ws.send(msg);
  20783. }
  20784. },
  20785. [](const std::vector<std::string> &protocols) -> std::string {
  20786. for (const auto &p : protocols) {
  20787. if (p == "graphql-ws") { return p; }
  20788. }
  20789. return "";
  20790. });
  20791. server_->WebSocket(
  20792. "/ws-subprotocol-unoffered",
  20793. [](const Request &, ws::WebSocket &ws) {
  20794. std::string msg;
  20795. while (ws.read(msg)) {
  20796. ws.send(msg);
  20797. }
  20798. },
  20799. [](const std::vector<std::string> &) -> std::string {
  20800. return "admin";
  20801. });
  20802. }
  20803. void start_server() {
  20804. port_ = server_->bind_to_any_port(HOST);
  20805. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20806. server_->wait_until_ready();
  20807. }
  20808. std::unique_ptr<Server> server_;
  20809. std::thread server_thread_;
  20810. int port_ = 0;
  20811. };
  20812. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20814. "/ws-echo");
  20815. ASSERT_TRUE(client.connect());
  20816. ASSERT_TRUE(client.is_open());
  20817. ASSERT_TRUE(client.send("Hello WebSocket"));
  20818. std::string msg;
  20819. EXPECT_EQ(ws::Text, client.read(msg));
  20820. EXPECT_EQ("Hello WebSocket", msg);
  20821. client.close();
  20822. }
  20823. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20824. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20825. "/ws-echo");
  20826. ASSERT_TRUE(client.connect());
  20827. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20828. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20829. std::string msg;
  20830. EXPECT_EQ(ws::Binary, client.read(msg));
  20831. EXPECT_EQ(binary_data, msg);
  20832. client.close();
  20833. }
  20834. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20835. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20836. "/ws-echo");
  20837. ASSERT_TRUE(client.connect());
  20838. for (int i = 0; i < 10; i++) {
  20839. auto text = "message " + std::to_string(i);
  20840. ASSERT_TRUE(client.send(text));
  20841. std::string msg;
  20842. ASSERT_TRUE(client.read(msg));
  20843. EXPECT_EQ(text, msg);
  20844. }
  20845. client.close();
  20846. }
  20847. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20848. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20849. "/ws-close");
  20850. ASSERT_TRUE(client.connect());
  20851. // Send a message to trigger the server to close
  20852. ASSERT_TRUE(client.send("trigger close"));
  20853. // The server will close, so read should return false
  20854. std::string msg;
  20855. EXPECT_FALSE(client.read(msg));
  20856. EXPECT_FALSE(client.is_open());
  20857. }
  20858. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20859. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20860. "/ws-echo");
  20861. ASSERT_TRUE(client.connect());
  20862. // 128KB message
  20863. std::string large_data(128 * 1024, 'X');
  20864. ASSERT_TRUE(client.send(large_data));
  20865. std::string msg;
  20866. ASSERT_TRUE(client.read(msg));
  20867. EXPECT_EQ(large_data, msg);
  20868. client.close();
  20869. }
  20870. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20871. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20872. "/ws-echo");
  20873. ASSERT_TRUE(client.connect());
  20874. const int num_threads = 4;
  20875. std::vector<std::thread> threads;
  20876. std::atomic<int> send_count{0};
  20877. for (int t = 0; t < num_threads; t++) {
  20878. threads.emplace_back([&client, &send_count, t]() {
  20879. for (int i = 0; i < 5; i++) {
  20880. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20881. if (client.send(text)) { send_count++; }
  20882. }
  20883. });
  20884. }
  20885. for (auto &th : threads) {
  20886. th.join();
  20887. }
  20888. int received = 0;
  20889. std::string msg;
  20890. while (received < send_count.load()) {
  20891. if (!client.read(msg)) { break; }
  20892. received++;
  20893. }
  20894. EXPECT_EQ(send_count.load(), received);
  20895. client.close();
  20896. }
  20897. TEST_F(WebSocketIntegrationTest, ReadString) {
  20898. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20899. "/ws-echo-string");
  20900. ASSERT_TRUE(client.connect());
  20901. ASSERT_TRUE(client.send("hello"));
  20902. std::string msg;
  20903. ASSERT_TRUE(client.read(msg));
  20904. EXPECT_EQ("echo: hello", msg);
  20905. ASSERT_TRUE(client.send("world"));
  20906. ASSERT_TRUE(client.read(msg));
  20907. EXPECT_EQ("echo: world", msg);
  20908. client.close();
  20909. }
  20910. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20911. Headers headers = {{"X-Test-Header", "test-value"}};
  20912. ws::WebSocketClient client(
  20913. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20914. ASSERT_TRUE(client.connect());
  20915. std::string msg;
  20916. ASSERT_TRUE(client.read(msg));
  20917. EXPECT_EQ("path:/ws-request-info", msg);
  20918. ASSERT_TRUE(client.read(msg));
  20919. EXPECT_EQ("header:test-value", msg);
  20920. client.close();
  20921. }
  20922. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20923. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20924. "/ws-echo");
  20925. client.set_read_timeout(1, 0); // 1 second
  20926. ASSERT_TRUE(client.connect());
  20927. // Don't send anything — server echo handler waits for a message, so read()
  20928. // should time out. The connection survives it: nothing was consumed.
  20929. std::string msg;
  20930. EXPECT_EQ(client.read(msg), ws::Timeout);
  20931. EXPECT_TRUE(client.is_open());
  20932. // And it is still usable afterwards.
  20933. EXPECT_TRUE(client.send("after timeout"));
  20934. EXPECT_EQ(client.read(msg), ws::Text);
  20935. EXPECT_EQ(msg, "after timeout");
  20936. }
  20937. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20938. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20939. "/ws-echo");
  20940. client.set_read_timeout(1, 0);
  20941. ASSERT_TRUE(client.connect());
  20942. ASSERT_TRUE(client.send("first"));
  20943. std::string msg;
  20944. ASSERT_EQ(client.read(msg), ws::Text);
  20945. ASSERT_EQ(msg, "first");
  20946. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20947. // not be used with a read timeout: it would reprocess the previous message.
  20948. EXPECT_EQ(client.read(msg), ws::Timeout);
  20949. EXPECT_EQ(msg, "first");
  20950. }
  20951. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20952. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20953. "/ws-echo");
  20954. ASSERT_TRUE(client.connect());
  20955. // Setting it once the connection is open reaches the live stream, not just
  20956. // the seed for the next connect().
  20957. client.set_read_timeout(1, 0);
  20958. std::string msg;
  20959. EXPECT_EQ(client.read(msg), ws::Timeout);
  20960. EXPECT_TRUE(client.is_open());
  20961. }
  20962. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20963. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20964. "/ws-echo");
  20965. client.set_read_timeout(5, 0);
  20966. ASSERT_TRUE(client.connect());
  20967. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20968. // The server should reject it and close the connection.
  20969. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20970. client.send(oversized);
  20971. // The server's read() should have failed due to payload limit,
  20972. // so our read() should return false (connection closed).
  20973. std::string msg;
  20974. EXPECT_FALSE(client.read(msg));
  20975. }
  20976. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20977. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20978. "/ws-echo");
  20979. client.set_read_timeout(10, 0);
  20980. ASSERT_TRUE(client.connect());
  20981. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20982. // This should succeed.
  20983. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20984. ASSERT_TRUE(client.send(at_limit));
  20985. std::string msg;
  20986. ASSERT_TRUE(client.read(msg));
  20987. EXPECT_EQ(at_limit.size(), msg.size());
  20988. client.close();
  20989. }
  20990. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20992. "/nonexistent");
  20993. auto res = client.connect();
  20994. EXPECT_FALSE(res);
  20995. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20996. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20997. EXPECT_FALSE(client.is_open());
  20998. }
  20999. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21000. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21001. "/ws-echo");
  21002. ASSERT_TRUE(client.connect());
  21003. ASSERT_TRUE(client.send(""));
  21004. std::string msg;
  21005. EXPECT_EQ(ws::Text, client.read(msg));
  21006. EXPECT_EQ("", msg);
  21007. client.close();
  21008. }
  21009. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21010. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21011. "/ws-echo");
  21012. // First connection
  21013. ASSERT_TRUE(client.connect());
  21014. ASSERT_TRUE(client.send("first"));
  21015. std::string msg;
  21016. ASSERT_TRUE(client.read(msg));
  21017. EXPECT_EQ("first", msg);
  21018. client.close();
  21019. EXPECT_FALSE(client.is_open());
  21020. // Reconnect using the same client object
  21021. ASSERT_TRUE(client.connect());
  21022. ASSERT_TRUE(client.is_open());
  21023. ASSERT_TRUE(client.send("second"));
  21024. ASSERT_TRUE(client.read(msg));
  21025. EXPECT_EQ("second", msg);
  21026. client.close();
  21027. }
  21028. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21030. "/ws-close-status");
  21031. ASSERT_TRUE(client.connect());
  21032. // Trigger the server to close with GoingAway status
  21033. ASSERT_TRUE(client.send("trigger"));
  21034. // read() should return false after receiving the close frame
  21035. std::string msg;
  21036. EXPECT_FALSE(client.read(msg));
  21037. EXPECT_FALSE(client.is_open());
  21038. }
  21039. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21041. "/ws-echo");
  21042. ASSERT_TRUE(client.connect());
  21043. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21044. EXPECT_FALSE(client.is_open());
  21045. }
  21046. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21047. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21048. ws::WebSocketClient client(
  21049. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21050. ASSERT_TRUE(client.connect());
  21051. // Server should have selected graphql-ws
  21052. EXPECT_EQ("graphql-ws", client.subprotocol());
  21053. client.close();
  21054. }
  21055. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21056. Headers headers;
  21057. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21058. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21059. ws::WebSocketClient client(
  21060. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21061. ASSERT_TRUE(client.connect());
  21062. // The offer on the second field line counts too, so graphql-ws is selected
  21063. EXPECT_EQ("graphql-ws", client.subprotocol());
  21064. client.close();
  21065. }
  21066. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21067. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21068. ws::WebSocketClient client(
  21069. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21070. ASSERT_TRUE(client.connect());
  21071. // Server should not have selected any subprotocol
  21072. EXPECT_TRUE(client.subprotocol().empty());
  21073. client.close();
  21074. }
  21075. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21076. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21077. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21078. "/ws-subprotocol-unoffered",
  21079. headers);
  21080. ASSERT_TRUE(client.connect());
  21081. EXPECT_TRUE(client.subprotocol().empty());
  21082. client.close();
  21083. }
  21084. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21085. // Connect without requesting any subprotocol
  21086. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21087. "/ws-subprotocol");
  21088. ASSERT_TRUE(client.connect());
  21089. EXPECT_TRUE(client.subprotocol().empty());
  21090. client.close();
  21091. }
  21092. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21093. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21094. "/ws-echo");
  21095. client.set_tcp_nodelay(true);
  21096. client.set_connection_timeout(3, 0);
  21097. bool socket_options_called = false;
  21098. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21099. ASSERT_TRUE(client.connect());
  21100. ASSERT_TRUE(client.is_open());
  21101. EXPECT_TRUE(socket_options_called);
  21102. ASSERT_TRUE(client.send("hello"));
  21103. std::string msg;
  21104. auto result = client.read(msg);
  21105. EXPECT_EQ(result, ws::ReadResult::Text);
  21106. EXPECT_EQ(msg, "hello");
  21107. client.close();
  21108. }
  21109. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21110. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21111. "/ws-echo");
  21112. client.set_connection_timeout(std::chrono::seconds(3));
  21113. client.set_write_timeout(std::chrono::seconds(3));
  21114. // A sub-second remainder exercises the seconds/microseconds split.
  21115. client.set_read_timeout(std::chrono::milliseconds(1500));
  21116. ASSERT_TRUE(client.connect());
  21117. auto start = std::chrono::steady_clock::now();
  21118. std::string msg;
  21119. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21120. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21121. std::chrono::steady_clock::now() - start)
  21122. .count();
  21123. // Above 1s so that dropping the microseconds half of the split fails here.
  21124. // Ignoring the setter altogether would not reach this line at all: a client
  21125. // waits forever by default.
  21126. EXPECT_GE(elapsed, 1400);
  21127. EXPECT_LT(elapsed, 30000);
  21128. }
  21129. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21130. Server svr;
  21131. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21132. if (!req.has_header("Authorization")) {
  21133. res.status = StatusCode::Unauthorized_401;
  21134. res.set_content("Unauthorized", "text/plain");
  21135. return Server::HandlerResponse::Handled;
  21136. }
  21137. return Server::HandlerResponse::Unhandled;
  21138. });
  21139. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21140. std::string msg;
  21141. while (ws.read(msg)) {
  21142. ws.send(msg);
  21143. }
  21144. });
  21145. auto port = svr.bind_to_any_port("localhost");
  21146. std::thread t([&]() { svr.listen_after_bind(); });
  21147. svr.wait_until_ready();
  21148. // Without Authorization header - should be rejected before upgrade
  21149. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21150. EXPECT_FALSE(client1.connect());
  21151. // The rejection is framed like any other HTTP response
  21152. {
  21153. Client cli("localhost", port);
  21154. Headers headers = {{"Upgrade", "websocket"},
  21155. {"Connection", "Upgrade"},
  21156. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21157. {"Sec-WebSocket-Version", "13"}};
  21158. auto res = cli.Get("/ws", headers);
  21159. ASSERT_TRUE(res);
  21160. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21161. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21162. EXPECT_EQ("Unauthorized", res->body);
  21163. }
  21164. // With Authorization header - should succeed
  21165. Headers headers = {{"Authorization", "Bearer token123"}};
  21166. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21167. headers);
  21168. ASSERT_TRUE(client2.connect());
  21169. ASSERT_TRUE(client2.send("hello"));
  21170. std::string msg;
  21171. ASSERT_TRUE(client2.read(msg));
  21172. EXPECT_EQ("hello", msg);
  21173. client2.close();
  21174. svr.stop();
  21175. t.join();
  21176. }
  21177. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21178. Server svr;
  21179. std::atomic<int> pre_request_calls{0};
  21180. std::atomic<bool> route_matched{false};
  21181. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21182. pre_request_calls++;
  21183. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21184. if (req.get_header_value("Authorization") != "Bearer token123") {
  21185. res.status = StatusCode::Unauthorized_401;
  21186. res.set_content("Unauthorized", "text/plain");
  21187. return Server::HandlerResponse::Handled;
  21188. }
  21189. return Server::HandlerResponse::Unhandled;
  21190. });
  21191. std::atomic<bool> handler_called{false};
  21192. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21193. handler_called = true;
  21194. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21195. });
  21196. auto port = svr.bind_to_any_port("localhost");
  21197. std::thread t([&]() { svr.listen_after_bind(); });
  21198. svr.wait_until_ready();
  21199. // Without Authorization header - should be rejected before upgrade
  21200. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21201. "/ws/1");
  21202. EXPECT_FALSE(client1.connect());
  21203. EXPECT_FALSE(handler_called);
  21204. EXPECT_EQ(1, pre_request_calls);
  21205. EXPECT_TRUE(route_matched);
  21206. // The rejection is an ordinary HTTP response, not a protocol switch
  21207. {
  21208. Client cli("localhost", port);
  21209. Headers headers = {{"Upgrade", "websocket"},
  21210. {"Connection", "Upgrade"},
  21211. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21212. {"Sec-WebSocket-Version", "13"}};
  21213. auto res = cli.Get("/ws/1", headers);
  21214. ASSERT_TRUE(res);
  21215. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21216. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21217. EXPECT_EQ("Unauthorized", res->body);
  21218. }
  21219. EXPECT_FALSE(handler_called);
  21220. // With Authorization header - should succeed
  21221. Headers headers = {{"Authorization", "Bearer token123"}};
  21222. ws::WebSocketClient client2(
  21223. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21224. ASSERT_TRUE(client2.connect());
  21225. std::string msg;
  21226. ASSERT_TRUE(client2.read(msg));
  21227. EXPECT_EQ("/ws/:id 2", msg);
  21228. EXPECT_TRUE(handler_called);
  21229. client2.close();
  21230. svr.stop();
  21231. t.join();
  21232. }
  21233. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21234. Server svr;
  21235. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21236. // A read timeout is how a handler gets control back. Without it, a handler
  21237. // parked in read() can never write on the connection it is reading.
  21238. ws.set_read_timeout(std::chrono::milliseconds(100));
  21239. std::string msg;
  21240. while (ws.is_open()) {
  21241. auto r = ws.read(msg);
  21242. if (r == httplib::ws::Timeout) {
  21243. ws.send("tick");
  21244. continue;
  21245. }
  21246. if (r == httplib::ws::Fail) { break; }
  21247. ws.send(msg);
  21248. }
  21249. });
  21250. auto port = svr.bind_to_any_port("localhost");
  21251. std::thread t([&]() { svr.listen_after_bind(); });
  21252. svr.wait_until_ready();
  21253. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21254. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21255. ASSERT_TRUE(client.connect());
  21256. // The client sends nothing, so anything it receives came out of the
  21257. // handler's timeout path.
  21258. std::string msg;
  21259. ASSERT_EQ(client.read(msg), ws::Text);
  21260. EXPECT_EQ("tick", msg);
  21261. client.close();
  21262. svr.stop();
  21263. t.join();
  21264. }
  21265. // Stream::read may return fewer bytes than asked for. This is that contract at
  21266. // its worst -- one byte per call -- which is what a frame header straddling a
  21267. // read buffer's boundary looks like to the frame parser.
  21268. class WsByteAtATimeStream : public Stream {
  21269. public:
  21270. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21271. bool is_readable() const override { return true; }
  21272. bool wait_readable() const override { return true; }
  21273. bool wait_writable() const override { return true; }
  21274. ssize_t read(char *ptr, size_t size) override {
  21275. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21276. *ptr = data_[pos_++];
  21277. return 1;
  21278. }
  21279. ssize_t write(const char *, size_t size) override {
  21280. return static_cast<ssize_t>(size);
  21281. }
  21282. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21283. ip = "127.0.0.1";
  21284. port = 0;
  21285. }
  21286. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21287. ip = "127.0.0.1";
  21288. port = 0;
  21289. }
  21290. socket_t socket() const override { return INVALID_SOCKET; }
  21291. time_t duration() const override { return 0; }
  21292. private:
  21293. std::string data_;
  21294. size_t pos_ = 0;
  21295. };
  21296. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21297. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21298. // length and the mask key are all multi-byte fields here. Each used to be
  21299. // read with a single read() call, which fails as soon as one is split.
  21300. std::string body(200, 'x');
  21301. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21302. std::string frame;
  21303. frame += static_cast<char>(0x81); // FIN + Text
  21304. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21305. frame += static_cast<char>(body.size() >> 8);
  21306. frame += static_cast<char>(body.size() & 0xff);
  21307. for (size_t i = 0; i < 4; i++) {
  21308. frame += static_cast<char>(mask[i]);
  21309. }
  21310. for (size_t i = 0; i < body.size(); i++) {
  21311. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21312. }
  21313. WsByteAtATimeStream strm(frame);
  21314. ws::Opcode opcode;
  21315. std::string payload;
  21316. bool fin = false;
  21317. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21318. /*expect_masked=*/true, 1024),
  21319. ws::impl::FrameRead::Ok);
  21320. EXPECT_TRUE(fin);
  21321. EXPECT_EQ(opcode, ws::Opcode::Text);
  21322. EXPECT_EQ(payload, body);
  21323. }
  21324. TEST(WebSocketTest, QueryStringInHandshake) {
  21325. Server svr;
  21326. std::mutex mtx;
  21327. std::string received_target;
  21328. std::string received_token;
  21329. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21330. {
  21331. std::lock_guard<std::mutex> lock(mtx);
  21332. received_target = req.target;
  21333. if (req.has_param("token")) {
  21334. received_token = req.get_param_value("token");
  21335. }
  21336. }
  21337. std::string msg;
  21338. while (ws.read(msg)) {
  21339. ws.send(msg);
  21340. }
  21341. });
  21342. auto port = svr.bind_to_any_port("localhost");
  21343. std::thread t([&]() { svr.listen_after_bind(); });
  21344. svr.wait_until_ready();
  21345. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21346. "/ws?token=ABC&session=123");
  21347. ASSERT_TRUE(client.connect());
  21348. // Round-trip ensures the handler has run and captured the request.
  21349. ASSERT_TRUE(client.send("hello"));
  21350. std::string msg;
  21351. ASSERT_TRUE(client.read(msg));
  21352. EXPECT_EQ("hello", msg);
  21353. client.close();
  21354. {
  21355. std::lock_guard<std::mutex> lock(mtx);
  21356. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21357. EXPECT_EQ("ABC", received_token);
  21358. }
  21359. svr.stop();
  21360. t.join();
  21361. }
  21362. // Run a handshake against a throwaway server and hand the request the server
  21363. // received back to the caller, so tests can assert on the headers the client
  21364. // actually put on the wire.
  21365. static void capture_websocket_handshake_request(
  21366. const Headers &client_headers,
  21367. std::function<void(const Request &, int port)> verify) {
  21368. Server svr;
  21369. std::mutex mtx;
  21370. Request received;
  21371. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21372. {
  21373. std::lock_guard<std::mutex> lock(mtx);
  21374. received = req;
  21375. }
  21376. std::string msg;
  21377. while (ws.read(msg)) {
  21378. ws.send(msg);
  21379. }
  21380. });
  21381. auto port = svr.bind_to_any_port("localhost");
  21382. std::thread t([&]() { svr.listen_after_bind(); });
  21383. auto se = detail::scope_exit([&] {
  21384. svr.stop();
  21385. t.join();
  21386. });
  21387. svr.wait_until_ready();
  21388. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21389. client_headers);
  21390. ASSERT_TRUE(client.connect());
  21391. ASSERT_TRUE(client.send("hello"));
  21392. std::string msg;
  21393. ASSERT_TRUE(client.read(msg));
  21394. client.close();
  21395. {
  21396. std::lock_guard<std::mutex> lock(mtx);
  21397. verify(received, port);
  21398. }
  21399. }
  21400. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21401. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21402. // Non-default port must be present in the Host header. Default ports
  21403. // (80/443) are omitted; that logic is covered by
  21404. // MakeHostAndPortStringTest.
  21405. EXPECT_EQ("localhost:" + std::to_string(port),
  21406. req.get_header_value("Host"));
  21407. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21408. req.get_header_value("User-Agent"));
  21409. EXPECT_FALSE(req.has_header("Accept"));
  21410. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21411. EXPECT_FALSE(req.has_header("Content-Length"));
  21412. });
  21413. }
  21414. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21415. capture_websocket_handshake_request(
  21416. {{"Host", "example.com"},
  21417. {"User-Agent", "custom-agent"},
  21418. {"X-Custom", "value"}},
  21419. [](const Request &req, int) {
  21420. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21421. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21422. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21423. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21424. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21425. });
  21426. }
  21427. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21428. capture_websocket_handshake_request(
  21429. {{"Upgrade", "bogus"},
  21430. {"Connection", "close"},
  21431. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21432. {"Sec-WebSocket-Version", "8"}},
  21433. [](const Request &req, int) {
  21434. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21435. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21436. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21437. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21438. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21439. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21440. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21441. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21442. req.get_header_value("Sec-WebSocket-Key"));
  21443. });
  21444. }
  21445. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21446. // A header the client refuses to send must abort the handshake before any
  21447. // part of it reaches the wire; a lone request line would otherwise sit in
  21448. // the peer's buffer as a truncated request.
  21449. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21450. ASSERT_NE(INVALID_SOCKET, srv);
  21451. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21452. sockaddr_in addr{};
  21453. addr.sin_family = AF_INET;
  21454. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21455. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21456. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21457. ASSERT_EQ(0, ::listen(srv, 1));
  21458. sockaddr_in bound{};
  21459. socklen_t bound_len = sizeof(bound);
  21460. ASSERT_EQ(
  21461. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21462. auto port = ntohs(bound.sin_port);
  21463. ssize_t received = -1;
  21464. std::thread t([&] {
  21465. // Bound every blocking call so a regression fails the test with a bad
  21466. // value instead of hanging the suite.
  21467. fd_set rfds;
  21468. FD_ZERO(&rfds);
  21469. FD_SET(srv, &rfds);
  21470. timeval tv{5, 0};
  21471. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21472. 0) {
  21473. return;
  21474. }
  21475. sockaddr_in cli_addr{};
  21476. socklen_t cli_len = sizeof(cli_addr);
  21477. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21478. if (cli == INVALID_SOCKET) { return; }
  21479. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21480. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21481. char buf[4096];
  21482. received = ::recv(cli, buf, sizeof(buf), 0);
  21483. });
  21484. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21485. // connect() has already shut the socket down by the time it returns false,
  21486. // so the peer sees EOF without waiting for the client to be destroyed.
  21487. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21488. {{"X-Bad", "a\r\nInjected: 1"}});
  21489. EXPECT_FALSE(client.connect());
  21490. t.join();
  21491. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21492. EXPECT_EQ(0, received);
  21493. }
  21494. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21495. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21496. // contains "upgrade" as a substring is a different token and must not
  21497. // start a WebSocket handshake.
  21498. auto make_request = [](const std::vector<std::string> &connection_values) {
  21499. Request req;
  21500. req.method = "GET";
  21501. req.headers.emplace("Upgrade", "websocket");
  21502. for (const auto &value : connection_values) {
  21503. req.headers.emplace("Connection", value);
  21504. }
  21505. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21506. req.headers.emplace("Sec-WebSocket-Version", "13");
  21507. return req;
  21508. };
  21509. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21510. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21511. EXPECT_TRUE(
  21512. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21513. EXPECT_TRUE(
  21514. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21515. EXPECT_TRUE(
  21516. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21517. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21518. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21519. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21520. EXPECT_FALSE(
  21521. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21522. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21523. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21524. }
  21525. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21526. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21527. // asks recipients to match each protocol-name case-insensitively, and RFC
  21528. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21529. // client naming websocket alongside another protocol, or on a second field
  21530. // line, is offering websocket; a value that merely contains "websocket" as a
  21531. // substring is a different protocol name and is not.
  21532. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21533. Request req;
  21534. req.method = "GET";
  21535. for (const auto &value : upgrade_values) {
  21536. req.headers.emplace("Upgrade", value);
  21537. }
  21538. req.headers.emplace("Connection", "Upgrade");
  21539. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21540. req.headers.emplace("Sec-WebSocket-Version", "13");
  21541. return req;
  21542. };
  21543. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21544. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21545. EXPECT_TRUE(
  21546. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21547. EXPECT_TRUE(
  21548. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21549. EXPECT_TRUE(
  21550. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21551. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21552. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21553. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21554. EXPECT_FALSE(
  21555. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21556. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21557. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21558. }
  21559. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21560. Server svr;
  21561. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21562. auto port = svr.bind_to_any_port("localhost");
  21563. std::thread t([&]() { svr.listen_after_bind(); });
  21564. auto se = detail::scope_exit([&] {
  21565. svr.stop();
  21566. t.join();
  21567. });
  21568. svr.wait_until_ready();
  21569. Headers headers = {{"Upgrade", "websocket"},
  21570. {"Connection", "notupgrade"},
  21571. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21572. {"Sec-WebSocket-Version", "13"}};
  21573. Client cli("localhost", port);
  21574. auto res = cli.Get("/ws", headers);
  21575. // The route exists only as a WebSocket route, so a request that fails the
  21576. // handshake check falls through to ordinary routing.
  21577. ASSERT_TRUE(res);
  21578. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21579. }
  21580. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21581. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21582. // Connection value is the only thing left for the client to reject.
  21583. Server svr;
  21584. svr.Get("/ws", [](const Request &req, Response &res) {
  21585. res.status = StatusCode::SwitchingProtocol_101;
  21586. res.set_header("Upgrade", "websocket");
  21587. res.set_header("Connection", "notupgrade");
  21588. res.set_header("Sec-WebSocket-Accept",
  21589. detail::websocket_accept_key(
  21590. req.get_header_value("Sec-WebSocket-Key")));
  21591. });
  21592. auto port = svr.bind_to_any_port("localhost");
  21593. std::thread t([&]() { svr.listen_after_bind(); });
  21594. auto se = detail::scope_exit([&] {
  21595. svr.stop();
  21596. t.join();
  21597. });
  21598. svr.wait_until_ready();
  21599. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21600. auto res = client.connect();
  21601. EXPECT_FALSE(res);
  21602. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21603. EXPECT_FALSE(client.is_open());
  21604. }
  21605. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21606. Server svr;
  21607. svr.Get("/ws", [](const Request &req, Response &res) {
  21608. res.status = StatusCode::SwitchingProtocol_101;
  21609. res.set_header("Upgrade", "websocket");
  21610. res.set_header("Connection", "Upgrade");
  21611. res.set_header("Sec-WebSocket-Accept",
  21612. detail::websocket_accept_key(
  21613. req.get_header_value("Sec-WebSocket-Key")));
  21614. res.set_header("Sec-WebSocket-Protocol", "admin");
  21615. });
  21616. auto port = svr.bind_to_any_port("localhost");
  21617. std::thread t([&]() { svr.listen_after_bind(); });
  21618. auto se = detail::scope_exit([&] {
  21619. svr.stop();
  21620. t.join();
  21621. });
  21622. svr.wait_until_ready();
  21623. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21624. // Server selects a subprotocol the client never offered
  21625. {
  21626. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21627. ws::WebSocketClient client(url, headers);
  21628. auto res = client.connect();
  21629. EXPECT_FALSE(res);
  21630. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21631. EXPECT_FALSE(client.is_open());
  21632. EXPECT_TRUE(client.subprotocol().empty());
  21633. }
  21634. // Client offered none but the server named one anyway
  21635. {
  21636. ws::WebSocketClient client(url);
  21637. auto res = client.connect();
  21638. EXPECT_FALSE(res);
  21639. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21640. EXPECT_FALSE(client.is_open());
  21641. EXPECT_TRUE(client.subprotocol().empty());
  21642. }
  21643. }
  21644. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21645. // The socket path doubles as the URL host, so it must not contain '/'.
  21646. const char *shard = getenv("GTEST_SHARD_INDEX");
  21647. const std::string sock_path =
  21648. shard ? std::string("httplib-ws-") + shard + ".sock"
  21649. : std::string("httplib-ws.sock");
  21650. std::remove(sock_path.c_str());
  21651. Server svr;
  21652. std::mutex mtx;
  21653. std::string received_host;
  21654. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21655. {
  21656. std::lock_guard<std::mutex> lock(mtx);
  21657. received_host = req.get_header_value("Host");
  21658. }
  21659. std::string msg;
  21660. while (ws.read(msg)) {
  21661. ws.send(msg);
  21662. }
  21663. });
  21664. svr.set_address_family(AF_UNIX);
  21665. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21666. auto se = detail::scope_exit([&] {
  21667. svr.stop();
  21668. t.join();
  21669. std::remove(sock_path.c_str());
  21670. });
  21671. svr.wait_until_ready();
  21672. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21673. client.set_address_family(AF_UNIX);
  21674. ASSERT_TRUE(client.connect());
  21675. ASSERT_TRUE(client.send("hello"));
  21676. std::string msg;
  21677. ASSERT_TRUE(client.read(msg));
  21678. client.close();
  21679. {
  21680. std::lock_guard<std::mutex> lock(mtx);
  21681. // There is no host:port for a Unix socket, so the same "localhost"
  21682. // placeholder the HTTP client uses is expected.
  21683. EXPECT_EQ("localhost", received_host);
  21684. }
  21685. }
  21686. // Two threads must never parse WebSocket frames from the same stream.
  21687. // close() used to read the peer's Close reply with its own frame read, so it
  21688. // raced a reader thread that was in the middle of a payload: the payload loop
  21689. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21690. // so bytes taken by close() were replaced with bytes from further along the
  21691. // stream. The message kept its length and silently changed content.
  21692. //
  21693. // The raw peer below sends a frame header plus part of the payload, waits for
  21694. // the handler to call close(), and only then sends the rest. Whichever thread
  21695. // would win the race for those bytes, the message must arrive intact, because
  21696. // close() must not touch the stream while read() owns it.
  21697. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21698. #ifndef _WIN32
  21699. signal(SIGPIPE, SIG_IGN);
  21700. #endif
  21701. const size_t payload_len = 120; // fits the 7-bit length field
  21702. const size_t prefix_len = 8;
  21703. const int attempts = 8;
  21704. std::string expected(payload_len, '\0');
  21705. for (size_t i = 0; i < payload_len; i++) {
  21706. expected[i] = static_cast<char>('a' + i % 26);
  21707. }
  21708. std::atomic<bool> peer_stalled{false};
  21709. std::atomic<bool> handler_done{false};
  21710. std::mutex received_mutex;
  21711. std::vector<std::string> received;
  21712. // Bound every wait, so a regression fails the test instead of hanging the
  21713. // suite.
  21714. auto wait_for = [](const std::atomic<bool> &flag) {
  21715. for (int i = 0; i < 500 && !flag; i++) {
  21716. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21717. }
  21718. };
  21719. Server svr;
  21720. svr.set_websocket_ping_interval(0);
  21721. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21722. std::thread reader([&]() {
  21723. std::string msg;
  21724. while (ws.read(msg)) {
  21725. std::lock_guard<std::mutex> guard(received_mutex);
  21726. received.push_back(msg);
  21727. }
  21728. });
  21729. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21730. // inside read_websocket_frame() when close() runs.
  21731. wait_for(peer_stalled);
  21732. ws.close();
  21733. reader.join();
  21734. handler_done = true;
  21735. });
  21736. auto port = svr.bind_to_any_port("127.0.0.1");
  21737. std::thread t([&]() { svr.listen_after_bind(); });
  21738. auto se = detail::scope_exit([&] {
  21739. svr.stop();
  21740. t.join();
  21741. });
  21742. svr.wait_until_ready();
  21743. auto send_bytes = [](socket_t s, const std::string &data) {
  21744. #ifdef _WIN32
  21745. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21746. #else
  21747. auto n = ::send(s, data.data(), data.size(), 0);
  21748. #endif
  21749. return n == static_cast<decltype(n)>(data.size());
  21750. };
  21751. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21752. // Every length used here fits the 7-bit length field.
  21753. auto masked_header = [](uint8_t first_byte, size_t len) {
  21754. std::string h;
  21755. h += static_cast<char>(first_byte);
  21756. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21757. h.append(4, '\0'); // mask key
  21758. return h;
  21759. };
  21760. for (int attempt = 0; attempt < attempts; attempt++) {
  21761. peer_stalled = false;
  21762. handler_done = false;
  21763. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21764. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21765. auto se_sock = detail::scope_exit([&] {
  21766. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21767. });
  21768. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21769. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21770. sockaddr_in addr{};
  21771. addr.sin_family = AF_INET;
  21772. addr.sin_port = htons(static_cast<uint16_t>(port));
  21773. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21774. ASSERT_EQ(
  21775. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21776. << "attempt " << attempt;
  21777. ASSERT_TRUE(send_bytes(sock,
  21778. "GET /ws HTTP/1.1\r\n"
  21779. "Host: 127.0.0.1\r\n"
  21780. "Upgrade: websocket\r\n"
  21781. "Connection: Upgrade\r\n"
  21782. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21783. "Sec-WebSocket-Version: 13\r\n"
  21784. "\r\n"))
  21785. << "attempt " << attempt;
  21786. std::string response;
  21787. while (response.find("\r\n\r\n") == std::string::npos) {
  21788. char buf[512];
  21789. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21790. if (n <= 0) { break; }
  21791. response.append(buf, static_cast<size_t>(n));
  21792. }
  21793. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21794. << "attempt " << attempt;
  21795. // Send the header of a Binary message but only the first prefix_len bytes
  21796. // of its payload, leaving the reader thread stalled inside the payload.
  21797. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21798. expected.substr(0, prefix_len)))
  21799. << "attempt " << attempt;
  21800. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21801. peer_stalled = true;
  21802. // Let close() send its Close frame and park in its own read before the
  21803. // rest of the payload arrives, so both threads are waiting for it.
  21804. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21805. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21806. close_frame += static_cast<char>(0x03); // status 1000
  21807. close_frame += static_cast<char>(0xE8);
  21808. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21809. << "attempt " << attempt;
  21810. // Closing the peer releases the reader thread even on the buggy path,
  21811. // where it waits for bytes another thread already consumed.
  21812. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21813. detail::close_socket(sock);
  21814. sock = INVALID_SOCKET;
  21815. wait_for(handler_done);
  21816. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21817. }
  21818. std::lock_guard<std::mutex> guard(received_mutex);
  21819. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21820. << "a message in flight when close() ran was dropped";
  21821. for (size_t i = 0; i < received.size(); i++) {
  21822. EXPECT_EQ(expected, received[i]) << "message " << i;
  21823. }
  21824. }
  21825. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21826. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21827. protected:
  21828. void SetUp() override {
  21829. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21830. SERVER_PRIVATE_KEY_FILE);
  21831. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21832. std::string msg;
  21833. ws::ReadResult ret;
  21834. while ((ret = ws.read(msg))) {
  21835. if (ret == ws::Binary) {
  21836. ws.send(msg.data(), msg.size());
  21837. } else {
  21838. ws.send(msg);
  21839. }
  21840. }
  21841. });
  21842. port_ = server_->bind_to_any_port(HOST);
  21843. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21844. server_->wait_until_ready();
  21845. }
  21846. void TearDown() override {
  21847. server_->stop();
  21848. if (server_thread_.joinable()) { server_thread_.join(); }
  21849. }
  21850. std::unique_ptr<SSLServer> server_;
  21851. std::thread server_thread_;
  21852. int port_ = 0;
  21853. };
  21854. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21855. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21856. "/ws-echo");
  21857. client.enable_server_certificate_verification(false);
  21858. ASSERT_TRUE(client.connect());
  21859. ASSERT_TRUE(client.is_open());
  21860. ASSERT_TRUE(client.send("Hello WSS"));
  21861. std::string msg;
  21862. EXPECT_EQ(ws::Text, client.read(msg));
  21863. EXPECT_EQ("Hello WSS", msg);
  21864. client.close();
  21865. }
  21866. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21867. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21868. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21869. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21870. // client (without calling close() first) is the only path that runs
  21871. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21872. // bug exactly.
  21873. //
  21874. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21875. // when linked against an instrumented libssl; run under Valgrind to catch it
  21876. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21877. // suite (the freed session otherwise stalls on the close handshake) — this test
  21878. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21879. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21880. {
  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. // Intentionally do NOT call client.close(): leaving scope runs
  21890. // shutdown_and_close() with the WebSocket still open, which must send the
  21891. // close frame while the TLS session is still alive.
  21892. }
  21893. }
  21894. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21895. // shutdown_and_close() at the start of connect(), reproducing the same
  21896. // use-after-free within the test body rather than at scope exit. The second
  21897. // connect must succeed and echo, proving the close handshake ran over a live
  21898. // session. See the note above about memory-tool requirements.
  21899. TEST_F(WebSocketSSLIntegrationTest,
  21900. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21901. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21902. "/ws-echo");
  21903. client.enable_server_certificate_verification(false);
  21904. client.set_read_timeout(2, 0);
  21905. client.set_write_timeout(2, 0);
  21906. ASSERT_TRUE(client.connect());
  21907. ASSERT_TRUE(client.is_open());
  21908. ASSERT_TRUE(client.send("still open"));
  21909. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21910. // the still-open connection, which must not touch a freed TLS session.
  21911. ASSERT_TRUE(client.connect());
  21912. ASSERT_TRUE(client.is_open());
  21913. ASSERT_TRUE(client.send("after reconnect"));
  21914. std::string msg;
  21915. EXPECT_EQ(ws::Text, client.read(msg));
  21916. EXPECT_EQ("after reconnect", msg);
  21917. client.close();
  21918. }
  21919. #endif
  21920. #ifdef CPPHTTPLIB_SSL_ENABLED
  21921. class WebSocketSSLCATest : public ::testing::Test {
  21922. protected:
  21923. void SetUp() override {
  21924. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21925. SERVER_PRIVATE_KEY_FILE);
  21926. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21927. std::string msg;
  21928. while (ws.read(msg)) {
  21929. ws.send(msg);
  21930. }
  21931. });
  21932. port_ = server_->bind_to_any_port("127.0.0.1");
  21933. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21934. server_->wait_until_ready();
  21935. }
  21936. void TearDown() override {
  21937. server_->stop();
  21938. if (server_thread_.joinable()) { server_thread_.join(); }
  21939. }
  21940. std::string url() const {
  21941. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21942. }
  21943. std::unique_ptr<SSLServer> server_;
  21944. std::thread server_thread_;
  21945. int port_ = 0;
  21946. };
  21947. // A custom CA loaded as PEM verifies the server with full certificate
  21948. // verification enabled
  21949. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21950. ws::WebSocketClient client(url());
  21951. std::string cert;
  21952. read_file(SERVER_CERT2_FILE, cert);
  21953. client.load_ca_cert_store(cert.c_str(), cert.size());
  21954. ASSERT_TRUE(client.connect());
  21955. ASSERT_TRUE(client.send("hello"));
  21956. std::string msg;
  21957. EXPECT_EQ(ws::Text, client.read(msg));
  21958. EXPECT_EQ("hello", msg);
  21959. client.close();
  21960. }
  21961. // A custom CA that does not cover the server must fail verification (the
  21962. // custom CA is exclusive; system certs are not loaded alongside it)
  21963. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21964. ws::WebSocketClient client(url());
  21965. std::string cert;
  21966. read_file(CLIENT_CA_CERT_FILE, cert);
  21967. client.load_ca_cert_store(cert.c_str(), cert.size());
  21968. auto res = client.connect();
  21969. ASSERT_FALSE(res);
  21970. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21971. EXPECT_EQ(-1, res.status());
  21972. EXPECT_NE(0u, res.ssl_backend_error());
  21973. }
  21974. // The same CA as a file path rather than PEM in memory
  21975. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21976. ws::WebSocketClient client(url());
  21977. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21978. ASSERT_TRUE(client.connect());
  21979. ASSERT_TRUE(client.send("hello"));
  21980. std::string msg;
  21981. EXPECT_EQ(ws::Text, client.read(msg));
  21982. EXPECT_EQ("hello", msg);
  21983. client.close();
  21984. }
  21985. // ...and a CA file that does not cover the server still fails, so it is the
  21986. // path above that decides the outcome
  21987. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21988. ws::WebSocketClient client(url());
  21989. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21990. ASSERT_FALSE(client.connect());
  21991. }
  21992. // Regression test: reconnecting with a native custom CA store used to reuse
  21993. // a store handle the previous TLS context had already freed (use-after-free
  21994. // under the OpenSSL backend). The context now lives as long as the client.
  21995. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21996. ws::WebSocketClient client(url());
  21997. std::string cert;
  21998. read_file(SERVER_CERT2_FILE, cert);
  21999. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22000. ASSERT_TRUE(client.connect());
  22001. client.close();
  22002. ASSERT_TRUE(client.connect());
  22003. ASSERT_TRUE(client.send("again"));
  22004. std::string msg;
  22005. EXPECT_EQ(ws::Text, client.read(msg));
  22006. EXPECT_EQ("again", msg);
  22007. client.close();
  22008. }
  22009. // Regression test: a certificate with a trusted chain but no identity match
  22010. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22011. // verification entirely for IP hosts, so this connection succeeded there.
  22012. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22013. // chain verification while the identity check must still fail.
  22014. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22015. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22016. ASSERT_TRUE(svr.is_valid());
  22017. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22018. std::string msg;
  22019. while (ws.read(msg)) {
  22020. ws.send(msg);
  22021. }
  22022. });
  22023. auto port = svr.bind_to_any_port("127.0.0.1");
  22024. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22025. auto se = detail::scope_exit([&] {
  22026. svr.stop();
  22027. t.join();
  22028. });
  22029. svr.wait_until_ready();
  22030. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22031. "/echo");
  22032. std::string cert;
  22033. read_file(SERVER_CERT_FILE, cert);
  22034. client.load_ca_cert_store(cert.c_str(), cert.size());
  22035. ASSERT_FALSE(client.connect());
  22036. }
  22037. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22038. // SNI, so nothing binds the host name to the TLS session. These bind the
  22039. // server to "localhost" instead, the only shape that exercises the SNI and
  22040. // hostname-verification path with certificate verification left enabled.
  22041. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22042. protected:
  22043. void Start(const char *cert_file) {
  22044. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22045. SERVER_PRIVATE_KEY_FILE);
  22046. ASSERT_TRUE(server_->is_valid());
  22047. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22048. std::string msg;
  22049. while (ws.read(msg)) {
  22050. ws.send(msg);
  22051. }
  22052. });
  22053. port_ = server_->bind_to_any_port("localhost");
  22054. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22055. server_->wait_until_ready();
  22056. }
  22057. void TearDown() override {
  22058. if (server_) { server_->stop(); }
  22059. if (server_thread_.joinable()) { server_thread_.join(); }
  22060. }
  22061. std::string url() const {
  22062. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22063. }
  22064. std::unique_ptr<SSLServer> server_;
  22065. std::thread server_thread_;
  22066. int port_ = 0;
  22067. };
  22068. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22069. // out and the connection is usable
  22070. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22071. Start(SERVER_CERT2_FILE);
  22072. ws::WebSocketClient client(url());
  22073. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22074. ASSERT_TRUE(client.connect());
  22075. ASSERT_TRUE(client.send("hello"));
  22076. std::string msg;
  22077. EXPECT_EQ(ws::Text, client.read(msg));
  22078. EXPECT_EQ("hello", msg);
  22079. client.close();
  22080. }
  22081. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22082. // while the identity check must still reject "localhost"
  22083. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22084. Start(SERVER_CERT_FILE);
  22085. ws::WebSocketClient client(url());
  22086. client.set_ca_cert_path(SERVER_CERT_FILE);
  22087. auto res = client.connect();
  22088. ASSERT_FALSE(res);
  22089. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22090. EXPECT_EQ(-1, res.status());
  22091. }
  22092. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22093. // disabled: the chain is still checked, only the identity check is skipped
  22094. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22095. Start(SERVER_CERT_FILE);
  22096. ws::WebSocketClient client(url());
  22097. client.set_ca_cert_path(SERVER_CERT_FILE);
  22098. client.enable_server_hostname_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. // A CA that did not sign the server certificate fails the chain, even though
  22107. // the name would match
  22108. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22109. Start(SERVER_CERT2_FILE);
  22110. ws::WebSocketClient client(url());
  22111. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22112. ASSERT_FALSE(client.connect());
  22113. }
  22114. // With verification disabled, neither the chain nor the name is checked
  22115. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22116. Start(SERVER_CERT_FILE);
  22117. ws::WebSocketClient client(url());
  22118. client.enable_server_certificate_verification(false);
  22119. ASSERT_TRUE(client.connect());
  22120. ASSERT_TRUE(client.send("hello"));
  22121. std::string msg;
  22122. EXPECT_EQ(ws::Text, client.read(msg));
  22123. EXPECT_EQ("hello", msg);
  22124. client.close();
  22125. }
  22126. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22127. protected:
  22128. void SetUp() override {
  22129. server_ = httplib::detail::make_unique<SSLServer>(
  22130. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22131. ASSERT_TRUE(server_->is_valid());
  22132. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22133. std::string msg;
  22134. while (ws.read(msg)) {
  22135. ws.send(msg);
  22136. }
  22137. });
  22138. port_ = server_->bind_to_any_port("localhost");
  22139. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22140. server_->wait_until_ready();
  22141. }
  22142. void TearDown() override {
  22143. server_->stop();
  22144. if (server_thread_.joinable()) { server_thread_.join(); }
  22145. }
  22146. std::string url() const {
  22147. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22148. }
  22149. void ConnectWithClientCert(const std::string &client_cert_file,
  22150. const std::string &client_private_key_file,
  22151. const char *private_key_password) {
  22152. std::string cert_pem, key_pem;
  22153. read_file(client_cert_file, cert_pem);
  22154. read_file(client_private_key_file, key_pem);
  22155. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22156. key_pem.c_str(), key_pem.size(),
  22157. private_key_password};
  22158. ws::WebSocketClient client(url(), pem);
  22159. ASSERT_TRUE(client.is_valid());
  22160. client.enable_server_certificate_verification(false);
  22161. ASSERT_TRUE(client.connect());
  22162. ASSERT_TRUE(client.send("hello"));
  22163. std::string msg;
  22164. EXPECT_EQ(ws::Text, client.read(msg));
  22165. EXPECT_EQ("hello", msg);
  22166. client.close();
  22167. }
  22168. std::unique_ptr<SSLServer> server_;
  22169. std::thread server_thread_;
  22170. int port_ = 0;
  22171. };
  22172. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22173. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22174. }
  22175. // Control for the tests above: the fixture's server really does require a
  22176. // client certificate, so it is the PEM the constructor installed that decides
  22177. // the outcome.
  22178. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22179. ws::WebSocketClient client(url());
  22180. ASSERT_TRUE(client.is_valid());
  22181. client.enable_server_certificate_verification(false);
  22182. EXPECT_FALSE(client.connect());
  22183. }
  22184. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22185. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22186. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22187. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22188. }
  22189. #endif
  22190. #if !defined(_WIN32)
  22191. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22192. auto secret_dir = std::string("./symlink_test_secret");
  22193. auto served_dir = std::string("./symlink_test_served");
  22194. auto secret_file = secret_dir + "/secret.txt";
  22195. auto symlink_path = served_dir + "/escape";
  22196. // Setup: create directories and files
  22197. mkdir(secret_dir.c_str(), 0755);
  22198. mkdir(served_dir.c_str(), 0755);
  22199. {
  22200. std::ofstream ofs(secret_file);
  22201. ofs << "SECRET_DATA";
  22202. }
  22203. // Create symlink using absolute path so it resolves correctly
  22204. #ifdef PATH_MAX
  22205. char abs_secret[PATH_MAX];
  22206. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22207. #else
  22208. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22209. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22210. ASSERT_NE(nullptr, abs_secret);
  22211. #endif
  22212. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22213. auto se = detail::scope_exit([&] {
  22214. unlink(symlink_path.c_str());
  22215. unlink(secret_file.c_str());
  22216. rmdir(served_dir.c_str());
  22217. rmdir(secret_dir.c_str());
  22218. });
  22219. Server svr;
  22220. svr.set_mount_point("/", served_dir);
  22221. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22222. auto se2 = detail::scope_exit([&] {
  22223. svr.stop();
  22224. listen_thread.join();
  22225. });
  22226. svr.wait_until_ready();
  22227. Client cli("localhost", PORT);
  22228. // Symlink pointing outside base dir should be blocked
  22229. auto res = cli.Get("/escape/secret.txt");
  22230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22231. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22232. }
  22233. #endif
  22234. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22235. // "GET /smuggled" request), reads the first response, and only then sends the
  22236. // embedded request as the body. Returns how many times /smuggled ran.
  22237. //
  22238. // The body is sent AFTER receiving the first response (as in the original
  22239. // PoC) so that the stream_line_reader cannot buffer it together with the
  22240. // headers of the first request.
  22241. static int count_smuggled_requests(const std::string &outer_head,
  22242. std::string &first_response) {
  22243. Server svr;
  22244. svr.set_mount_point("/", "./www");
  22245. std::atomic<int> smuggled_count(0);
  22246. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22247. smuggled_count++;
  22248. res.set_content("oops", "text/plain");
  22249. });
  22250. svr.Post("/post", [&](const Request &req, Response &res) {
  22251. res.set_content(req.body, "text/plain");
  22252. });
  22253. auto port = svr.bind_to_any_port("localhost");
  22254. thread t = thread([&] { svr.listen_after_bind(); });
  22255. auto se = detail::scope_exit([&] {
  22256. svr.stop();
  22257. t.join();
  22258. });
  22259. svr.wait_until_ready();
  22260. auto error = Error::Success;
  22261. auto sock = detail::create_client_socket(
  22262. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22263. /*connection_timeout_sec=*/2, 0,
  22264. /*read_timeout_sec=*/2, 0,
  22265. /*write_timeout_sec=*/2, 0, std::string(), error);
  22266. EXPECT_NE(INVALID_SOCKET, sock);
  22267. if (sock == INVALID_SOCKET) { return -1; }
  22268. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22269. // The "smuggled" request will be sent as the body of the outer request
  22270. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22271. "Host: localhost\r\n"
  22272. "Connection: close\r\n"
  22273. "\r\n";
  22274. auto head = outer_head;
  22275. auto len = std::to_string(smuggled.size());
  22276. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22277. pos = head.find("{len}", pos + len.size())) {
  22278. head.replace(pos, 5, len);
  22279. }
  22280. // Step 1: Send only the outer request headers (no body yet)
  22281. auto sent = send(sock, head.data(), head.size(), 0);
  22282. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22283. // Step 2: Read the first response
  22284. char buf[4096];
  22285. for (;;) {
  22286. auto n = recv(sock, buf, sizeof(buf), 0);
  22287. if (n <= 0) break;
  22288. first_response.append(buf, static_cast<size_t>(n));
  22289. // Stop once we have a complete response (headers + body)
  22290. auto hdr_end = first_response.find("\r\n\r\n");
  22291. if (hdr_end != std::string::npos) {
  22292. // Check for Content-Length to know when the body is complete
  22293. auto cl_pos = first_response.find("Content-Length:");
  22294. if (cl_pos != std::string::npos) {
  22295. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22296. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22297. auto cl = std::stoul(
  22298. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22299. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22300. } else {
  22301. break; // No Content-Length, assume headers-only response
  22302. }
  22303. }
  22304. }
  22305. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22306. // vulnerable server the keep-alive loop reads this as a second request. The
  22307. // server may already have closed the connection, so the result is ignored.
  22308. send(sock, smuggled.data(), smuggled.size(), 0);
  22309. // Half-close so that a server which drained the body sees EOF and closes,
  22310. // instead of the read below waiting for the read timeout.
  22311. #ifdef _WIN32
  22312. ::shutdown(sock, SD_SEND);
  22313. #else
  22314. ::shutdown(sock, SHUT_WR);
  22315. #endif
  22316. // Step 4: Read until the server closes the connection
  22317. for (;;) {
  22318. auto n = recv(sock, buf, sizeof(buf), 0);
  22319. if (n <= 0) break;
  22320. }
  22321. return smuggled_count.load();
  22322. }
  22323. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22324. // A GET request with Content-Length to a static file handler must have its
  22325. // body drained before the keep-alive connection is reused. Otherwise the
  22326. // unread body bytes are interpreted as the next HTTP request.
  22327. std::string first_response;
  22328. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22329. "Host: localhost\r\n"
  22330. "Content-Length: {len}\r\n"
  22331. "\r\n",
  22332. first_response));
  22333. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22334. }
  22335. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22336. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22337. // be answered with 400 and the connection closed. Treating it as "no body"
  22338. // leaves the body to be parsed as the next request.
  22339. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22340. const char *targets[] = {
  22341. "GET /file", // handler that never reads the body
  22342. "GET /not-found", // no handler matches (404)
  22343. "POST /post", // handler that reads the body
  22344. };
  22345. for (auto target : targets) {
  22346. for (auto value : values) {
  22347. std::string first_response;
  22348. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22349. " HTTP/1.1\r\n"
  22350. "Host: localhost\r\n"
  22351. "Content-Length: " +
  22352. value + "\r\n\r\n",
  22353. first_response))
  22354. << target << " with Content-Length: " << value;
  22355. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22356. << target << " with Content-Length: " << value;
  22357. }
  22358. }
  22359. }
  22360. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22361. // A 400 for an unparseable request line leaves the rest of the message
  22362. // unread, so the connection must be closed rather than reused.
  22363. std::string first_response;
  22364. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22365. "Host: localhost\r\n"
  22366. "Content-Length: {len}\r\n"
  22367. "\r\n",
  22368. first_response));
  22369. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22370. }
  22371. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22372. // Same as above for a header block that fails to parse.
  22373. std::string first_response;
  22374. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22375. "Host: localhost\r\n"
  22376. "Bad Header\r\n"
  22377. "Content-Length: {len}\r\n"
  22378. "\r\n",
  22379. first_response));
  22380. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22381. }
  22382. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22383. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22384. // server must not read another request on that connection, even when the
  22385. // request had no body to drain.
  22386. std::string first_response;
  22387. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22388. "Host: localhost\r\n"
  22389. "\r\n",
  22390. first_response));
  22391. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22392. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22393. }
  22394. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22395. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22396. // must be rejected with 400 Bad Request.
  22397. Server svr;
  22398. svr.Post("/test", [&](const Request &, Response &res) {
  22399. res.set_content("ok", "text/plain");
  22400. });
  22401. thread t = thread([&] { svr.listen(HOST, PORT); });
  22402. auto se = detail::scope_exit([&] {
  22403. svr.stop();
  22404. t.join();
  22405. ASSERT_FALSE(svr.is_running());
  22406. });
  22407. svr.wait_until_ready();
  22408. // Exact "chunked"
  22409. {
  22410. auto req = "POST /test HTTP/1.1\r\n"
  22411. "Host: localhost\r\n"
  22412. "Content-Length: 5\r\n"
  22413. "Transfer-Encoding: chunked\r\n"
  22414. "Connection: close\r\n"
  22415. "\r\n"
  22416. "hello";
  22417. std::string response;
  22418. ASSERT_TRUE(send_request(1, req, &response));
  22419. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22420. response.substr(0, response.find("\r\n")));
  22421. }
  22422. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22423. {
  22424. auto req = "POST /test HTTP/1.1\r\n"
  22425. "Host: localhost\r\n"
  22426. "Content-Length: 5\r\n"
  22427. "Transfer-Encoding: gzip, chunked\r\n"
  22428. "Connection: close\r\n"
  22429. "\r\n"
  22430. "hello";
  22431. std::string response;
  22432. ASSERT_TRUE(send_request(1, req, &response));
  22433. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22434. response.substr(0, response.find("\r\n")));
  22435. }
  22436. }
  22437. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22438. Server svr;
  22439. svr.Post("/test", [&](const Request &, Response &res) {
  22440. res.set_content("ok", "text/plain");
  22441. });
  22442. thread t = thread([&] { svr.listen(HOST, PORT); });
  22443. auto se = detail::scope_exit([&] {
  22444. svr.stop();
  22445. t.join();
  22446. ASSERT_FALSE(svr.is_running());
  22447. });
  22448. svr.wait_until_ready();
  22449. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22450. // length cannot be determined, so the server must answer 400 and close
  22451. // rather than treat the request as bodyless and leave the body in the
  22452. // socket for the next request to pick up.
  22453. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22454. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22455. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22456. std::string response;
  22457. ASSERT_TRUE(send_request(1, req, &response));
  22458. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22459. response.substr(0, response.find("\r\n")))
  22460. << transfer_encoding;
  22461. }
  22462. // RFC 9110 5.3: the codings may also be split across several
  22463. // Transfer-Encoding lines, which combine in the order they were received.
  22464. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22465. // just like the single-line "chunked, gzip" above.
  22466. {
  22467. auto req = "POST /test HTTP/1.1\r\n"
  22468. "Host: localhost\r\n"
  22469. "Transfer-Encoding: chunked\r\n"
  22470. "Transfer-Encoding: gzip\r\n"
  22471. "\r\n"
  22472. "0\r\n\r\n";
  22473. std::string response;
  22474. ASSERT_TRUE(send_request(1, req, &response));
  22475. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22476. response.substr(0, response.find("\r\n")));
  22477. }
  22478. // A sequence ending in chunked stays valid.
  22479. auto req = "POST /test HTTP/1.1\r\n"
  22480. "Host: localhost\r\n"
  22481. "Transfer-Encoding: gzip, chunked\r\n"
  22482. "Connection: close\r\n"
  22483. "\r\n"
  22484. "0\r\n\r\n";
  22485. std::string response;
  22486. ASSERT_TRUE(send_request(1, req, &response));
  22487. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22488. // ...including when it is spread over several lines.
  22489. auto split_req = "POST /test HTTP/1.1\r\n"
  22490. "Host: localhost\r\n"
  22491. "Transfer-Encoding: gzip\r\n"
  22492. "Transfer-Encoding: chunked\r\n"
  22493. "Connection: close\r\n"
  22494. "\r\n"
  22495. "0\r\n\r\n";
  22496. std::string split_response;
  22497. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22498. EXPECT_EQ("HTTP/1.1 200 OK",
  22499. split_response.substr(0, split_response.find("\r\n")));
  22500. }
  22501. // Regression for issue #2450: a DELETE without Content-Length on a
  22502. // keep-alive connection must not let the post-response drain consume the
  22503. // next request's bytes.
  22504. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22505. Server svr;
  22506. std::atomic<int> delete_count(0);
  22507. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22508. delete_count++;
  22509. res.status = StatusCode::NoContent_204;
  22510. });
  22511. auto port = svr.bind_to_any_port(HOST);
  22512. thread t = thread([&] { svr.listen_after_bind(); });
  22513. auto se = detail::scope_exit([&] {
  22514. svr.stop();
  22515. t.join();
  22516. });
  22517. svr.wait_until_ready();
  22518. auto error = Error::Success;
  22519. auto sock = detail::create_client_socket(
  22520. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22521. /*connection_timeout_sec=*/2, 0,
  22522. /*read_timeout_sec=*/2, 0,
  22523. /*write_timeout_sec=*/2, 0, std::string(), error);
  22524. ASSERT_NE(INVALID_SOCKET, sock);
  22525. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22526. auto send_request_and_read_response = [&](const std::string &req,
  22527. std::string &out) -> bool {
  22528. auto sent = send(sock, req.data(), req.size(), 0);
  22529. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22530. char buf[4096];
  22531. for (;;) {
  22532. auto n = recv(sock, buf, sizeof(buf), 0);
  22533. if (n <= 0) { return !out.empty(); }
  22534. out.append(buf, static_cast<size_t>(n));
  22535. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22536. }
  22537. };
  22538. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22539. "Host: localhost\r\n"
  22540. "\r\n";
  22541. std::string resp1;
  22542. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22543. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22544. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22545. "Host: localhost\r\n"
  22546. "Connection: close\r\n"
  22547. "\r\n";
  22548. std::string resp2;
  22549. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22550. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22551. EXPECT_EQ(2, delete_count.load());
  22552. }
  22553. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22554. Server svr;
  22555. svr.Post("/ingest", [&](const Request &, Response &res,
  22556. const ContentReader &content_reader) {
  22557. auto consumed = content_reader([](const char *, size_t) { return false; });
  22558. EXPECT_FALSE(consumed);
  22559. res.status = StatusCode::Conflict_409;
  22560. res.set_header("Connection", "close");
  22561. });
  22562. auto port = svr.bind_to_any_port(HOST);
  22563. thread t = thread([&] { svr.listen_after_bind(); });
  22564. auto se = detail::scope_exit([&] {
  22565. svr.stop();
  22566. t.join();
  22567. });
  22568. svr.wait_until_ready();
  22569. auto error = Error::Success;
  22570. auto sock = detail::create_client_socket(
  22571. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22572. /*connection_timeout_sec=*/2, 0,
  22573. /*read_timeout_sec=*/1, 0,
  22574. /*write_timeout_sec=*/2, 0, std::string(), error);
  22575. ASSERT_NE(INVALID_SOCKET, sock);
  22576. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22577. std::string request = "POST /ingest HTTP/1.1\r\n"
  22578. "Host: localhost\r\n"
  22579. "Transfer-Encoding: chunked\r\n"
  22580. "\r\n"
  22581. "4\r\n"
  22582. "data\r\n";
  22583. auto sent = send(sock, request.data(), request.size(), 0);
  22584. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22585. std::string response;
  22586. ssize_t received = 0;
  22587. do {
  22588. char buf[4096];
  22589. received = recv(sock, buf, sizeof(buf), 0);
  22590. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22591. } while (received > 0);
  22592. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22593. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22594. EXPECT_EQ(0, received);
  22595. }
  22596. namespace no_proxy_test {
  22597. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22598. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22599. // calling listen().
  22600. class ScopedServer {
  22601. public:
  22602. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22603. ~ScopedServer() {
  22604. svr_.stop();
  22605. if (th_.joinable()) { th_.join(); }
  22606. }
  22607. Server &svr() { return svr_; }
  22608. int port() const { return port_; }
  22609. void listen() {
  22610. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22611. svr_.wait_until_ready();
  22612. }
  22613. private:
  22614. Server svr_;
  22615. std::thread th_;
  22616. int port_ = 0;
  22617. };
  22618. class ProxyAndTargetServers {
  22619. public:
  22620. ProxyAndTargetServers() {
  22621. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22622. proxy_hits_++;
  22623. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22624. res.set_content("via-proxy", "text/plain");
  22625. });
  22626. target_.Get(".*", [this](const Request &req, Response &res) {
  22627. target_hits_++;
  22628. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22629. res.set_content("direct", "text/plain");
  22630. });
  22631. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22632. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22633. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22634. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22635. proxy_mock_.wait_until_ready();
  22636. target_.wait_until_ready();
  22637. }
  22638. ~ProxyAndTargetServers() {
  22639. proxy_mock_.stop();
  22640. target_.stop();
  22641. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22642. if (target_thread_.joinable()) { target_thread_.join(); }
  22643. }
  22644. Server &proxy_mock() { return proxy_mock_; }
  22645. Server &target() { return target_; }
  22646. int proxy_port() const { return proxy_port_; }
  22647. int target_port() const { return target_port_; }
  22648. int proxy_hits() const { return proxy_hits_.load(); }
  22649. int target_hits() const { return target_hits_.load(); }
  22650. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22651. void reset_counters() {
  22652. proxy_hits_ = 0;
  22653. target_hits_ = 0;
  22654. last_had_proxy_authz_ = false;
  22655. }
  22656. private:
  22657. Server proxy_mock_;
  22658. Server target_;
  22659. std::thread proxy_thread_;
  22660. std::thread target_thread_;
  22661. int proxy_port_ = 0;
  22662. int target_port_ = 0;
  22663. std::atomic<int> proxy_hits_{0};
  22664. std::atomic<int> target_hits_{0};
  22665. std::atomic<bool> last_had_proxy_authz_{false};
  22666. };
  22667. inline std::unique_ptr<Client> make_client(const std::string &host,
  22668. ProxyAndTargetServers &s) {
  22669. auto cli = detail::make_unique<Client>(host, s.target_port());
  22670. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22671. cli->set_proxy("127.0.0.1", s.proxy_port());
  22672. return cli;
  22673. }
  22674. } // namespace no_proxy_test
  22675. using no_proxy_test::make_client;
  22676. using no_proxy_test::ProxyAndTargetServers;
  22677. TEST(NoProxyTest, ExactHostnameBypasses) {
  22678. ProxyAndTargetServers s;
  22679. auto cli = make_client("example.com", s);
  22680. cli->set_no_proxy({"example.com"});
  22681. auto res = cli->Get("/");
  22682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22683. EXPECT_EQ(0, s.proxy_hits());
  22684. EXPECT_EQ(1, s.target_hits());
  22685. }
  22686. TEST(NoProxyTest, SubdomainBypasses) {
  22687. ProxyAndTargetServers s;
  22688. auto cli = make_client("foo.example.com", s);
  22689. cli->set_no_proxy({"example.com"});
  22690. auto res = cli->Get("/");
  22691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22692. EXPECT_EQ(0, s.proxy_hits());
  22693. EXPECT_EQ(1, s.target_hits());
  22694. }
  22695. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22696. // Regression guard: "evilexample.com" must not be considered a subdomain
  22697. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22698. // check would let traffic bypass the proxy and leak credentials direct
  22699. // to the attacker host.
  22700. ProxyAndTargetServers s;
  22701. auto cli = make_client("evilexample.com", s);
  22702. cli->set_no_proxy({"example.com"});
  22703. auto res = cli->Get("/");
  22704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22705. EXPECT_GE(s.proxy_hits(), 1);
  22706. EXPECT_EQ(0, s.target_hits());
  22707. }
  22708. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22709. ProxyAndTargetServers s;
  22710. auto cli = make_client("example.com.evil.com", s);
  22711. cli->set_no_proxy({"example.com"});
  22712. auto res = cli->Get("/");
  22713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22714. EXPECT_GE(s.proxy_hits(), 1);
  22715. EXPECT_EQ(0, s.target_hits());
  22716. }
  22717. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22718. ProxyAndTargetServers s;
  22719. auto cli = make_client("example.com", s);
  22720. cli->set_no_proxy({".example.com"});
  22721. auto res = cli->Get("/");
  22722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22723. EXPECT_EQ(0, s.proxy_hits());
  22724. EXPECT_EQ(1, s.target_hits());
  22725. }
  22726. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22727. ProxyAndTargetServers s;
  22728. auto cli = make_client("Example.COM", s);
  22729. cli->set_no_proxy({"EXAMPLE.com"});
  22730. auto res = cli->Get("/");
  22731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22732. EXPECT_EQ(0, s.proxy_hits());
  22733. EXPECT_EQ(1, s.target_hits());
  22734. }
  22735. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22736. ProxyAndTargetServers s;
  22737. auto cli = make_client("example.com.", s);
  22738. cli->set_no_proxy({"example.com"});
  22739. auto res = cli->Get("/");
  22740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22741. EXPECT_EQ(0, s.proxy_hits());
  22742. EXPECT_EQ(1, s.target_hits());
  22743. }
  22744. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22745. // Trailing dots must be normalized on BOTH sides — host and entry.
  22746. // An implementation that only strips the host-side trailing dot would
  22747. // fail to match host "example.com" against entry "example.com." because
  22748. // a literal substring search would compare 11 chars against 12.
  22749. ProxyAndTargetServers s;
  22750. auto cli = make_client("example.com", s);
  22751. cli->set_no_proxy({"example.com."});
  22752. auto res = cli->Get("/");
  22753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22754. EXPECT_EQ(0, s.proxy_hits());
  22755. EXPECT_EQ(1, s.target_hits());
  22756. }
  22757. TEST(NoProxyTest, WildcardBypassesEverything) {
  22758. ProxyAndTargetServers s;
  22759. auto cli = make_client("anything.invalid.test", s);
  22760. cli->set_no_proxy({"*"});
  22761. auto res = cli->Get("/");
  22762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22763. EXPECT_EQ(0, s.proxy_hits());
  22764. EXPECT_EQ(1, s.target_hits());
  22765. }
  22766. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22767. ProxyAndTargetServers s;
  22768. Client cli("127.0.0.1", s.target_port());
  22769. cli.set_proxy("127.0.0.1", s.proxy_port());
  22770. cli.set_no_proxy({"127.0.0.1"});
  22771. auto res = cli.Get("/");
  22772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22773. EXPECT_EQ(0, s.proxy_hits());
  22774. EXPECT_EQ(1, s.target_hits());
  22775. }
  22776. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22777. ProxyAndTargetServers s;
  22778. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22779. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22780. cli.set_proxy("127.0.0.1", s.proxy_port());
  22781. cli.set_no_proxy({"::1"});
  22782. auto res = cli.Get("/");
  22783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22784. EXPECT_EQ(0, s.proxy_hits());
  22785. EXPECT_EQ(1, s.target_hits());
  22786. }
  22787. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22788. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22789. // must still be recognized as IPv6 for CIDR matching. Implementations
  22790. // that detect IPv6 only when the host begins with '[' would parse the
  22791. // host as a hostname and miss the match.
  22792. ProxyAndTargetServers s;
  22793. Client cli("fe80::1", s.target_port());
  22794. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22795. cli.set_proxy("127.0.0.1", s.proxy_port());
  22796. cli.set_no_proxy({"fe80::/10"});
  22797. auto res = cli.Get("/");
  22798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22799. EXPECT_EQ(0, s.proxy_hits());
  22800. EXPECT_EQ(1, s.target_hits());
  22801. }
  22802. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22803. ProxyAndTargetServers s;
  22804. Client cli("::1", s.target_port());
  22805. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22806. cli.set_proxy("127.0.0.1", s.proxy_port());
  22807. cli.set_no_proxy({"[::1]"});
  22808. auto res = cli.Get("/");
  22809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22810. EXPECT_EQ(0, s.proxy_hits());
  22811. EXPECT_EQ(1, s.target_hits());
  22812. }
  22813. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22814. ProxyAndTargetServers s;
  22815. Client cli("fe80::1", s.target_port());
  22816. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22817. cli.set_proxy("127.0.0.1", s.proxy_port());
  22818. cli.set_no_proxy({"[fe80::]/10"});
  22819. auto res = cli.Get("/");
  22820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22821. EXPECT_EQ(0, s.proxy_hits());
  22822. EXPECT_EQ(1, s.target_hits());
  22823. }
  22824. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22825. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22826. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22827. // tricks via address-family conversion.
  22828. ProxyAndTargetServers s;
  22829. Client cli("::ffff:127.0.0.1", s.target_port());
  22830. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22831. cli.set_proxy("127.0.0.1", s.proxy_port());
  22832. cli.set_no_proxy({"127.0.0.1"});
  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, IPv4CidrMatch) {
  22839. ProxyAndTargetServers s;
  22840. Client cli("127.0.0.1", s.target_port());
  22841. cli.set_proxy("127.0.0.1", s.proxy_port());
  22842. cli.set_no_proxy({"127.0.0.0/8"});
  22843. auto res = cli.Get("/");
  22844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22845. EXPECT_EQ(0, s.proxy_hits());
  22846. EXPECT_EQ(1, s.target_hits());
  22847. }
  22848. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22849. ProxyAndTargetServers s;
  22850. Client cli("127.0.0.1", s.target_port());
  22851. cli.set_proxy("127.0.0.1", s.proxy_port());
  22852. cli.set_no_proxy({"10.0.0.0/8"});
  22853. auto res = cli.Get("/");
  22854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22855. EXPECT_GE(s.proxy_hits(), 1);
  22856. EXPECT_EQ(0, s.target_hits());
  22857. }
  22858. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22859. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22860. // IPv4 target matches.
  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({"0.0.0.0/0"});
  22865. auto res = cli.Get("/");
  22866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22867. EXPECT_EQ(0, s.proxy_hits());
  22868. EXPECT_EQ(1, s.target_hits());
  22869. }
  22870. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22871. ProxyAndTargetServers s;
  22872. Client cli("127.0.0.1", s.target_port());
  22873. cli.set_proxy("127.0.0.1", s.proxy_port());
  22874. cli.set_no_proxy({"127.0.0.1"});
  22875. auto res = cli.Get("/");
  22876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22877. EXPECT_EQ(0, s.proxy_hits());
  22878. EXPECT_EQ(1, s.target_hits());
  22879. }
  22880. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22881. ProxyAndTargetServers s;
  22882. Client cli("127.0.0.1", s.target_port());
  22883. cli.set_proxy("127.0.0.1", s.proxy_port());
  22884. cli.set_no_proxy({"127.0.0.0/33"});
  22885. auto res = cli.Get("/");
  22886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22887. EXPECT_GE(s.proxy_hits(), 1);
  22888. EXPECT_EQ(0, s.target_hits());
  22889. }
  22890. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22891. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22892. ProxyAndTargetServers s;
  22893. Client cli("127.0.0.1", s.target_port());
  22894. cli.set_proxy("127.0.0.1", s.proxy_port());
  22895. cli.set_no_proxy({"127.0.0.1/"});
  22896. auto res = cli.Get("/");
  22897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22898. EXPECT_GE(s.proxy_hits(), 1);
  22899. EXPECT_EQ(0, s.target_hits());
  22900. }
  22901. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22902. ProxyAndTargetServers s;
  22903. auto cli = make_client("internal.corp", s);
  22904. cli->set_proxy_basic_auth("u", "p");
  22905. cli->set_no_proxy({"internal.corp"});
  22906. auto res = cli->Get("/");
  22907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22908. EXPECT_EQ(1, s.target_hits());
  22909. EXPECT_EQ(0, s.proxy_hits());
  22910. EXPECT_FALSE(s.last_had_proxy_authz())
  22911. << "Proxy-Authorization must not be sent direct to the target";
  22912. }
  22913. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22914. ProxyAndTargetServers s;
  22915. auto cli = make_client("public.example", s);
  22916. cli->set_proxy_basic_auth("u", "p");
  22917. cli->set_no_proxy({"internal.corp"}); // does not match
  22918. auto res = cli->Get("/");
  22919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22920. EXPECT_GE(s.proxy_hits(), 1);
  22921. EXPECT_TRUE(s.last_had_proxy_authz());
  22922. }
  22923. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22924. std::atomic<int> hits{0};
  22925. std::atomic<int> hits_with_authz{0};
  22926. no_proxy_test::ScopedServer proxy_mock;
  22927. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22928. hits++;
  22929. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  22930. if (req.target.find("/redir") != std::string::npos) {
  22931. res.set_redirect("http://other.example/landed");
  22932. } else {
  22933. res.set_content("via-proxy", "text/plain");
  22934. }
  22935. });
  22936. proxy_mock.listen();
  22937. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  22938. hits = 0;
  22939. hits_with_authz = 0;
  22940. Client cli("public.example", 80);
  22941. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22942. cli.set_proxy_basic_auth(c.first, c.second);
  22943. cli.set_follow_location(true);
  22944. // The redirect to another host goes through the proxy as well
  22945. auto res = cli.Get("/redir");
  22946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22947. EXPECT_EQ(2, hits.load());
  22948. EXPECT_EQ(2, hits_with_authz.load());
  22949. }
  22950. }
  22951. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22952. ProxyAndTargetServers s;
  22953. auto cli = make_client("anything.test", s);
  22954. auto res = cli->Get("/");
  22955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22956. EXPECT_GE(s.proxy_hits(), 1);
  22957. EXPECT_EQ(0, s.target_hits());
  22958. }
  22959. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22960. ProxyAndTargetServers s;
  22961. auto cli = make_client("example.com", s);
  22962. cli->set_no_proxy({"example.com:8080"});
  22963. auto res = cli->Get("/");
  22964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22965. EXPECT_GE(s.proxy_hits(), 1);
  22966. EXPECT_EQ(0, s.target_hits());
  22967. }
  22968. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22969. ProxyAndTargetServers s;
  22970. auto cli = make_client("anything.test", s);
  22971. cli->set_no_proxy({"", " ", "\t"});
  22972. auto res = cli->Get("/");
  22973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22974. EXPECT_GE(s.proxy_hits(), 1);
  22975. EXPECT_EQ(0, s.target_hits());
  22976. }
  22977. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22978. // An entry with leading/trailing whitespace must still match — env-style
  22979. // values are commonly pasted with stray spaces and an implementation
  22980. // that feeds the raw token directly to inet_pton would fail to match
  22981. // valid CIDRs because of the spaces.
  22982. ProxyAndTargetServers s;
  22983. Client cli("127.0.0.1", s.target_port());
  22984. cli.set_proxy("127.0.0.1", s.proxy_port());
  22985. cli.set_no_proxy({" 127.0.0.0/8 "});
  22986. auto res = cli.Get("/");
  22987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22988. EXPECT_EQ(0, s.proxy_hits());
  22989. EXPECT_EQ(1, s.target_hits());
  22990. }
  22991. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22992. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22993. // go direct and must NOT carry Proxy-Authorization.
  22994. std::atomic<int> proxy_hits{0};
  22995. std::atomic<int> target_hits{0};
  22996. std::atomic<bool> target_saw_authz{false};
  22997. no_proxy_test::ScopedServer proxy_mock, target;
  22998. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22999. proxy_hits++;
  23000. res.status = 302;
  23001. res.set_header("Location", "http://127.0.0.1:" +
  23002. std::to_string(target.port()) + "/landed");
  23003. });
  23004. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23005. target_hits++;
  23006. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23007. res.set_content("direct", "text/plain");
  23008. });
  23009. proxy_mock.listen();
  23010. target.listen();
  23011. Client cli("public.example", target.port());
  23012. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23013. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23014. cli.set_proxy_basic_auth("u", "p");
  23015. cli.set_no_proxy({"127.0.0.1"});
  23016. cli.set_follow_location(true);
  23017. auto res = cli.Get("/redir");
  23018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23019. EXPECT_GE(proxy_hits.load(), 1);
  23020. EXPECT_GE(target_hits.load(), 1);
  23021. EXPECT_FALSE(target_saw_authz.load());
  23022. }
  23023. #ifdef CPPHTTPLIB_SSL_ENABLED
  23024. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23025. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23026. // proxy creds would be sent to the (possibly hostile) origin.
  23027. std::atomic<int> target_hits{0};
  23028. std::atomic<bool> target_saw_proxy_authz{false};
  23029. no_proxy_test::ScopedServer target;
  23030. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23031. target_hits++;
  23032. if (req.has_header("Proxy-Authorization")) {
  23033. target_saw_proxy_authz = true;
  23034. }
  23035. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23036. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23037. "nonce=\"abc\", algorithm=MD5");
  23038. });
  23039. target.listen();
  23040. // The proxy address is set to the target's port: the bypass MUST kick in;
  23041. // if it doesn't, the test still routes "via proxy" to the same server and
  23042. // the Proxy-Authorization assertion below catches the leak.
  23043. Client cli("evil.example", target.port());
  23044. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23045. cli.set_proxy("127.0.0.1", target.port());
  23046. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23047. cli.set_no_proxy({"evil.example"});
  23048. auto res = cli.Get("/x");
  23049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23050. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23051. EXPECT_EQ(1, target_hits.load());
  23052. EXPECT_FALSE(target_saw_proxy_authz.load());
  23053. }
  23054. #endif
  23055. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23056. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23057. std::atomic<int> proxy_hits{0};
  23058. std::atomic<int> bypass_hits{0};
  23059. std::atomic<bool> proxy_saw_c_url{false};
  23060. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23061. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23062. proxy_hits++;
  23063. if (req.path.find("/start") != std::string::npos) {
  23064. res.status = 302;
  23065. res.set_header("Location", "http://127.0.0.1:" +
  23066. std::to_string(bypass_server.port()) +
  23067. "/middle");
  23068. return;
  23069. }
  23070. if (req.path.find("/end") != std::string::npos) {
  23071. proxy_saw_c_url = true;
  23072. res.set_content("c-via-proxy", "text/plain");
  23073. return;
  23074. }
  23075. res.set_content("unexpected", "text/plain");
  23076. });
  23077. // public.example's "advertised" port is arbitrary (the request never lands
  23078. // there — it goes through the proxy), but use a dynamic value to stay
  23079. // friendly with sharded parallel runs.
  23080. int public_port = bypass_server.port();
  23081. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23082. bypass_hits++;
  23083. res.status = 302;
  23084. res.set_header("Location", "http://public.example:" +
  23085. std::to_string(public_port) + "/end");
  23086. });
  23087. proxy_mock.listen();
  23088. bypass_server.listen();
  23089. Client cli("public.example", public_port);
  23090. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23091. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23092. cli.set_no_proxy({"127.0.0.1"});
  23093. cli.set_follow_location(true);
  23094. auto res = cli.Get("/start");
  23095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23096. EXPECT_EQ(StatusCode::OK_200, res->status);
  23097. EXPECT_EQ("c-via-proxy", res->body);
  23098. EXPECT_GE(proxy_hits.load(), 2);
  23099. EXPECT_GE(bypass_hits.load(), 1);
  23100. EXPECT_TRUE(proxy_saw_c_url.load());
  23101. }
  23102. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23103. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23104. // request reconnects to the correct endpoint.
  23105. std::atomic<int> proxy_hits{0};
  23106. std::atomic<int> target_hits{0};
  23107. no_proxy_test::ScopedServer proxy_mock, target;
  23108. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23109. proxy_hits++;
  23110. res.set_content("via-proxy", "text/plain");
  23111. });
  23112. target.svr().Get(".*", [&](const Request &, Response &res) {
  23113. target_hits++;
  23114. res.set_content("direct", "text/plain");
  23115. });
  23116. proxy_mock.listen();
  23117. target.listen();
  23118. Client cli("public.example", target.port());
  23119. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23120. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23121. cli.set_keep_alive(true);
  23122. auto res1 = cli.Get("/a");
  23123. ASSERT_TRUE(res1);
  23124. EXPECT_EQ("via-proxy", res1->body);
  23125. EXPECT_EQ(1, proxy_hits.load());
  23126. EXPECT_EQ(0, target_hits.load());
  23127. cli.set_no_proxy({"public.example"});
  23128. auto res2 = cli.Get("/b");
  23129. ASSERT_TRUE(res2);
  23130. EXPECT_EQ("direct", res2->body);
  23131. EXPECT_EQ(1, proxy_hits.load());
  23132. EXPECT_EQ(1, target_hits.load());
  23133. }
  23134. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23135. namespace proxy_tunnel_test {
  23136. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23137. class ScopedSSLServer {
  23138. public:
  23139. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23140. port_ = svr_.bind_to_any_port("127.0.0.1");
  23141. }
  23142. ~ScopedSSLServer() {
  23143. svr_.stop();
  23144. if (th_.joinable()) { th_.join(); }
  23145. }
  23146. SSLServer &svr() { return svr_; }
  23147. int port() const { return port_; }
  23148. void listen() {
  23149. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23150. svr_.wait_until_ready();
  23151. }
  23152. private:
  23153. SSLServer svr_;
  23154. std::thread th_;
  23155. int port_ = 0;
  23156. };
  23157. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23158. class ScopedConnectProxy {
  23159. public:
  23160. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23161. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23162. if (listen_fd_ < 0) { return; }
  23163. int yes = 1;
  23164. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23165. sockaddr_in a{};
  23166. a.sin_family = AF_INET;
  23167. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23168. a.sin_port = 0;
  23169. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23170. return;
  23171. }
  23172. socklen_t alen = sizeof(a);
  23173. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23174. 0) {
  23175. return;
  23176. }
  23177. port_ = ntohs(a.sin_port);
  23178. if (::listen(listen_fd_, 1) != 0) { return; }
  23179. th_ = std::thread([this] { run(); });
  23180. }
  23181. ~ScopedConnectProxy() {
  23182. stop_ = true;
  23183. if (listen_fd_ >= 0) {
  23184. ::shutdown(listen_fd_, SHUT_RDWR);
  23185. ::close(listen_fd_);
  23186. }
  23187. if (th_.joinable()) { th_.join(); }
  23188. }
  23189. int port() const { return port_; }
  23190. int connect_hits() const { return connect_hits_.load(); }
  23191. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23192. std::string connect_request() const {
  23193. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23194. return connect_request_;
  23195. }
  23196. private:
  23197. void run() {
  23198. while (!stop_.load()) {
  23199. fd_set rfds;
  23200. FD_ZERO(&rfds);
  23201. FD_SET(listen_fd_, &rfds);
  23202. timeval tv{0, 100 * 1000};
  23203. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23204. if (sel <= 0) { continue; }
  23205. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23206. if (client_fd < 0) { continue; }
  23207. std::string req;
  23208. char buf[2048];
  23209. while (req.find("\r\n\r\n") == std::string::npos) {
  23210. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23211. if (n <= 0) { break; }
  23212. req.append(buf, static_cast<size_t>(n));
  23213. }
  23214. if (req.compare(0, 7, "CONNECT") != 0) {
  23215. ::close(client_fd);
  23216. continue;
  23217. }
  23218. connect_hits_++;
  23219. {
  23220. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23221. connect_request_ = req;
  23222. }
  23223. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23224. ::send(client_fd, ok, std::strlen(ok), 0);
  23225. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23226. sockaddr_in o{};
  23227. o.sin_family = AF_INET;
  23228. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23229. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23230. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23231. 0) {
  23232. ::close(client_fd);
  23233. ::close(origin_fd);
  23234. continue;
  23235. }
  23236. auto forward = [](int from, int to) {
  23237. char b[8192];
  23238. for (;;) {
  23239. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23240. if (n <= 0) { break; }
  23241. ssize_t off = 0;
  23242. while (off < n) {
  23243. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23244. if (s <= 0) {
  23245. off = n;
  23246. break;
  23247. }
  23248. off += s;
  23249. }
  23250. }
  23251. ::shutdown(to, SHUT_WR);
  23252. };
  23253. std::thread t1([&] { forward(client_fd, origin_fd); });
  23254. std::thread t2([&] { forward(origin_fd, client_fd); });
  23255. t1.join();
  23256. t2.join();
  23257. ::close(client_fd);
  23258. ::close(origin_fd);
  23259. }
  23260. }
  23261. int forward_port_ = -1;
  23262. int listen_fd_ = -1;
  23263. int port_ = 0;
  23264. std::thread th_;
  23265. std::atomic<bool> stop_{false};
  23266. std::atomic<int> connect_hits_{0};
  23267. mutable std::mutex connect_request_mutex_;
  23268. std::string connect_request_;
  23269. };
  23270. // Sends one request through the CONNECT proxy to the TLS origin with a
  23271. // credential configured for each hop, and checks that each credential reaches
  23272. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23273. // origin's (every header in origin_headers) on the tunnelled request.
  23274. void CredentialsStayWithTheirHop(
  23275. const std::function<void(SSLClient &)> &set_credentials,
  23276. const std::string &scheme,
  23277. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23278. std::atomic<int> origin_hits{0};
  23279. std::atomic<bool> origin_saw_proxy_authz{false};
  23280. std::atomic<bool> origin_saw_headers{false};
  23281. ScopedSSLServer origin;
  23282. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23283. origin_hits++;
  23284. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23285. origin_saw_headers =
  23286. std::all_of(origin_headers.begin(), origin_headers.end(),
  23287. [&](const std::string &h) { return req.has_header(h); });
  23288. res.set_content("ok", "text/plain");
  23289. });
  23290. origin.listen();
  23291. ScopedConnectProxy proxy(origin.port());
  23292. ASSERT_NE(0, proxy.port());
  23293. // Pinned to 127.0.0.1 for the same reason as the test below.
  23294. SSLClient cli("127.0.0.1", origin.port());
  23295. cli.enable_server_certificate_verification(false);
  23296. cli.set_proxy("127.0.0.1", proxy.port());
  23297. set_credentials(cli);
  23298. auto res = cli.Get("/x");
  23299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23300. EXPECT_EQ(StatusCode::OK_200, res->status);
  23301. EXPECT_EQ(1, origin_hits.load());
  23302. EXPECT_EQ(1, proxy.connect_hits());
  23303. EXPECT_TRUE(origin_saw_headers.load());
  23304. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23305. << "Proxy-Authorization must not be sent inside the tunnel";
  23306. auto connect_req = proxy.connect_request();
  23307. EXPECT_NE(std::string::npos,
  23308. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23309. for (const auto &h : origin_headers) {
  23310. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23311. << h << " must not be sent to the proxy on CONNECT";
  23312. }
  23313. }
  23314. } // namespace proxy_tunnel_test
  23315. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23316. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23317. [](SSLClient &cli) {
  23318. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23319. cli.set_basic_auth("origin-user", "origin-pass");
  23320. },
  23321. "Basic");
  23322. }
  23323. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23324. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23325. [](SSLClient &cli) {
  23326. cli.set_proxy_bearer_token_auth("proxy-token");
  23327. cli.set_bearer_token_auth("origin-token");
  23328. },
  23329. "Bearer");
  23330. }
  23331. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23332. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23333. [](SSLClient &cli) {
  23334. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23335. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23336. {"Cookie", "sid=origin-session"},
  23337. {"X-Api-Key", "origin-key"}});
  23338. },
  23339. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23340. }
  23341. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23342. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23343. // retry; otherwise proxy creds would be sent to the origin.
  23344. std::atomic<int> origin_hits{0};
  23345. std::atomic<bool> origin_saw_proxy_authz{false};
  23346. proxy_tunnel_test::ScopedSSLServer origin;
  23347. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23348. origin_hits++;
  23349. if (req.has_header("Proxy-Authorization")) {
  23350. origin_saw_proxy_authz = true;
  23351. }
  23352. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23353. res.set_header("Proxy-Authenticate",
  23354. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23355. "algorithm=MD5");
  23356. });
  23357. origin.listen();
  23358. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23359. ASSERT_NE(0, proxy.port());
  23360. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23361. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23362. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23363. // and answer with its own status, making this test flaky.
  23364. SSLClient cli("127.0.0.1", origin.port());
  23365. cli.enable_server_certificate_verification(false);
  23366. cli.set_proxy("127.0.0.1", proxy.port());
  23367. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23368. auto res = cli.Get("/x");
  23369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23370. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23371. EXPECT_EQ(1, origin_hits.load());
  23372. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23373. EXPECT_EQ(1, proxy.connect_hits());
  23374. }
  23375. #endif