test.cc 904 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901
  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. // Forward declaration (see the base64_encode note).
  10427. namespace httplib {
  10428. namespace detail {
  10429. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10430. const std::string &content_type,
  10431. EncodingType encoding);
  10432. } // namespace detail
  10433. } // namespace httplib
  10434. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10435. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10436. ASSERT_TRUE(mm->is_open());
  10437. Response res;
  10438. detail::set_file_content_provider(res, mm, "text/html",
  10439. detail::EncodingType::None);
  10440. std::string out;
  10441. DataSink sink;
  10442. sink.write = [&](const char *d, size_t l) {
  10443. out.append(d, l);
  10444. return true;
  10445. };
  10446. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10447. EXPECT_EQ("test.html", out);
  10448. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10449. EXPECT_EQ("test.html", out);
  10450. }
  10451. TEST(LongPollingTest, ClientCloseDetection) {
  10452. Server svr;
  10453. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10454. res.set_chunked_content_provider(
  10455. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10456. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10457. sink.os << "hello";
  10458. auto count = 10;
  10459. while (count > 0 && sink.is_writable()) {
  10460. this_thread::sleep_for(chrono::milliseconds(10));
  10461. count--;
  10462. }
  10463. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10464. return true;
  10465. });
  10466. });
  10467. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10468. auto se = detail::scope_exit([&] {
  10469. svr.stop();
  10470. listen_thread.join();
  10471. ASSERT_FALSE(svr.is_running());
  10472. });
  10473. svr.wait_until_ready();
  10474. Client cli("localhost", PORT);
  10475. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10476. EXPECT_EQ("hello", string(data, data_length));
  10477. return false; // close the socket immediately.
  10478. });
  10479. ASSERT_FALSE(res);
  10480. }
  10481. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10482. Server svr;
  10483. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10484. res.set_chunked_content_provider(
  10485. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10486. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10487. sink.os << "hello";
  10488. EXPECT_TRUE(sink.os.good());
  10489. // Wait for the client to close the connection
  10490. auto count = 10;
  10491. while (count > 0 && sink.is_writable()) {
  10492. this_thread::sleep_for(chrono::milliseconds(10));
  10493. count--;
  10494. }
  10495. // After client disconnect, write repeatedly until the socket
  10496. // write actually fails (small writes may be absorbed by the
  10497. // kernel buffer)
  10498. std::string chunk(1024, 'x');
  10499. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10500. sink.os << chunk;
  10501. }
  10502. EXPECT_TRUE(sink.os.fail());
  10503. return true;
  10504. });
  10505. });
  10506. auto port = svr.bind_to_any_port("localhost");
  10507. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10508. auto se = detail::scope_exit([&] {
  10509. svr.stop();
  10510. listen_thread.join();
  10511. ASSERT_FALSE(svr.is_running());
  10512. });
  10513. svr.wait_until_ready();
  10514. Client cli("localhost", port);
  10515. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10516. EXPECT_EQ("hello", string(data, data_length));
  10517. return false; // close the socket immediately.
  10518. });
  10519. ASSERT_FALSE(res);
  10520. }
  10521. TEST(GetWithParametersTest, GetWithParameters) {
  10522. Server svr;
  10523. svr.Get("/", [&](const Request &req, Response &) {
  10524. EXPECT_EQ("world", req.get_param_value("hello"));
  10525. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10526. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10527. });
  10528. svr.Get("/params", [&](const Request &req, Response &) {
  10529. EXPECT_EQ("world", req.get_param_value("hello"));
  10530. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10531. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10532. });
  10533. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10534. EXPECT_EQ("resource-id", req.matches[1]);
  10535. EXPECT_EQ("foo", req.get_param_value("param1"));
  10536. EXPECT_EQ("bar", req.get_param_value("param2"));
  10537. });
  10538. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10539. EXPECT_EQ("user-id", req.path_params.at("id"));
  10540. EXPECT_EQ("foo", req.get_param_value("param1"));
  10541. EXPECT_EQ("bar", req.get_param_value("param2"));
  10542. });
  10543. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10544. auto se = detail::scope_exit([&] {
  10545. svr.stop();
  10546. listen_thread.join();
  10547. ASSERT_FALSE(svr.is_running());
  10548. });
  10549. svr.wait_until_ready();
  10550. {
  10551. Client cli(HOST, PORT);
  10552. Params params;
  10553. params.emplace("hello", "world");
  10554. params.emplace("hello2", "world2");
  10555. params.emplace("hello3", "world3");
  10556. auto res = cli.Get("/", params, Headers{});
  10557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10558. EXPECT_EQ(StatusCode::OK_200, res->status);
  10559. }
  10560. {
  10561. Client cli(HOST, PORT);
  10562. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10564. EXPECT_EQ(StatusCode::OK_200, res->status);
  10565. }
  10566. {
  10567. Client cli(HOST, PORT);
  10568. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10570. EXPECT_EQ(StatusCode::OK_200, res->status);
  10571. }
  10572. {
  10573. Client cli(HOST, PORT);
  10574. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10576. EXPECT_EQ(StatusCode::OK_200, res->status);
  10577. }
  10578. }
  10579. TEST(GetWithParametersTest, GetWithParameters2) {
  10580. Server svr;
  10581. svr.Get("/", [&](const Request &req, Response &res) {
  10582. auto text = req.get_param_value("hello");
  10583. res.set_content(text, "text/plain");
  10584. });
  10585. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10586. auto se = detail::scope_exit([&] {
  10587. svr.stop();
  10588. listen_thread.join();
  10589. ASSERT_FALSE(svr.is_running());
  10590. });
  10591. svr.wait_until_ready();
  10592. Client cli("localhost", PORT);
  10593. Params params;
  10594. params.emplace("hello", "world");
  10595. std::string body;
  10596. auto res = cli.Get("/", params, Headers{},
  10597. [&](const char *data, size_t data_length) {
  10598. body.append(data, data_length);
  10599. return true;
  10600. });
  10601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10602. EXPECT_EQ(StatusCode::OK_200, res->status);
  10603. EXPECT_EQ("world", body);
  10604. }
  10605. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10606. Server svr;
  10607. svr.Get("/search", [&](const Request &req, Response &res) {
  10608. auto q = req.get_param_value("q");
  10609. res.set_content(q, "text/plain");
  10610. });
  10611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10612. auto se = detail::scope_exit([&] {
  10613. svr.stop();
  10614. listen_thread.join();
  10615. ASSERT_FALSE(svr.is_running());
  10616. });
  10617. svr.wait_until_ready();
  10618. Client cli("localhost", PORT);
  10619. // Verify that Get(path, params) works without requiring Headers argument
  10620. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10622. EXPECT_EQ(StatusCode::OK_200, res->status);
  10623. EXPECT_EQ("cpp-httplib", res->body);
  10624. }
  10625. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10626. auto host = "httpbingo.org";
  10627. auto path = std::string{"/range/32"};
  10628. #ifdef CPPHTTPLIB_SSL_ENABLED
  10629. SSLClient cli(host);
  10630. #else
  10631. Client cli(host);
  10632. #endif
  10633. cli.set_default_headers({make_range_header({{1, 10}})});
  10634. cli.set_connection_timeout(5);
  10635. {
  10636. auto res = cli.Get(path);
  10637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10638. EXPECT_EQ("bcdefghijk", res->body);
  10639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10640. }
  10641. {
  10642. auto res = cli.Get(path);
  10643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10644. EXPECT_EQ("bcdefghijk", res->body);
  10645. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10646. }
  10647. }
  10648. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10649. Server svr;
  10650. svr.set_default_headers({{"Hello", "World"}});
  10651. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10652. res.set_content("ok", "text/plain");
  10653. });
  10654. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10655. auto se = detail::scope_exit([&] {
  10656. svr.stop();
  10657. listen_thread.join();
  10658. ASSERT_FALSE(svr.is_running());
  10659. });
  10660. svr.wait_until_ready();
  10661. Client cli("localhost", PORT);
  10662. auto res = cli.Get("/");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::OK_200, res->status);
  10665. EXPECT_EQ("ok", res->body);
  10666. EXPECT_EQ("World", res->get_header_value("Hello"));
  10667. }
  10668. #ifdef CPPHTTPLIB_SSL_ENABLED
  10669. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10671. ASSERT_TRUE(svr.is_valid());
  10672. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10673. std::this_thread::sleep_for(std::chrono::seconds(2));
  10674. res.set_content("a", "text/plain");
  10675. });
  10676. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10677. res.set_content("b", "text/plain");
  10678. });
  10679. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10680. auto se = detail::scope_exit([&] {
  10681. svr.stop();
  10682. listen_thread.join();
  10683. ASSERT_FALSE(svr.is_running());
  10684. });
  10685. svr.wait_until_ready();
  10686. SSLClient cli("localhost", PORT);
  10687. cli.enable_server_certificate_verification(false);
  10688. cli.set_keep_alive(true);
  10689. cli.set_read_timeout(std::chrono::seconds(1));
  10690. auto resa = cli.Get("/a");
  10691. ASSERT_TRUE(!resa);
  10692. EXPECT_EQ(Error::Read, resa.error());
  10693. auto resb = cli.Get("/b");
  10694. ASSERT_TRUE(resb);
  10695. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10696. EXPECT_EQ("b", resb->body);
  10697. }
  10698. // Closing an idle keep-alive connection sends close_notify and returns. The
  10699. // server must not wait for the client's close_notify: an idle client never
  10700. // sends one, so the worker would be held until the read timeout expires, and
  10701. // stop() would wait for it.
  10702. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10704. ASSERT_TRUE(svr.is_valid());
  10705. svr.set_keep_alive_timeout(1);
  10706. svr.set_read_timeout(10, 0);
  10707. svr.Get("/", [](const Request &, Response &res) {
  10708. res.set_content("ok", "text/plain");
  10709. });
  10710. auto port = svr.bind_to_any_port(HOST);
  10711. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10712. auto se = detail::scope_exit([&] {
  10713. if (listen_thread.joinable()) {
  10714. svr.stop();
  10715. listen_thread.join();
  10716. }
  10717. });
  10718. svr.wait_until_ready();
  10719. SSLClient cli(HOST, port);
  10720. cli.enable_server_certificate_verification(false);
  10721. cli.set_keep_alive(true);
  10722. auto res = cli.Get("/");
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. // Stay idle past the keep-alive timeout so the server closes the connection.
  10726. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10727. auto start = std::chrono::steady_clock::now();
  10728. svr.stop();
  10729. listen_thread.join();
  10730. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10731. std::chrono::steady_clock::now() - start)
  10732. .count();
  10733. EXPECT_LT(elapsed, 3000);
  10734. }
  10735. #endif
  10736. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10737. protected:
  10738. ServerTestWithAI_PASSIVE()
  10739. : cli_(HOST, PORT)
  10740. #ifdef CPPHTTPLIB_SSL_ENABLED
  10741. ,
  10742. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10743. #endif
  10744. {
  10745. #ifdef CPPHTTPLIB_SSL_ENABLED
  10746. cli_.enable_server_certificate_verification(false);
  10747. #endif
  10748. }
  10749. virtual void SetUp() {
  10750. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10751. res.set_content("Hello World!", "text/plain");
  10752. });
  10753. t_ = thread(
  10754. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10755. svr_.wait_until_ready();
  10756. }
  10757. virtual void TearDown() {
  10758. svr_.stop();
  10759. t_.join();
  10760. }
  10761. #ifdef CPPHTTPLIB_SSL_ENABLED
  10762. SSLClient cli_;
  10763. SSLServer svr_;
  10764. #else
  10765. Client cli_;
  10766. Server svr_;
  10767. #endif
  10768. thread t_;
  10769. };
  10770. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10771. auto res = cli_.Get("/hi");
  10772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10773. EXPECT_EQ(StatusCode::OK_200, res->status);
  10774. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10775. EXPECT_EQ("Hello World!", res->body);
  10776. }
  10777. class ServerUpDownTest : public ::testing::Test {
  10778. protected:
  10779. ServerUpDownTest() : cli_(HOST, PORT) {}
  10780. virtual void SetUp() {
  10781. t_ = thread([&]() {
  10782. svr_.bind_to_any_port(HOST);
  10783. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10784. ASSERT_TRUE(svr_.listen_after_bind());
  10785. });
  10786. svr_.wait_until_ready();
  10787. }
  10788. virtual void TearDown() {
  10789. svr_.stop();
  10790. t_.join();
  10791. }
  10792. Client cli_;
  10793. Server svr_;
  10794. thread t_;
  10795. };
  10796. TEST_F(ServerUpDownTest, QuickStartStop) {
  10797. // Should not crash, especially when run with
  10798. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10799. }
  10800. class PayloadMaxLengthTest : public ::testing::Test {
  10801. protected:
  10802. PayloadMaxLengthTest()
  10803. : cli_(HOST, PORT)
  10804. #ifdef CPPHTTPLIB_SSL_ENABLED
  10805. ,
  10806. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10807. #endif
  10808. {
  10809. #ifdef CPPHTTPLIB_SSL_ENABLED
  10810. cli_.enable_server_certificate_verification(false);
  10811. #endif
  10812. }
  10813. virtual void SetUp() {
  10814. svr_.set_payload_max_length(8);
  10815. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10816. res.set_content("test", "text/plain");
  10817. });
  10818. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10819. svr_.wait_until_ready();
  10820. }
  10821. virtual void TearDown() {
  10822. svr_.stop();
  10823. t_.join();
  10824. }
  10825. #ifdef CPPHTTPLIB_SSL_ENABLED
  10826. SSLClient cli_;
  10827. SSLServer svr_;
  10828. #else
  10829. Client cli_;
  10830. Server svr_;
  10831. #endif
  10832. thread t_;
  10833. };
  10834. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10835. auto res = cli_.Post("/test", "123456789", "text/plain");
  10836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10837. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10838. res = cli_.Post("/test", "12345678", "text/plain");
  10839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10840. EXPECT_EQ(StatusCode::OK_200, res->status);
  10841. }
  10842. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10843. // Test chunked encoding with payload exceeding the 8-byte limit
  10844. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10845. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10847. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10848. }
  10849. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10850. // Test chunked encoding with payload within the 8-byte limit
  10851. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10852. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10854. EXPECT_EQ(StatusCode::OK_200, res->status);
  10855. }
  10856. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10857. // Test using send_request to send chunked data exceeding payload limit
  10858. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10859. "Host: " +
  10860. std::string(HOST) + ":" + std::to_string(PORT) +
  10861. "\r\n"
  10862. "Transfer-Encoding: chunked\r\n"
  10863. "Connection: close\r\n"
  10864. "\r\n"
  10865. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10866. "0123456789\r\n"
  10867. "0\r\n" // End chunk
  10868. "\r\n";
  10869. std::string response;
  10870. bool result = send_request(1, chunked_request, &response);
  10871. if (!result) {
  10872. // If send_request fails, it might be because the server closed the
  10873. // connection due to payload limit enforcement, which is acceptable
  10874. SUCCEED()
  10875. << "Server rejected oversized chunked request (connection closed)";
  10876. } else {
  10877. // If we got a response, check if it's an error response or connection was
  10878. // closed early Short response length indicates connection was closed due to
  10879. // payload limit
  10880. if (response.length() <= 10) {
  10881. SUCCEED() << "Server closed connection for oversized chunked request";
  10882. } else {
  10883. // Check for error status codes
  10884. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10885. response.find("Payload Too Large") != std::string::npos ||
  10886. response.find("400") != std::string::npos);
  10887. }
  10888. }
  10889. }
  10890. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10891. // Test request without Content-Length header exceeding payload limit
  10892. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10893. "Host: " +
  10894. std::string(HOST) + ":" +
  10895. std::to_string(PORT) +
  10896. "\r\n"
  10897. "Connection: close\r\n"
  10898. "\r\n";
  10899. // Add payload exceeding the 8-byte limit
  10900. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10901. request_without_content_length += large_payload;
  10902. std::string response;
  10903. bool result = send_request(1, request_without_content_length, &response);
  10904. if (!result) {
  10905. // If send_request fails, server likely closed connection due to payload
  10906. // limit
  10907. SUCCEED() << "Server rejected oversized request without Content-Length "
  10908. "(connection closed)";
  10909. } else {
  10910. // Check if server responded with error or closed connection early
  10911. if (response.length() <= 10) {
  10912. SUCCEED() << "Server closed connection for oversized request without "
  10913. "Content-Length";
  10914. } else {
  10915. // Check for error status codes
  10916. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10917. response.find("Payload Too Large") != std::string::npos ||
  10918. response.find("400") != std::string::npos);
  10919. }
  10920. }
  10921. }
  10922. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10923. // Test request without Content-Length header within payload limit
  10924. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10925. "Host: " +
  10926. std::string(HOST) + ":" +
  10927. std::to_string(PORT) +
  10928. "\r\n"
  10929. "Connection: close\r\n"
  10930. "\r\n";
  10931. // Add payload within the 8-byte limit
  10932. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10933. request_without_content_length += small_payload;
  10934. std::string response;
  10935. bool result = send_request(1, request_without_content_length, &response);
  10936. // For requests without Content-Length, the server may have different behavior
  10937. // The key is that it should not reject due to payload limit for small
  10938. // payloads
  10939. if (result) {
  10940. // Check for any HTTP response (success or error, but not connection closed)
  10941. if (response.length() > 10) {
  10942. SUCCEED()
  10943. << "Server processed request without Content-Length within limit";
  10944. } else {
  10945. // Short response might indicate connection closed, which is acceptable
  10946. SUCCEED() << "Server closed connection for request without "
  10947. "Content-Length (acceptable behavior)";
  10948. }
  10949. } else {
  10950. // Connection failure might be due to protocol requirements
  10951. SUCCEED() << "Connection issue with request without Content-Length "
  10952. "(environment-specific)";
  10953. }
  10954. }
  10955. class LargePayloadMaxLengthTest : public ::testing::Test {
  10956. protected:
  10957. LargePayloadMaxLengthTest()
  10958. : cli_(HOST, PORT)
  10959. #ifdef CPPHTTPLIB_SSL_ENABLED
  10960. ,
  10961. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10962. #endif
  10963. {
  10964. #ifdef CPPHTTPLIB_SSL_ENABLED
  10965. cli_.enable_server_certificate_verification(false);
  10966. #endif
  10967. }
  10968. virtual void SetUp() {
  10969. // Set 10MB payload limit
  10970. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10971. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10972. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10973. res.set_content("Large payload test", "text/plain");
  10974. });
  10975. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10976. svr_.wait_until_ready();
  10977. }
  10978. virtual void TearDown() {
  10979. svr_.stop();
  10980. t_.join();
  10981. }
  10982. #ifdef CPPHTTPLIB_SSL_ENABLED
  10983. SSLClient cli_;
  10984. SSLServer svr_;
  10985. #else
  10986. Client cli_;
  10987. Server svr_;
  10988. #endif
  10989. thread t_;
  10990. };
  10991. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10992. // Test chunked encoding with payload within 10MB limit
  10993. std::string medium_payload(5 * 1024 * 1024,
  10994. 'A'); // 5MB payload, within 10MB limit
  10995. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10997. EXPECT_EQ(StatusCode::OK_200, res->status);
  10998. }
  10999. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11000. // Test chunked encoding with payload exceeding 10MB limit
  11001. std::string large_payload(12 * 1024 * 1024,
  11002. 'B'); // 12MB payload, exceeds 10MB limit
  11003. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11004. // Server may either return 413 or close the connection
  11005. if (res) {
  11006. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11007. } else {
  11008. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11009. }
  11010. }
  11011. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11012. // Test request without Content-Length header within 10MB limit
  11013. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11014. "Host: " +
  11015. std::string(HOST) + ":" +
  11016. std::to_string(PORT) +
  11017. "\r\n"
  11018. "Connection: close\r\n"
  11019. "\r\n";
  11020. // Add 1MB payload (within 10MB limit)
  11021. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11022. request_without_content_length += medium_payload;
  11023. std::string response;
  11024. bool result = send_request(5, request_without_content_length, &response);
  11025. if (result) {
  11026. // Should get a proper HTTP response for payloads within limit
  11027. if (response.length() > 10) {
  11028. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11029. "10MB limit";
  11030. } else {
  11031. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11032. "Content-Length)";
  11033. }
  11034. } else {
  11035. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11036. }
  11037. }
  11038. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11039. // Test request without Content-Length header exceeding 10MB limit
  11040. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11041. "Host: " +
  11042. std::string(HOST) + ":" +
  11043. std::to_string(PORT) +
  11044. "\r\n"
  11045. "Connection: close\r\n"
  11046. "\r\n";
  11047. // Add 12MB payload (exceeds 10MB limit)
  11048. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11049. request_without_content_length += large_payload;
  11050. std::string response;
  11051. bool result = send_request(10, request_without_content_length, &response);
  11052. if (!result) {
  11053. // Server should close connection due to payload limit
  11054. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11055. "(connection closed)";
  11056. } else {
  11057. // Check for error response
  11058. if (response.length() <= 10) {
  11059. SUCCEED()
  11060. << "Server closed connection for 12MB request exceeding 10MB limit";
  11061. } else {
  11062. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11063. response.find("Payload Too Large") != std::string::npos ||
  11064. response.find("400") != std::string::npos);
  11065. }
  11066. }
  11067. }
  11068. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11069. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11070. // path.
  11071. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11072. Server svr;
  11073. const size_t LIMIT = 64 * 1024; // 64KB
  11074. svr.set_payload_max_length(LIMIT);
  11075. size_t total = 0;
  11076. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11077. const ContentReader &content_reader) {
  11078. content_reader([&](const char * /*data*/, size_t len) {
  11079. total += len;
  11080. return true;
  11081. });
  11082. res.status = 200;
  11083. res.set_content("stream_ok", "text/plain");
  11084. });
  11085. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11086. auto se = detail::scope_exit([&] {
  11087. svr.stop();
  11088. thread.join();
  11089. ASSERT_FALSE(svr.is_running());
  11090. });
  11091. svr.wait_until_ready();
  11092. // Prepare 256KB raw data and gzip-compress it
  11093. std::string raw(256 * 1024, 'A');
  11094. std::string gz;
  11095. {
  11096. z_stream zs{};
  11097. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11098. Z_DEFAULT_STRATEGY);
  11099. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11100. zs.avail_in = static_cast<uInt>(raw.size());
  11101. char outbuf[4096];
  11102. int ret;
  11103. do {
  11104. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11105. zs.avail_out = sizeof(outbuf);
  11106. ret = deflate(&zs, Z_FINISH);
  11107. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11108. } while (ret != Z_STREAM_END);
  11109. deflateEnd(&zs);
  11110. }
  11111. Client cli(HOST, PORT);
  11112. cli.set_connection_timeout(std::chrono::seconds(5));
  11113. Headers headers = {{"Content-Encoding", "gzip"}};
  11114. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11115. "application/octet-stream");
  11116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11117. // Server must reject oversized decompressed payloads with 413.
  11118. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11119. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11120. EXPECT_LE(total, LIMIT);
  11121. }
  11122. #ifndef CPPHTTPLIB_SSL_ENABLED
  11123. // For a request with neither Content-Length nor Transfer-Encoding, the
  11124. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11125. // compressed wire bytes straight to the ContentReader without ever routing
  11126. // them through the decompressor, so payload_max_length_ only bounded the
  11127. // compressed size on the wire, not the decompressed size.
  11128. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11129. Server svr;
  11130. const size_t LIMIT = 64 * 1024; // 64KB
  11131. svr.set_payload_max_length(LIMIT);
  11132. size_t total = 0;
  11133. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11134. const ContentReader &content_reader) {
  11135. content_reader([&](const char * /*data*/, size_t len) {
  11136. total += len;
  11137. return true;
  11138. });
  11139. res.status = 200;
  11140. res.set_content("stream_ok", "text/plain");
  11141. });
  11142. auto port = svr.bind_to_any_port(HOST);
  11143. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11144. auto se = detail::scope_exit([&] {
  11145. svr.stop();
  11146. thread.join();
  11147. ASSERT_FALSE(svr.is_running());
  11148. });
  11149. svr.wait_until_ready();
  11150. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11151. // StreamingGzipDecompression test above.
  11152. std::string raw(256 * 1024, 'A');
  11153. std::string gz;
  11154. {
  11155. httplib::detail::gzip_compressor compressor;
  11156. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11157. [&](const char *chunk, size_t len) {
  11158. gz.append(chunk, len);
  11159. return true;
  11160. });
  11161. ASSERT_TRUE(result);
  11162. }
  11163. // Send the gzip body over raw TCP with neither Content-Length nor
  11164. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11165. // kicks in.
  11166. std::string req = "POST /stream HTTP/1.1\r\n"
  11167. "Host: " +
  11168. std::string(HOST) + ":" + std::to_string(port) +
  11169. "\r\n"
  11170. "Content-Encoding: gzip\r\n"
  11171. "Connection: close\r\n"
  11172. "\r\n" +
  11173. gz;
  11174. std::string response;
  11175. ASSERT_TRUE(send_request(5, req, &response, port));
  11176. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11177. EXPECT_LE(total, LIMIT);
  11178. }
  11179. #endif
  11180. #endif
  11181. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11182. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11183. // the payload must be passed through untouched instead of being rejected.
  11184. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11185. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11186. Server svr;
  11187. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11188. res.set_content(body, "image/jpeg");
  11189. res.set_header("Content-Encoding", "UTF-8");
  11190. });
  11191. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11192. res.set_content(body, "image/jpeg");
  11193. res.set_header("Content-Encoding", "identity");
  11194. });
  11195. svr.Post("/echo", [](const Request &req, Response &res) {
  11196. res.set_content(req.body, "image/jpeg");
  11197. });
  11198. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11199. auto se = detail::scope_exit([&] {
  11200. svr.stop();
  11201. t.join();
  11202. ASSERT_FALSE(svr.is_running());
  11203. });
  11204. svr.wait_until_ready();
  11205. Client cli(HOST, PORT);
  11206. {
  11207. auto res = cli.Get("/image");
  11208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. EXPECT_EQ(body, res->body);
  11211. }
  11212. {
  11213. auto res = cli.Get("/identity");
  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. // The same applies to a request body reaching the server.
  11220. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11221. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11223. EXPECT_EQ(StatusCode::OK_200, res->status);
  11224. EXPECT_EQ(body, res->body);
  11225. }
  11226. }
  11227. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11228. // gzip-encoded response even when the build has no zlib support.
  11229. static const char GZIPPED_HELLO_WORLD[] = {
  11230. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11231. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11232. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11233. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11234. // A content coding is a whole token, not something the field value merely
  11235. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11236. // as "fibre" look like Brotli, and turned a multi-coding value like
  11237. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11238. // it was never meant to see.
  11239. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11240. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11241. Server svr;
  11242. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11243. res.set_content(body, "image/jpeg");
  11244. res.set_header("Content-Encoding", "fibre");
  11245. });
  11246. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11247. res.set_content(body, "image/jpeg");
  11248. res.set_header("Content-Encoding", "gzip, br");
  11249. });
  11250. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11251. res.set_content(body, "image/jpeg");
  11252. res.set_header("Content-Encoding", "x-zstd-ish");
  11253. });
  11254. auto port = svr.bind_to_any_port(HOST);
  11255. thread t = thread([&]() { svr.listen_after_bind(); });
  11256. auto se = detail::scope_exit([&] {
  11257. svr.stop();
  11258. t.join();
  11259. ASSERT_FALSE(svr.is_running());
  11260. });
  11261. svr.wait_until_ready();
  11262. Client cli(HOST, port);
  11263. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11264. auto res = cli.Get(path);
  11265. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11266. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11267. // Not a coding we recognize, so the payload comes back untouched
  11268. EXPECT_EQ(body, res->body) << path;
  11269. }
  11270. }
  11271. // A content coding cpp-httplib recognizes but was not built with must be
  11272. // reported as such. Handing the still-compressed payload back to the caller
  11273. // would silently corrupt it.
  11274. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11275. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11276. Server svr;
  11277. // "image/jpeg" keeps the server from applying a content coding of its own,
  11278. // so the hand-crafted Content-Encoding below survives.
  11279. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11280. res.set_content(gzipped, "image/jpeg");
  11281. res.set_header("Content-Encoding", "gzip");
  11282. });
  11283. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11284. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11285. res.set_content(gzipped, "image/jpeg");
  11286. res.set_header("Content-Encoding", "GZIP");
  11287. });
  11288. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11289. auto se = detail::scope_exit([&] {
  11290. svr.stop();
  11291. t.join();
  11292. ASSERT_FALSE(svr.is_running());
  11293. });
  11294. svr.wait_until_ready();
  11295. Client cli(HOST, PORT);
  11296. {
  11297. auto res = cli.Get("/gzipped");
  11298. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11300. EXPECT_EQ("Hello World!", res->body);
  11301. #else
  11302. ASSERT_FALSE(res);
  11303. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11304. #endif
  11305. }
  11306. {
  11307. // open_stream() must behave the same way.
  11308. auto handle = cli.open_stream("GET", "/gzipped");
  11309. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11310. ASSERT_TRUE(handle.is_valid());
  11311. std::string received;
  11312. char buf[256];
  11313. ssize_t n;
  11314. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11315. received.append(buf, static_cast<size_t>(n));
  11316. }
  11317. EXPECT_EQ("Hello World!", received);
  11318. #else
  11319. EXPECT_FALSE(handle.is_valid());
  11320. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11321. #endif
  11322. }
  11323. {
  11324. // A differently-cased coding must not be mistaken for an unknown one, or
  11325. // the body would be handed back still compressed.
  11326. auto res = cli.Get("/gzipped-uppercase");
  11327. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11329. EXPECT_EQ("Hello World!", res->body);
  11330. #else
  11331. ASSERT_FALSE(res);
  11332. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11333. #endif
  11334. }
  11335. }
  11336. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11337. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11338. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11339. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11340. // body a second time and appending a second Content-Encoding field line, so
  11341. // clients that decode one coding per listed value handed back raw gzip bytes.
  11342. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11343. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11344. Server svr;
  11345. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11346. // keeps the server from applying a coding of its own.
  11347. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11348. res.set_content(gzipped, "text/plain");
  11349. res.set_header("Content-Encoding", "gzip");
  11350. });
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. thread t = thread([&]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. t.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. Headers headers = {{"Accept-Encoding", "gzip"}};
  11361. auto res = cli.Get("/pre-gzipped", headers);
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. EXPECT_EQ(StatusCode::OK_200, res->status);
  11364. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11365. EXPECT_EQ("Hello World!", res->body);
  11366. }
  11367. // A chunked provider settles its coding where the headers are written and
  11368. // reuses it at write time. Both ends of that have to hold: a handler's own
  11369. // Content-Encoding suppresses the coding, and a response without one is still
  11370. // compressed as it always was.
  11371. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11372. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11373. const std::string plain = "Hello World! Hello World! Hello World!";
  11374. Server svr;
  11375. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11376. res.set_header("Content-Encoding", "gzip");
  11377. res.set_chunked_content_provider(
  11378. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11379. sink.write(gzipped.data(), gzipped.size());
  11380. sink.done();
  11381. return true;
  11382. });
  11383. });
  11384. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11385. res.set_chunked_content_provider(
  11386. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11387. sink.write(plain.data(), plain.size());
  11388. sink.done();
  11389. return true;
  11390. });
  11391. });
  11392. auto port = svr.bind_to_any_port(HOST);
  11393. thread t = thread([&]() { svr.listen_after_bind(); });
  11394. auto se = detail::scope_exit([&] {
  11395. svr.stop();
  11396. t.join();
  11397. ASSERT_FALSE(svr.is_running());
  11398. });
  11399. svr.wait_until_ready();
  11400. Client cli(HOST, port);
  11401. Headers headers = {{"Accept-Encoding", "gzip"}};
  11402. {
  11403. auto res = cli.Get("/pre-gzipped", headers);
  11404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11405. EXPECT_EQ(StatusCode::OK_200, res->status);
  11406. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11407. EXPECT_EQ("Hello World!", res->body);
  11408. }
  11409. {
  11410. auto res = cli.Get("/negotiated", headers);
  11411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11412. EXPECT_EQ(StatusCode::OK_200, res->status);
  11413. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11414. EXPECT_EQ(plain, res->body);
  11415. }
  11416. }
  11417. #endif
  11418. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11419. // the same message as the comma-joined one, so both have to be read the same
  11420. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11421. // single gzip coding, and a body the sender says was encoded twice was handed
  11422. // back after one pass, still compressed but presented as decoded.
  11423. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11424. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11425. Server svr;
  11426. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11427. res.set_content(body, "image/jpeg");
  11428. res.headers.emplace("Content-Encoding", "gzip");
  11429. res.headers.emplace("Content-Encoding", "gzip");
  11430. });
  11431. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11432. res.set_content(body, "image/jpeg");
  11433. res.set_header("Content-Encoding", "gzip, gzip");
  11434. });
  11435. auto port = svr.bind_to_any_port(HOST);
  11436. thread t = thread([&]() { svr.listen_after_bind(); });
  11437. auto se = detail::scope_exit([&] {
  11438. svr.stop();
  11439. t.join();
  11440. ASSERT_FALSE(svr.is_running());
  11441. });
  11442. svr.wait_until_ready();
  11443. Client cli(HOST, port);
  11444. // Two codings is not something cpp-httplib decodes, so both representations
  11445. // take the pass-through path rather than one of them being gunzipped once.
  11446. for (const char *path : {"/split", "/joined"}) {
  11447. auto res = cli.Get(path);
  11448. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11449. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11450. EXPECT_EQ(body, res->body) << path;
  11451. }
  11452. }
  11453. // Regression test for DoS vulnerability: a malicious server sending a response
  11454. // without Content-Length header must not cause unbounded memory consumption on
  11455. // the client side. The client should stop reading after a reasonable limit,
  11456. // similar to the server-side set_payload_max_length protection.
  11457. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11458. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11459. #ifndef _WIN32
  11460. signal(SIGPIPE, SIG_IGN);
  11461. #endif
  11462. auto server_thread = std::thread([] {
  11463. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11464. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11465. default_socket_options(srv);
  11466. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11467. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11468. sockaddr_in addr{};
  11469. addr.sin_family = AF_INET;
  11470. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11471. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11472. int opt = 1;
  11473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11474. #ifdef _WIN32
  11475. reinterpret_cast<const char *>(&opt),
  11476. #else
  11477. &opt,
  11478. #endif
  11479. sizeof(opt));
  11480. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11481. ::listen(srv, 1);
  11482. sockaddr_in cli_addr{};
  11483. socklen_t cli_len = sizeof(cli_addr);
  11484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11485. if (cli != INVALID_SOCKET) {
  11486. char buf[4096];
  11487. ::recv(cli, buf, sizeof(buf), 0);
  11488. // Malicious response: no Content-Length, no chunked encoding
  11489. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11490. "Connection: close\r\n"
  11491. "\r\n";
  11492. ::send(cli,
  11493. #ifdef _WIN32
  11494. static_cast<const char *>(response_header.c_str()),
  11495. static_cast<int>(response_header.size()),
  11496. #else
  11497. response_header.c_str(), response_header.size(),
  11498. #endif
  11499. 0);
  11500. // Send 10MB of data
  11501. std::string chunk(64 * 1024, 'A');
  11502. size_t total_sent = 0;
  11503. while (total_sent < MALICIOUS_DATA_SIZE) {
  11504. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11505. auto sent = ::send(cli,
  11506. #ifdef _WIN32
  11507. static_cast<const char *>(chunk.c_str()),
  11508. static_cast<int>(to_send),
  11509. #else
  11510. chunk.c_str(), to_send,
  11511. #endif
  11512. 0);
  11513. if (sent <= 0) break;
  11514. total_sent += static_cast<size_t>(sent);
  11515. }
  11516. detail::close_socket(cli);
  11517. }
  11518. detail::close_socket(srv);
  11519. });
  11520. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11521. size_t total_read = 0;
  11522. {
  11523. Client cli("127.0.0.1", PORT + 2);
  11524. cli.set_read_timeout(5, 0);
  11525. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11526. auto stream = cli.open_stream("GET", "/malicious");
  11527. ASSERT_TRUE(stream.is_valid());
  11528. char buffer[64 * 1024];
  11529. ssize_t n;
  11530. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11531. total_read += static_cast<size_t>(n);
  11532. }
  11533. } // StreamHandle and Client destroyed here, closing the socket
  11534. server_thread.join();
  11535. // With set_payload_max_length, the client must stop reading before consuming
  11536. // all 10MB. The read loop should be cut off at or near the configured limit.
  11537. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11538. << "Client read " << total_read << " bytes, exceeding the configured "
  11539. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11540. }
  11541. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11542. // the entire response body without truncation.
  11543. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11544. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11545. #ifndef _WIN32
  11546. signal(SIGPIPE, SIG_IGN);
  11547. #endif
  11548. auto server_thread = std::thread([] {
  11549. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11550. default_socket_options(srv);
  11551. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11552. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11553. sockaddr_in addr{};
  11554. addr.sin_family = AF_INET;
  11555. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11556. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11557. int opt = 1;
  11558. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11559. #ifdef _WIN32
  11560. reinterpret_cast<const char *>(&opt),
  11561. #else
  11562. &opt,
  11563. #endif
  11564. sizeof(opt));
  11565. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11566. ::listen(srv, 1);
  11567. sockaddr_in cli_addr{};
  11568. socklen_t cli_len = sizeof(cli_addr);
  11569. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11570. if (cli != INVALID_SOCKET) {
  11571. char buf[4096];
  11572. ::recv(cli, buf, sizeof(buf), 0);
  11573. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11574. "Connection: close\r\n"
  11575. "\r\n";
  11576. ::send(cli,
  11577. #ifdef _WIN32
  11578. static_cast<const char *>(response_header.c_str()),
  11579. static_cast<int>(response_header.size()),
  11580. #else
  11581. response_header.c_str(), response_header.size(),
  11582. #endif
  11583. 0);
  11584. std::string chunk(64 * 1024, 'A');
  11585. size_t total_sent = 0;
  11586. while (total_sent < DATA_SIZE) {
  11587. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11588. auto sent = ::send(cli,
  11589. #ifdef _WIN32
  11590. static_cast<const char *>(chunk.c_str()),
  11591. static_cast<int>(to_send),
  11592. #else
  11593. chunk.c_str(), to_send,
  11594. #endif
  11595. 0);
  11596. if (sent <= 0) break;
  11597. total_sent += static_cast<size_t>(sent);
  11598. }
  11599. #ifdef _WIN32
  11600. ::shutdown(cli, SD_SEND);
  11601. #else
  11602. ::shutdown(cli, SHUT_WR);
  11603. #endif
  11604. // Drain until the client closes its end, ensuring all data is delivered
  11605. char drain[1024];
  11606. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11607. detail::close_socket(cli);
  11608. }
  11609. detail::close_socket(srv);
  11610. });
  11611. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11612. size_t total_read = 0;
  11613. {
  11614. Client cli("127.0.0.1", PORT + 2);
  11615. cli.set_read_timeout(5, 0);
  11616. cli.set_payload_max_length(0); // 0 means no limit
  11617. auto stream = cli.open_stream("GET", "/data");
  11618. ASSERT_TRUE(stream.is_valid());
  11619. char buffer[64 * 1024];
  11620. ssize_t n;
  11621. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11622. total_read += static_cast<size_t>(n);
  11623. }
  11624. }
  11625. server_thread.join();
  11626. EXPECT_EQ(total_read, DATA_SIZE)
  11627. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11628. << " bytes without truncation, but only read " << total_read << " bytes.";
  11629. }
  11630. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11631. // enormous Content-Length must not cause the client to pre-allocate a huge
  11632. // response body buffer. The reservation is capped at payload_max_length_, and
  11633. // the read itself fails when the body exceeds the limit.
  11634. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11635. #ifndef _WIN32
  11636. signal(SIGPIPE, SIG_IGN);
  11637. #endif
  11638. auto server_thread = std::thread([] {
  11639. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11640. default_socket_options(srv);
  11641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11642. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11643. sockaddr_in addr{};
  11644. addr.sin_family = AF_INET;
  11645. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11646. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11647. int opt = 1;
  11648. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11649. #ifdef _WIN32
  11650. reinterpret_cast<const char *>(&opt),
  11651. #else
  11652. &opt,
  11653. #endif
  11654. sizeof(opt));
  11655. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11656. ::listen(srv, 1);
  11657. sockaddr_in cli_addr{};
  11658. socklen_t cli_len = sizeof(cli_addr);
  11659. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11660. if (cli != INVALID_SOCKET) {
  11661. char buf[4096];
  11662. ::recv(cli, buf, sizeof(buf), 0);
  11663. // Malicious response: claim a 20GB body but send only a tiny payload.
  11664. std::string response = "HTTP/1.1 200 OK\r\n"
  11665. "Content-Length: 20000000000\r\n"
  11666. "\r\n"
  11667. "abc";
  11668. ::send(cli,
  11669. #ifdef _WIN32
  11670. static_cast<const char *>(response.c_str()),
  11671. static_cast<int>(response.size()),
  11672. #else
  11673. response.c_str(), response.size(),
  11674. #endif
  11675. 0);
  11676. detail::close_socket(cli);
  11677. }
  11678. detail::close_socket(srv);
  11679. });
  11680. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11681. {
  11682. Client cli("127.0.0.1", PORT + 2);
  11683. cli.set_read_timeout(5, 0);
  11684. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11685. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11686. // (server claims more bytes than payload_max_length permits), but it must
  11687. // not exhaust memory before getting there.
  11688. auto res = cli.Get("/malicious");
  11689. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11690. }
  11691. server_thread.join();
  11692. }
  11693. // Verify that content_receiver bypasses the default payload_max_length,
  11694. // allowing streaming downloads larger than 100MB without requiring an explicit
  11695. // set_payload_max_length call.
  11696. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11697. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11698. #ifndef _WIN32
  11699. signal(SIGPIPE, SIG_IGN);
  11700. #endif
  11701. auto server_thread = std::thread([] {
  11702. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11703. default_socket_options(srv);
  11704. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11705. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11706. sockaddr_in addr{};
  11707. addr.sin_family = AF_INET;
  11708. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11709. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11710. int opt = 1;
  11711. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11712. #ifdef _WIN32
  11713. reinterpret_cast<const char *>(&opt),
  11714. #else
  11715. &opt,
  11716. #endif
  11717. sizeof(opt));
  11718. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11719. ::listen(srv, 1);
  11720. sockaddr_in cli_addr{};
  11721. socklen_t cli_len = sizeof(cli_addr);
  11722. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11723. if (cli != INVALID_SOCKET) {
  11724. char buf[4096];
  11725. ::recv(cli, buf, sizeof(buf), 0);
  11726. // Response with Content-Length larger than default 100MB limit
  11727. auto content_length = std::to_string(DATA_SIZE);
  11728. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11729. "Content-Length: " +
  11730. content_length +
  11731. "\r\n"
  11732. "Connection: close\r\n"
  11733. "\r\n";
  11734. ::send(cli,
  11735. #ifdef _WIN32
  11736. static_cast<const char *>(response_header.c_str()),
  11737. static_cast<int>(response_header.size()),
  11738. #else
  11739. response_header.c_str(), response_header.size(),
  11740. #endif
  11741. 0);
  11742. std::string chunk(64 * 1024, 'A');
  11743. size_t total_sent = 0;
  11744. while (total_sent < DATA_SIZE) {
  11745. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11746. auto sent = ::send(cli,
  11747. #ifdef _WIN32
  11748. static_cast<const char *>(chunk.c_str()),
  11749. static_cast<int>(to_send),
  11750. #else
  11751. chunk.c_str(), to_send,
  11752. #endif
  11753. 0);
  11754. if (sent <= 0) break;
  11755. total_sent += static_cast<size_t>(sent);
  11756. }
  11757. detail::close_socket(cli);
  11758. }
  11759. detail::close_socket(srv);
  11760. });
  11761. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11762. size_t total_received = 0;
  11763. {
  11764. Client cli("127.0.0.1", PORT + 2);
  11765. cli.set_read_timeout(10, 0);
  11766. // Do NOT call set_payload_max_length — use the default 100MB limit
  11767. auto res =
  11768. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11769. total_received += data_length;
  11770. return true;
  11771. });
  11772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11773. EXPECT_EQ(StatusCode::OK_200, res->status);
  11774. }
  11775. server_thread.join();
  11776. EXPECT_EQ(total_received, DATA_SIZE)
  11777. << "With content_receiver, the client should read all " << DATA_SIZE
  11778. << " bytes despite the default 100MB payload_max_length, but only read "
  11779. << total_received << " bytes.";
  11780. }
  11781. // Verify that an explicit set_payload_max_length smaller than the response is
  11782. // enforced even when a content_receiver is used.
  11783. TEST(ClientVulnerabilityTest,
  11784. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11785. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11786. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11787. #ifndef _WIN32
  11788. signal(SIGPIPE, SIG_IGN);
  11789. #endif
  11790. auto server_thread = std::thread([] {
  11791. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11792. default_socket_options(srv);
  11793. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11794. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11795. sockaddr_in addr{};
  11796. addr.sin_family = AF_INET;
  11797. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11798. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11799. int opt = 1;
  11800. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11801. #ifdef _WIN32
  11802. reinterpret_cast<const char *>(&opt),
  11803. #else
  11804. &opt,
  11805. #endif
  11806. sizeof(opt));
  11807. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11808. ::listen(srv, 1);
  11809. sockaddr_in cli_addr{};
  11810. socklen_t cli_len = sizeof(cli_addr);
  11811. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11812. if (cli != INVALID_SOCKET) {
  11813. char buf[4096];
  11814. ::recv(cli, buf, sizeof(buf), 0);
  11815. auto content_length = std::to_string(DATA_SIZE);
  11816. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11817. "Content-Length: " +
  11818. content_length +
  11819. "\r\n"
  11820. "Connection: close\r\n"
  11821. "\r\n";
  11822. ::send(cli,
  11823. #ifdef _WIN32
  11824. static_cast<const char *>(response_header.c_str()),
  11825. static_cast<int>(response_header.size()),
  11826. #else
  11827. response_header.c_str(), response_header.size(),
  11828. #endif
  11829. 0);
  11830. std::string chunk(64 * 1024, 'A');
  11831. size_t total_sent = 0;
  11832. while (total_sent < DATA_SIZE) {
  11833. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11834. auto sent = ::send(cli,
  11835. #ifdef _WIN32
  11836. static_cast<const char *>(chunk.c_str()),
  11837. static_cast<int>(to_send),
  11838. #else
  11839. chunk.c_str(), to_send,
  11840. #endif
  11841. 0);
  11842. if (sent <= 0) break;
  11843. total_sent += static_cast<size_t>(sent);
  11844. }
  11845. detail::close_socket(cli);
  11846. }
  11847. detail::close_socket(srv);
  11848. });
  11849. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11850. size_t total_received = 0;
  11851. {
  11852. Client cli("127.0.0.1", PORT + 2);
  11853. cli.set_read_timeout(10, 0);
  11854. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11855. auto res =
  11856. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11857. total_received += data_length;
  11858. return true;
  11859. });
  11860. // Should fail because 200MB exceeds the explicit 150MB limit
  11861. EXPECT_FALSE(res);
  11862. }
  11863. server_thread.join();
  11864. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11865. << "Client with content_receiver should respect the explicit "
  11866. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11867. << total_received << " bytes.";
  11868. }
  11869. // Verify that an explicit set_payload_max_length larger than the response
  11870. // allows the content_receiver to read all data successfully.
  11871. TEST(ClientVulnerabilityTest,
  11872. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11873. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11874. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11875. #ifndef _WIN32
  11876. signal(SIGPIPE, SIG_IGN);
  11877. #endif
  11878. auto server_thread = std::thread([] {
  11879. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11880. default_socket_options(srv);
  11881. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11882. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11883. sockaddr_in addr{};
  11884. addr.sin_family = AF_INET;
  11885. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11886. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11887. int opt = 1;
  11888. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11889. #ifdef _WIN32
  11890. reinterpret_cast<const char *>(&opt),
  11891. #else
  11892. &opt,
  11893. #endif
  11894. sizeof(opt));
  11895. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11896. ::listen(srv, 1);
  11897. sockaddr_in cli_addr{};
  11898. socklen_t cli_len = sizeof(cli_addr);
  11899. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11900. if (cli != INVALID_SOCKET) {
  11901. char buf[4096];
  11902. ::recv(cli, buf, sizeof(buf), 0);
  11903. auto content_length = std::to_string(DATA_SIZE);
  11904. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11905. "Content-Length: " +
  11906. content_length +
  11907. "\r\n"
  11908. "Connection: close\r\n"
  11909. "\r\n";
  11910. ::send(cli,
  11911. #ifdef _WIN32
  11912. static_cast<const char *>(response_header.c_str()),
  11913. static_cast<int>(response_header.size()),
  11914. #else
  11915. response_header.c_str(), response_header.size(),
  11916. #endif
  11917. 0);
  11918. std::string chunk(64 * 1024, 'A');
  11919. size_t total_sent = 0;
  11920. while (total_sent < DATA_SIZE) {
  11921. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11922. auto sent = ::send(cli,
  11923. #ifdef _WIN32
  11924. static_cast<const char *>(chunk.c_str()),
  11925. static_cast<int>(to_send),
  11926. #else
  11927. chunk.c_str(), to_send,
  11928. #endif
  11929. 0);
  11930. if (sent <= 0) break;
  11931. total_sent += static_cast<size_t>(sent);
  11932. }
  11933. #ifdef _WIN32
  11934. ::shutdown(cli, SD_SEND);
  11935. #else
  11936. ::shutdown(cli, SHUT_WR);
  11937. #endif
  11938. char drain[1024];
  11939. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11940. detail::close_socket(cli);
  11941. }
  11942. detail::close_socket(srv);
  11943. });
  11944. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11945. size_t total_received = 0;
  11946. {
  11947. Client cli("127.0.0.1", PORT + 2);
  11948. cli.set_read_timeout(10, 0);
  11949. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11950. auto res =
  11951. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11952. total_received += data_length;
  11953. return true;
  11954. });
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. server_thread.join();
  11959. EXPECT_EQ(total_received, DATA_SIZE)
  11960. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11961. << " bytes (larger than " << DATA_SIZE
  11962. << " bytes response), content_receiver should read all data, but only "
  11963. "read "
  11964. << total_received << " bytes.";
  11965. }
  11966. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11967. // Regression test for "zip bomb" attack on the client side: a malicious server
  11968. // sends a small gzip-compressed response that decompresses to a huge payload.
  11969. // The client must enforce payload_max_length on the decompressed size.
  11970. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11971. constexpr size_t DECOMPRESSED_SIZE =
  11972. 10 * 1024 * 1024; // 10MB after decompression
  11973. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11974. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11975. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11976. std::string compressed;
  11977. {
  11978. httplib::detail::gzip_compressor compressor;
  11979. bool ok =
  11980. compressor.compress(uncompressed.data(), uncompressed.size(),
  11981. /*last=*/true, [&](const char *buf, size_t len) {
  11982. compressed.append(buf, len);
  11983. return true;
  11984. });
  11985. ASSERT_TRUE(ok);
  11986. }
  11987. // Sanity: compressed data should be much smaller than the decompressed size
  11988. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11989. #ifndef _WIN32
  11990. signal(SIGPIPE, SIG_IGN);
  11991. #endif
  11992. // Set up the listening socket in the main thread so the server is guaranteed
  11993. // to be ready before the client connects (eliminates race condition).
  11994. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11995. default_socket_options(srv);
  11996. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11997. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11998. sockaddr_in addr{};
  11999. addr.sin_family = AF_INET;
  12000. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12001. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12002. int opt = 1;
  12003. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12004. #ifdef _WIN32
  12005. reinterpret_cast<const char *>(&opt),
  12006. #else
  12007. &opt,
  12008. #endif
  12009. sizeof(opt));
  12010. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12011. ASSERT_EQ(0, ::listen(srv, 1));
  12012. auto server_thread = std::thread([&compressed, srv] {
  12013. sockaddr_in cli_addr{};
  12014. socklen_t cli_len = sizeof(cli_addr);
  12015. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12016. if (cli != INVALID_SOCKET) {
  12017. // Read the full HTTP request (until \r\n\r\n)
  12018. char buf[4096];
  12019. size_t total = 0;
  12020. while (total < sizeof(buf)) {
  12021. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12022. if (n <= 0) break;
  12023. total += static_cast<size_t>(n);
  12024. // Check for end of headers
  12025. if (total >= 4) {
  12026. std::string req(buf, total);
  12027. if (req.find("\r\n\r\n") != std::string::npos) break;
  12028. }
  12029. }
  12030. // Malicious response: gzip-compressed body, no Content-Length
  12031. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12032. "Content-Encoding: gzip\r\n"
  12033. "Connection: close\r\n"
  12034. "\r\n";
  12035. ::send(cli,
  12036. #ifdef _WIN32
  12037. static_cast<const char *>(response_header.c_str()),
  12038. static_cast<int>(response_header.size()),
  12039. #else
  12040. response_header.c_str(), response_header.size(),
  12041. #endif
  12042. 0);
  12043. // Send the compressed payload (small on the wire, huge when decompressed)
  12044. size_t total_sent = 0;
  12045. while (total_sent < compressed.size()) {
  12046. auto to_send = std::min(compressed.size() - total_sent,
  12047. static_cast<size_t>(64 * 1024));
  12048. auto sent =
  12049. ::send(cli,
  12050. #ifdef _WIN32
  12051. static_cast<const char *>(compressed.c_str() + total_sent),
  12052. static_cast<int>(to_send),
  12053. #else
  12054. compressed.c_str() + total_sent, to_send,
  12055. #endif
  12056. 0);
  12057. if (sent <= 0) break;
  12058. total_sent += static_cast<size_t>(sent);
  12059. }
  12060. detail::close_socket(cli);
  12061. }
  12062. });
  12063. auto se = detail::scope_exit([&] {
  12064. detail::close_socket(srv);
  12065. server_thread.join();
  12066. });
  12067. size_t total_decompressed = 0;
  12068. {
  12069. Client cli("127.0.0.1", PORT + 3);
  12070. cli.set_read_timeout(5, 0);
  12071. cli.set_decompress(true);
  12072. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12073. auto stream = cli.open_stream("GET", "/zipbomb");
  12074. ASSERT_TRUE(stream.is_valid());
  12075. char buffer[64 * 1024];
  12076. ssize_t n;
  12077. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12078. total_decompressed += static_cast<size_t>(n);
  12079. }
  12080. }
  12081. // The decompressed size must be capped by payload_max_length. Without
  12082. // protection, the client would decompress the full 10MB from a tiny
  12083. // compressed payload, enabling a zip bomb DoS attack.
  12084. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12085. << "Client decompressed " << total_decompressed
  12086. << " bytes from a gzip response. The decompressed size should be "
  12087. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12088. }
  12089. #endif
  12090. TEST(HostAndPortPropertiesTest, NoSSL) {
  12091. httplib::Client cli("www.google.com", 1234);
  12092. ASSERT_EQ("www.google.com", cli.host());
  12093. ASSERT_EQ(1234, cli.port());
  12094. }
  12095. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12096. httplib::Client cli("www.google.com:1234");
  12097. ASSERT_EQ("www.google.com", cli.host());
  12098. ASSERT_EQ(1234, cli.port());
  12099. }
  12100. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12101. // Port number that overflows int — should not crash, client becomes invalid
  12102. httplib::Client cli("http://www.google.com:99999999999999999999");
  12103. ASSERT_FALSE(cli.is_valid());
  12104. }
  12105. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12106. // Port 99999 exceeds valid range (1-65535) — should not crash
  12107. httplib::Client cli("http://www.google.com:99999");
  12108. ASSERT_FALSE(cli.is_valid());
  12109. }
  12110. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12111. httplib::Client cli("http://www.google.com:80abc");
  12112. ASSERT_FALSE(cli.is_valid());
  12113. }
  12114. #ifdef CPPHTTPLIB_SSL_ENABLED
  12115. TEST(HostAndPortPropertiesTest, SSL) {
  12116. httplib::SSLClient cli("www.google.com");
  12117. ASSERT_EQ("www.google.com", cli.host());
  12118. ASSERT_EQ(443, cli.port());
  12119. }
  12120. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12121. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12122. std::string cert;
  12123. read_file(CA_CERT_FILE, cert);
  12124. httplib::SSLClient httplib_client("www.google.com");
  12125. // Load CA store first time
  12126. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12127. // Load CA store second time (update)
  12128. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12129. // Verify client is still valid and can make connections
  12130. httplib_client.enable_server_certificate_verification(true);
  12131. auto res = httplib_client.Get("/");
  12132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12133. // Google may return 200 or 301 depending on various factors
  12134. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12135. res->status == StatusCode::MovedPermanently_301);
  12136. }
  12137. TEST(SSLClientTest, ServerNameIndication_Online) {
  12138. auto host = "httpbingo.org";
  12139. auto path = std::string{"/get"};
  12140. SSLClient cli(host, 443);
  12141. auto res = cli.Get(path);
  12142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12143. ASSERT_EQ(StatusCode::OK_200, res->status);
  12144. }
  12145. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12146. // Use a site that will cause SSL verification failure due to self-signed cert
  12147. SSLClient cli("self-signed.badssl.com", 443);
  12148. cli.enable_server_certificate_verification(true);
  12149. auto res = cli.Get("/");
  12150. ASSERT_TRUE(!res);
  12151. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12152. // Verify backend error is captured for SSLServerVerification
  12153. // This occurs when certificate verification fails
  12154. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12155. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12156. EXPECT_NE(0UL, res.ssl_backend_error());
  12157. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12158. // For OpenSSL, ssl_error is 0 for verification errors
  12159. EXPECT_EQ(0, res.ssl_error());
  12160. #if !defined(_WIN32) || \
  12161. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12162. // On non-Windows or when Windows Schannel is disabled, the error comes
  12163. // from OpenSSL's verification
  12164. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12165. res.ssl_backend_error());
  12166. #endif
  12167. #endif
  12168. }
  12169. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12170. // Use a site where hostname doesn't match the certificate
  12171. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12172. SSLClient cli("wrong.host.badssl.com", 443);
  12173. cli.enable_server_certificate_verification(true);
  12174. cli.enable_server_hostname_verification(true);
  12175. auto res = cli.Get("/");
  12176. ASSERT_TRUE(!res);
  12177. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12178. // Verify backend error is captured for hostname verification failure
  12179. EXPECT_NE(0UL, res.ssl_backend_error());
  12180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12181. // For OpenSSL, ssl_error is 0 for verification errors
  12182. EXPECT_EQ(0, res.ssl_error());
  12183. #if !defined(_WIN32) || \
  12184. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12185. // On non-Windows or when Windows Schannel is disabled, the error comes
  12186. // from OpenSSL's hostname verification
  12187. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12188. res.ssl_backend_error());
  12189. #endif
  12190. #endif
  12191. }
  12192. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12193. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12194. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12195. SSLClient cli("www.google.com", 443);
  12196. cli.enable_server_certificate_verification(true);
  12197. auto res = cli.Get("/");
  12198. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12199. }
  12200. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12201. SSLClient cli("www.google.com", 443);
  12202. cli.enable_server_certificate_verification(true);
  12203. cli.enable_windows_certificate_verification(false);
  12204. auto res = cli.Get("/");
  12205. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12206. }
  12207. // The server sends an intermediate cross-signed by a root Windows trusts,
  12208. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12209. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12210. SSLClient cli("accounts.spotify.com", 443);
  12211. auto res = cli.Get("/");
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12213. << " ssl_backend_error=" << res.ssl_backend_error();
  12214. }
  12215. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12216. // policy status, which no backend reports for a self-signed certificate.
  12217. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12218. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12219. ASSERT_TRUE(svr.is_valid());
  12220. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12221. auto se = detail::scope_exit([&] {
  12222. svr.stop();
  12223. t.join();
  12224. ASSERT_FALSE(svr.is_running());
  12225. });
  12226. svr.wait_until_ready();
  12227. SSLClient cli("127.0.0.1", PORT);
  12228. cli.set_connection_timeout(30);
  12229. auto res = cli.Get("/");
  12230. ASSERT_FALSE(res);
  12231. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12232. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12233. }
  12234. #endif
  12235. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12236. Client cli("https://google.com");
  12237. auto res = cli.Get("/");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12240. }
  12241. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12242. SSLClient cli("google.com");
  12243. cli.set_ca_cert_path(CA_CERT_FILE);
  12244. auto res = cli.Get("/");
  12245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12246. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12247. }
  12248. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12249. SSLClient cli("google.com");
  12250. cli.enable_server_certificate_verification(true);
  12251. cli.set_ca_cert_path("hello");
  12252. auto res = cli.Get("/");
  12253. ASSERT_TRUE(!res);
  12254. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12255. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12256. // should be set
  12257. EXPECT_EQ(0, res.ssl_error());
  12258. // Verify backend error is captured for SSLLoadingCerts
  12259. // This error occurs when loading CA certificates fails
  12260. EXPECT_NE(0UL, res.ssl_backend_error());
  12261. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12262. // OpenSSL specific error codes:
  12263. // > openssl errstr 0x80000002
  12264. // error:80000002:system library::No such file or directory
  12265. // > openssl errstr 0xA000126
  12266. // error:0A000126:SSL routines::unexpected eof while reading
  12267. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12268. res.ssl_backend_error() == 0xA000126);
  12269. #endif
  12270. }
  12271. TEST(SSLClientTest, ServerCertificateVerification4) {
  12272. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12273. ASSERT_TRUE(svr.is_valid());
  12274. svr.Get("/test", [&](const Request &, Response &res) {
  12275. res.set_content("test", "text/plain");
  12276. svr.stop();
  12277. ASSERT_TRUE(true);
  12278. });
  12279. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12280. auto se = detail::scope_exit([&] {
  12281. t.join();
  12282. ASSERT_FALSE(svr.is_running());
  12283. });
  12284. svr.wait_until_ready();
  12285. SSLClient cli("127.0.0.1", PORT);
  12286. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12287. cli.enable_server_certificate_verification(true);
  12288. cli.set_connection_timeout(30);
  12289. auto res = cli.Get("/test");
  12290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12291. ASSERT_EQ(StatusCode::OK_200, res->status);
  12292. }
  12293. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12294. std::string cert;
  12295. read_file(CA_CERT_FILE, cert);
  12296. SSLClient cli("google.com");
  12297. cli.load_ca_cert_store(cert.data(), cert.size());
  12298. const auto res = cli.Get("/");
  12299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12300. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12301. }
  12302. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12303. // clang-format off
  12304. static constexpr char cert[] =
  12305. "GlobalSign Root CA\n"
  12306. "==================\n"
  12307. "-----BEGIN CERTIFICATE-----\n"
  12308. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12309. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12310. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12311. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12312. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12313. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12314. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12315. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12316. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12317. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12318. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12319. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12320. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12321. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12322. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12323. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12324. "-----END CERTIFICATE-----\n";
  12325. // clang-format on
  12326. SSLClient cli("google.com");
  12327. cli.load_ca_cert_store(cert, sizeof(cert));
  12328. const auto res = cli.Get("/");
  12329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12330. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12331. }
  12332. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12333. SSLClient cli("www.youtube.com");
  12334. cli.set_ca_cert_path(CA_CERT_FILE);
  12335. cli.enable_server_certificate_verification(true);
  12336. cli.set_follow_location(true);
  12337. auto res = cli.Get("/");
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. ASSERT_EQ(StatusCode::OK_200, res->status);
  12340. }
  12341. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12342. SSLClient cli("wWw.YouTube.Com");
  12343. cli.set_ca_cert_path(CA_CERT_FILE);
  12344. cli.enable_server_certificate_verification(true);
  12345. cli.enable_server_hostname_verification(true);
  12346. cli.set_follow_location(true);
  12347. auto res = cli.Get("/");
  12348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12349. ASSERT_EQ(StatusCode::OK_200, res->status);
  12350. }
  12351. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12352. SSLClient cli("gOoGlE.COm");
  12353. cli.enable_server_certificate_verification(true);
  12354. cli.enable_server_hostname_verification(true);
  12355. cli.set_follow_location(true);
  12356. auto res = cli.Get("/");
  12357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12358. ASSERT_EQ(StatusCode::OK_200, res->status);
  12359. }
  12360. TEST(SSLClientTest, Issue2004_Online) {
  12361. Client client("https://google.com");
  12362. client.set_follow_location(true);
  12363. auto res = client.Get("/");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. ASSERT_EQ(StatusCode::OK_200, res->status);
  12366. auto body = res->body;
  12367. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12368. }
  12369. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12370. // Create SSLClient with invalid cert/key to make is_valid() return false
  12371. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12372. "nonexistent_key.pem");
  12373. // is_valid() should be false due to cert loading failure
  12374. ASSERT_FALSE(cli.is_valid());
  12375. auto res = cli.Get("/");
  12376. ASSERT_FALSE(res);
  12377. EXPECT_EQ(Error::SSLConnection, res.error());
  12378. }
  12379. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12380. // Test for Issue #2251: SSL error not properly reported when client cert
  12381. // and key paths are swapped or mismatched
  12382. // This simulates the scenario where user accidentally swaps the cert and key
  12383. // files
  12384. // Using client cert file as private key and vice versa (completely wrong)
  12385. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12386. // Should fail validation due to cert/key mismatch
  12387. ASSERT_FALSE(cli.is_valid());
  12388. // Attempt to make a request should fail with proper error
  12389. auto res = cli.Get("/");
  12390. ASSERT_FALSE(res);
  12391. EXPECT_EQ(Error::SSLConnection, res.error());
  12392. // SSL error should be recorded in the Result object (this is the key fix for
  12393. // Issue #2251)
  12394. auto backend_error = res.ssl_backend_error();
  12395. EXPECT_NE(0u, backend_error);
  12396. }
  12397. // Tests cert/key mismatch detection at the TLS context level
  12398. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12399. // Test that using mismatched cert/key causes connection failure.
  12400. // We verify this at the SSLClient level rather than through internal
  12401. // TLS API functions.
  12402. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12403. cli.enable_server_certificate_verification(false);
  12404. cli.set_connection_timeout(2);
  12405. // The mismatch should cause a connection or handshake error
  12406. auto res = cli.Get("/test");
  12407. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12408. // Either way, the request should fail
  12409. EXPECT_FALSE(res);
  12410. }
  12411. #endif
  12412. #if 0
  12413. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12414. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12415. ASSERT_TRUE(cli != nullptr);
  12416. cli->set_address_family(AF_INET6);
  12417. cli->set_interface("en0");
  12418. auto res = cli->Get("/get");
  12419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12420. ASSERT_EQ(StatusCode::OK_200, res->status);
  12421. }
  12422. #endif
  12423. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12424. #ifdef CPPHTTPLIB_SSL_ENABLED
  12425. void ClientCertPresent(
  12426. const std::string &client_cert_file,
  12427. const std::string &client_private_key_file,
  12428. const std::string &client_encrypted_private_key_pass = std::string()) {
  12429. using namespace httplib::tls;
  12430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12431. CLIENT_CA_CERT_DIR);
  12432. ASSERT_TRUE(svr.is_valid());
  12433. svr.Get("/test", [&](const Request &req, Response &res) {
  12434. res.set_content("test", "text/plain");
  12435. auto cert = req.peer_cert();
  12436. ASSERT_TRUE(static_cast<bool>(cert));
  12437. std::string common_name = cert.subject_cn();
  12438. EXPECT_EQ("Common Name", common_name);
  12439. });
  12440. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12441. auto se = detail::scope_exit([&] {
  12442. svr.stop();
  12443. t.join();
  12444. ASSERT_FALSE(svr.is_running());
  12445. });
  12446. svr.wait_until_ready();
  12447. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12448. client_encrypted_private_key_pass);
  12449. cli.enable_server_certificate_verification(false);
  12450. cli.set_connection_timeout(30);
  12451. auto res = cli.Get("/test");
  12452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12453. ASSERT_EQ(StatusCode::OK_200, res->status);
  12454. }
  12455. TEST(SSLClientServerTest, ClientCertPresent) {
  12456. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12457. }
  12458. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12459. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12460. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12461. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12462. }
  12463. // PEM memory-based constructor tests (works with all TLS backends)
  12464. void PemMemoryClientCertPresent(
  12465. const std::string &client_cert_file,
  12466. const std::string &client_private_key_file,
  12467. const std::string &client_encrypted_private_key_pass = std::string()) {
  12468. // Read PEM files into memory
  12469. std::string server_cert_pem, server_key_pem;
  12470. std::string client_ca_pem;
  12471. std::string client_cert_pem, client_key_pem;
  12472. read_file(SERVER_CERT_FILE, server_cert_pem);
  12473. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12474. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12475. read_file(client_cert_file, client_cert_pem);
  12476. read_file(client_private_key_file, client_key_pem);
  12477. // Create server with PEM memory
  12478. SSLServer::PemMemory server_pem = {
  12479. server_cert_pem.c_str(),
  12480. server_cert_pem.size(),
  12481. server_key_pem.c_str(),
  12482. server_key_pem.size(),
  12483. client_ca_pem.c_str(),
  12484. client_ca_pem.size(),
  12485. nullptr // no password for server key
  12486. };
  12487. SSLServer svr(server_pem);
  12488. ASSERT_TRUE(svr.is_valid());
  12489. svr.Get("/test", [&](const Request &, Response &res) {
  12490. res.set_content("test", "text/plain");
  12491. });
  12492. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12493. auto se = detail::scope_exit([&] {
  12494. svr.stop();
  12495. t.join();
  12496. ASSERT_FALSE(svr.is_running());
  12497. });
  12498. svr.wait_until_ready();
  12499. // Create client with PEM memory
  12500. const char *password = client_encrypted_private_key_pass.empty()
  12501. ? nullptr
  12502. : client_encrypted_private_key_pass.c_str();
  12503. SSLClient::PemMemory client_pem = {
  12504. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12505. client_key_pem.size(), password};
  12506. SSLClient cli(HOST, PORT, client_pem);
  12507. cli.enable_server_certificate_verification(false);
  12508. cli.set_connection_timeout(30);
  12509. auto res = cli.Get("/test");
  12510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12511. ASSERT_EQ(StatusCode::OK_200, res->status);
  12512. }
  12513. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12514. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12515. }
  12516. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12517. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12518. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12519. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12520. }
  12521. TEST(SSLClientServerTest, ClientCertMissing) {
  12522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12523. CLIENT_CA_CERT_DIR);
  12524. ASSERT_TRUE(svr.is_valid());
  12525. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12527. auto se = detail::scope_exit([&] {
  12528. svr.stop();
  12529. t.join();
  12530. ASSERT_FALSE(svr.is_running());
  12531. });
  12532. svr.wait_until_ready();
  12533. SSLClient cli(HOST, PORT);
  12534. cli.set_connection_timeout(30);
  12535. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12536. // the chain check on Windows, so the result does not depend on the order.
  12537. cli.enable_server_hostname_verification(false);
  12538. auto res = cli.Get("/test");
  12539. ASSERT_TRUE(!res);
  12540. // When client cert is missing and server requires it, connection fails
  12541. // Error type depends on backend implementation
  12542. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12543. res.error() == Error::SSLConnection);
  12544. // Verify backend error is captured
  12545. // Note: This test may have different error codes depending on the exact
  12546. // verification failure
  12547. EXPECT_NE(0UL, res.ssl_backend_error());
  12548. }
  12549. TEST(SSLClientServerTest, TrustDirOptional) {
  12550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12551. ASSERT_TRUE(svr.is_valid());
  12552. svr.Get("/test", [&](const Request &, Response &res) {
  12553. res.set_content("test", "text/plain");
  12554. });
  12555. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12556. auto se = detail::scope_exit([&] {
  12557. svr.stop();
  12558. t.join();
  12559. ASSERT_FALSE(svr.is_running());
  12560. });
  12561. svr.wait_until_ready();
  12562. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12563. cli.enable_server_certificate_verification(false);
  12564. cli.set_connection_timeout(30);
  12565. auto res = cli.Get("/test");
  12566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12567. ASSERT_EQ(StatusCode::OK_200, res->status);
  12568. }
  12569. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12570. class NoListenSSLServer : public SSLServer {
  12571. public:
  12572. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12573. const char *client_ca_cert_file_path,
  12574. const char *client_ca_cert_dir_path = nullptr)
  12575. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12576. client_ca_cert_dir_path),
  12577. stop_(false) {}
  12578. std::atomic_bool stop_;
  12579. private:
  12580. bool process_and_close_socket(socket_t /*sock*/) override {
  12581. // Don't create SSL context
  12582. while (!stop_.load()) {
  12583. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12584. }
  12585. return true;
  12586. }
  12587. };
  12588. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12589. CLIENT_CA_CERT_FILE);
  12590. ASSERT_TRUE(svr.is_valid());
  12591. svr.Get("/test", [&](const Request &, Response &res) {
  12592. res.set_content("test", "text/plain");
  12593. });
  12594. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12595. auto se = detail::scope_exit([&] {
  12596. svr.stop_ = true;
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12603. cli.enable_server_certificate_verification(false);
  12604. cli.set_connection_timeout(1);
  12605. auto res = cli.Get("/test");
  12606. ASSERT_TRUE(!res);
  12607. EXPECT_EQ(Error::SSLConnection, res.error());
  12608. // Timeout results in WantRead error code (maps to backend-specific value)
  12609. EXPECT_NE(0, res.ssl_error());
  12610. }
  12611. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12612. // Test SSLServer with client certificate verification using the standard
  12613. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12615. CLIENT_CA_CERT_DIR);
  12616. ASSERT_TRUE(svr.is_valid());
  12617. svr.Get("/test", [&](const Request &req, Response &res) {
  12618. res.set_content("test", "text/plain");
  12619. auto cert = req.peer_cert();
  12620. ASSERT_TRUE(static_cast<bool>(cert));
  12621. auto common_name = cert.subject_cn();
  12622. EXPECT_EQ("Common Name", common_name);
  12623. });
  12624. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12625. auto se = detail::scope_exit([&] {
  12626. svr.stop();
  12627. t.join();
  12628. ASSERT_FALSE(svr.is_running());
  12629. });
  12630. svr.wait_until_ready();
  12631. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12632. cli.enable_server_certificate_verification(false);
  12633. cli.set_connection_timeout(30);
  12634. auto res = cli.Get("/test");
  12635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12636. ASSERT_EQ(StatusCode::OK_200, res->status);
  12637. }
  12638. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12639. // Verifies that wildcard matching and exact matching work consistently
  12640. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12641. using namespace httplib::tls;
  12642. // We need a running server to test against
  12643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12644. ASSERT_TRUE(svr.is_valid());
  12645. svr.Get("/test", [](const Request &, Response &res) {
  12646. res.set_content("ok", "text/plain");
  12647. });
  12648. thread t([&]() { svr.listen(HOST, PORT); });
  12649. auto se = detail::scope_exit([&] {
  12650. svr.stop();
  12651. t.join();
  12652. });
  12653. svr.wait_until_ready();
  12654. bool verify_callback_called = false;
  12655. bool verify_result_wrong = false;
  12656. SSLClient cli(HOST, PORT);
  12657. cli.enable_server_certificate_verification(true);
  12658. cli.set_ca_cert_path(CA_CERT_FILE);
  12659. cli.set_connection_timeout(5);
  12660. // Note: Test certificate has CN="Common Name", not "localhost"
  12661. bool verify_result_cn = false;
  12662. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12663. verify_callback_called = true;
  12664. if (!ctx.cert) return false;
  12665. // Test 1: "Common Name" should match (our test server cert CN)
  12666. verify_result_cn = ctx.check_hostname("Common Name");
  12667. // Test 2: wrong hostname should not match
  12668. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12669. return true; // Accept for the purpose of this test
  12670. });
  12671. auto res = cli.Get("/test");
  12672. // The request may succeed or fail depending on cert configuration
  12673. // but the callback should have been called
  12674. ASSERT_TRUE(verify_callback_called)
  12675. << "Verify callback should have been called";
  12676. // CN="Common Name" should match our test certificate
  12677. //
  12678. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12679. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12680. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12681. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12682. // <openssl/base.h>, which is included transitively when
  12683. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12684. #if defined(OPENSSL_IS_BORINGSSL)
  12685. EXPECT_FALSE(verify_result_cn)
  12686. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12687. #else
  12688. EXPECT_TRUE(verify_result_cn)
  12689. << "verify_hostname should match 'Common Name' (certificate CN)";
  12690. #endif
  12691. // Wrong hostname should not match
  12692. EXPECT_FALSE(verify_result_wrong)
  12693. << "verify_hostname should not match 'wronghost.example.com'";
  12694. }
  12695. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12696. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12697. // X509_check_ip behavior and must hold for every backend.
  12698. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12699. using namespace httplib::tls;
  12700. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12701. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12702. ASSERT_TRUE(svr.is_valid());
  12703. svr.Get("/test", [](const Request &, Response &res) {
  12704. res.set_content("ok", "text/plain");
  12705. });
  12706. thread t([&]() { svr.listen(HOST, PORT); });
  12707. auto se = detail::scope_exit([&] {
  12708. svr.stop();
  12709. t.join();
  12710. });
  12711. svr.wait_until_ready();
  12712. bool verify_callback_called = false;
  12713. bool ip_matched_via_cn = true;
  12714. SSLClient cli(HOST, PORT);
  12715. cli.enable_server_certificate_verification(true);
  12716. cli.set_ca_cert_path(CA_CERT_FILE);
  12717. cli.set_connection_timeout(5);
  12718. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12719. verify_callback_called = true;
  12720. if (!ctx.cert) return false;
  12721. // The IP appears only in the CN, so it must NOT be accepted.
  12722. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12723. return true; // Accept for the purpose of this test
  12724. });
  12725. cli.Get("/test");
  12726. ASSERT_TRUE(verify_callback_called)
  12727. << "Verify callback should have been called";
  12728. EXPECT_FALSE(ip_matched_via_cn)
  12729. << "An IP host must not be authenticated via the certificate CN";
  12730. }
  12731. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12732. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12733. using namespace httplib::tls;
  12734. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12735. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.Get("/test", [](const Request &, Response &res) {
  12738. res.set_content("ok", "text/plain");
  12739. });
  12740. thread t([&]() { svr.listen(HOST, PORT); });
  12741. auto se = detail::scope_exit([&] {
  12742. svr.stop();
  12743. t.join();
  12744. });
  12745. svr.wait_until_ready();
  12746. bool verify_callback_called = false;
  12747. bool san_matched = false;
  12748. bool wrong_ipv6_matched = true;
  12749. bool cn_ipv6_matched = true;
  12750. SSLClient cli(HOST, PORT);
  12751. cli.enable_server_certificate_verification(true);
  12752. cli.set_ca_cert_path(CA_CERT_FILE);
  12753. cli.set_connection_timeout(5);
  12754. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12755. verify_callback_called = true;
  12756. if (!ctx.cert) return false;
  12757. // Matches the IPv6 iPAddress SAN.
  12758. san_matched = ctx.check_hostname("2001:db8::1");
  12759. // A different IPv6 address must not match.
  12760. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12761. // "::1" lives only in the CN, so it must not be accepted.
  12762. cn_ipv6_matched = ctx.check_hostname("::1");
  12763. return true; // Accept for the purpose of this test
  12764. });
  12765. cli.Get("/test");
  12766. ASSERT_TRUE(verify_callback_called)
  12767. << "Verify callback should have been called";
  12768. EXPECT_TRUE(san_matched)
  12769. << "verify_hostname should match an IPv6 iPAddress SAN";
  12770. EXPECT_FALSE(wrong_ipv6_matched)
  12771. << "verify_hostname should not match a non-matching IPv6 address";
  12772. EXPECT_FALSE(cn_ipv6_matched)
  12773. << "An IPv6 host must not be authenticated via the certificate CN";
  12774. }
  12775. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12776. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12777. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12778. using namespace httplib::tls;
  12779. // SANs: DNS:a.zz, IP:42.46.122.122
  12780. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12781. ASSERT_TRUE(svr.is_valid());
  12782. svr.Get("/test", [](const Request &, Response &res) {
  12783. res.set_content("ok", "text/plain");
  12784. });
  12785. auto port = svr.bind_to_any_port(HOST);
  12786. thread t([&]() { svr.listen_after_bind(); });
  12787. auto se = detail::scope_exit([&] {
  12788. svr.stop();
  12789. t.join();
  12790. });
  12791. svr.wait_until_ready();
  12792. bool verify_callback_called = false;
  12793. bool dns_san_matched = false;
  12794. bool ip_san_matched = false;
  12795. bool ip_matched_via_dns_san = true;
  12796. bool dns_matched_via_ip_san = true;
  12797. SSLClient cli(HOST, port);
  12798. cli.enable_server_certificate_verification(true);
  12799. cli.set_ca_cert_path(CA_CERT_FILE);
  12800. cli.set_connection_timeout(5);
  12801. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12802. verify_callback_called = true;
  12803. if (!ctx.cert) return false;
  12804. dns_san_matched = ctx.check_hostname("a.zz");
  12805. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12806. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12807. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12808. return true; // Accept for the purpose of this test
  12809. });
  12810. cli.Get("/test");
  12811. ASSERT_TRUE(verify_callback_called)
  12812. << "Verify callback should have been called";
  12813. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12814. EXPECT_TRUE(ip_san_matched)
  12815. << "verify_hostname should match an iPAddress SAN";
  12816. EXPECT_FALSE(ip_matched_via_dns_san)
  12817. << "An IP host must not be authenticated via a dNSName SAN";
  12818. EXPECT_FALSE(dns_matched_via_ip_san)
  12819. << "A DNS host must not be authenticated via an iPAddress SAN";
  12820. }
  12821. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12822. // "www.*.example.test" names one host and not every host under example.test.
  12823. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12824. using namespace httplib::tls;
  12825. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12826. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12827. ASSERT_TRUE(svr.is_valid());
  12828. svr.Get("/test", [](const Request &, Response &res) {
  12829. res.set_content("ok", "text/plain");
  12830. });
  12831. auto port = svr.bind_to_any_port(HOST);
  12832. thread t([&]() { svr.listen_after_bind(); });
  12833. auto se = detail::scope_exit([&] {
  12834. svr.stop();
  12835. t.join();
  12836. });
  12837. svr.wait_until_ready();
  12838. bool verify_callback_called = false;
  12839. bool leftmost_wildcard_matched = false;
  12840. bool wildcard_spanned_labels = true;
  12841. bool inner_wildcard_matched = true;
  12842. SSLClient cli(HOST, port);
  12843. cli.enable_server_certificate_verification(true);
  12844. cli.set_ca_cert_path(CA_CERT_FILE);
  12845. cli.set_connection_timeout(5);
  12846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12847. verify_callback_called = true;
  12848. if (!ctx.cert) return false;
  12849. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12850. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12851. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12852. return true; // Accept for the purpose of this test
  12853. });
  12854. cli.Get("/test");
  12855. ASSERT_TRUE(verify_callback_called)
  12856. << "Verify callback should have been called";
  12857. EXPECT_TRUE(leftmost_wildcard_matched)
  12858. << "A leftmost wildcard should match a single label";
  12859. EXPECT_FALSE(wildcard_spanned_labels)
  12860. << "A wildcard label must not match more than one label";
  12861. EXPECT_FALSE(inner_wildcard_matched)
  12862. << "A wildcard outside the leftmost label must not be honoured";
  12863. }
  12864. // sans() must report each SAN entry under its own type.
  12865. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12866. using namespace httplib::tls;
  12867. // SANs: DNS:a.zz, IP:42.46.122.122
  12868. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12869. ASSERT_TRUE(svr.is_valid());
  12870. svr.Get("/test", [](const Request &, Response &res) {
  12871. res.set_content("ok", "text/plain");
  12872. });
  12873. auto port = svr.bind_to_any_port(HOST);
  12874. thread t([&]() { svr.listen_after_bind(); });
  12875. auto se = detail::scope_exit([&] {
  12876. svr.stop();
  12877. t.join();
  12878. });
  12879. svr.wait_until_ready();
  12880. bool verify_callback_called = false;
  12881. std::vector<SanEntry> sans;
  12882. SSLClient cli(HOST, port);
  12883. cli.enable_server_certificate_verification(true);
  12884. cli.set_ca_cert_path(CA_CERT_FILE);
  12885. cli.set_connection_timeout(5);
  12886. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12887. verify_callback_called = true;
  12888. if (!ctx.cert) return false;
  12889. sans = ctx.sans();
  12890. return true; // Accept for the purpose of this test
  12891. });
  12892. cli.Get("/test");
  12893. ASSERT_TRUE(verify_callback_called)
  12894. << "Verify callback should have been called";
  12895. auto has_san = [&](SanType type, const std::string &value) {
  12896. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12897. return san.type == type && san.value == value;
  12898. });
  12899. };
  12900. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12901. << "sans() should report the dNSName SAN";
  12902. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12903. << "sans() should report the iPAddress SAN";
  12904. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12905. << "sans() must not report the dNSName SAN as an address";
  12906. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12907. << "sans() must not report the iPAddress SAN as a DNS name";
  12908. }
  12909. #endif
  12910. // mbedTLS-specific callback constructor test
  12911. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12912. #ifdef CPPHTTPLIB_SSL_ENABLED
  12913. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12915. ASSERT_TRUE(svr.is_valid());
  12916. // Set up a handler to verify client certificate is present
  12917. bool client_cert_verified = false;
  12918. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12919. // Verify that client certificate was provided
  12920. client_cert_verified = true;
  12921. res.set_content("success", "text/plain");
  12922. });
  12923. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12924. auto se = detail::scope_exit([&] {
  12925. svr.stop();
  12926. t.join();
  12927. ASSERT_FALSE(svr.is_running());
  12928. });
  12929. svr.wait_until_ready();
  12930. // Client with certificate
  12931. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12932. cli.enable_server_certificate_verification(false);
  12933. cli.set_connection_timeout(30);
  12934. auto res = cli.Get("/test");
  12935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12936. ASSERT_EQ(StatusCode::OK_200, res->status);
  12937. ASSERT_TRUE(client_cert_verified);
  12938. EXPECT_EQ("success", res->body);
  12939. }
  12940. #endif
  12941. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12942. // backends
  12943. #ifdef CPPHTTPLIB_SSL_ENABLED
  12944. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12945. using namespace httplib::tls;
  12946. // Test that when client CA cert file is provided,
  12947. // the server properly requests and validates client certificates
  12948. // Create a server with client authentication
  12949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12950. ASSERT_TRUE(svr.is_valid());
  12951. bool handler_called = false;
  12952. svr.Get("/test", [&](const Request &req, Response &res) {
  12953. handler_called = true;
  12954. // Verify that a client certificate was provided
  12955. auto cert = req.peer_cert();
  12956. ASSERT_TRUE(static_cast<bool>(cert));
  12957. // Get the issuer name
  12958. std::string issuer_str = cert.issuer_name();
  12959. ASSERT_FALSE(issuer_str.empty());
  12960. // The client certificate should be issued by our test CA
  12961. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12962. res.set_content("authenticated", "text/plain");
  12963. });
  12964. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12965. auto se = detail::scope_exit([&] {
  12966. svr.stop();
  12967. t.join();
  12968. ASSERT_FALSE(svr.is_running());
  12969. });
  12970. svr.wait_until_ready();
  12971. // Connect with a client certificate issued by the CA
  12972. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12973. cli.enable_server_certificate_verification(false);
  12974. cli.set_connection_timeout(30);
  12975. auto res = cli.Get("/test");
  12976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12977. ASSERT_EQ(StatusCode::OK_200, res->status);
  12978. ASSERT_TRUE(handler_called);
  12979. EXPECT_EQ("authenticated", res->body);
  12980. }
  12981. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12982. using namespace httplib::tls;
  12983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12984. ASSERT_TRUE(svr.is_valid());
  12985. svr.Get("/test", [](const Request &, Response &res) {
  12986. res.set_content("ok", "text/plain");
  12987. });
  12988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12989. auto se = detail::scope_exit([&] {
  12990. svr.stop();
  12991. t.join();
  12992. });
  12993. svr.wait_until_ready();
  12994. SSLClient cli(HOST, PORT);
  12995. cli.enable_server_certificate_verification(false);
  12996. cli.set_connection_timeout(30);
  12997. bool cert_checked = false;
  12998. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12999. if (ctx.cert) {
  13000. auto sans = ctx.sans();
  13001. // Test certificate may or may not have SANs - just verify the API
  13002. // works If SANs exist, verify the types are valid
  13003. for (const auto &san : sans) {
  13004. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13005. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13006. san.type == SanType::OTHER);
  13007. EXPECT_FALSE(san.value.empty());
  13008. }
  13009. cert_checked = true;
  13010. }
  13011. return true;
  13012. });
  13013. auto res = cli.Get("/test");
  13014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13015. EXPECT_TRUE(cert_checked);
  13016. }
  13017. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13018. using namespace httplib::tls;
  13019. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13020. ASSERT_TRUE(svr.is_valid());
  13021. svr.Get("/test", [](const Request &, Response &res) {
  13022. res.set_content("ok", "text/plain");
  13023. });
  13024. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13025. auto se = detail::scope_exit([&] {
  13026. svr.stop();
  13027. t.join();
  13028. });
  13029. svr.wait_until_ready();
  13030. SSLClient cli(HOST, PORT);
  13031. cli.enable_server_certificate_verification(false);
  13032. cli.set_connection_timeout(30);
  13033. bool validity_checked = false;
  13034. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13035. if (ctx.cert) {
  13036. time_t not_before = 0, not_after = 0;
  13037. bool result = ctx.validity(not_before, not_after);
  13038. EXPECT_TRUE(result);
  13039. // Verify that not_before < now < not_after for a valid cert
  13040. time_t now = time(nullptr);
  13041. EXPECT_LT(not_before, now);
  13042. EXPECT_GT(not_after, now);
  13043. validity_checked = true;
  13044. }
  13045. return true;
  13046. });
  13047. auto res = cli.Get("/test");
  13048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13049. EXPECT_TRUE(validity_checked);
  13050. }
  13051. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13052. using namespace httplib::tls;
  13053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13054. ASSERT_TRUE(svr.is_valid());
  13055. svr.Get("/test", [](const Request &, Response &res) {
  13056. res.set_content("ok", "text/plain");
  13057. });
  13058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13059. auto se = detail::scope_exit([&] {
  13060. svr.stop();
  13061. t.join();
  13062. });
  13063. svr.wait_until_ready();
  13064. SSLClient cli(HOST, PORT);
  13065. cli.enable_server_certificate_verification(false);
  13066. cli.set_connection_timeout(30);
  13067. bool serial_checked = false;
  13068. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13069. if (ctx.cert) {
  13070. std::string serial = ctx.serial();
  13071. EXPECT_FALSE(serial.empty());
  13072. // Serial should be a hex string
  13073. for (char c : serial) {
  13074. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13075. (c >= 'a' && c <= 'f'));
  13076. }
  13077. serial_checked = true;
  13078. }
  13079. return true;
  13080. });
  13081. auto res = cli.Get("/test");
  13082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13083. EXPECT_TRUE(serial_checked);
  13084. }
  13085. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13086. // Test 1: Valid CA file - no error should be recorded
  13087. {
  13088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13089. CLIENT_CA_CERT_FILE);
  13090. ASSERT_TRUE(svr.is_valid());
  13091. // With valid setup, last_ssl_error should be 0
  13092. EXPECT_EQ(0, svr.ssl_last_error());
  13093. }
  13094. // Test 2: Invalid CA file content
  13095. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13096. {
  13097. // Create a temporary file with completely invalid content
  13098. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13099. {
  13100. std::ofstream ofs(temp_invalid_ca);
  13101. ofs << "This is not a certificate file at all\n";
  13102. ofs << "Just plain text content\n";
  13103. }
  13104. // Create server with invalid CA file
  13105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13106. // Clean up temporary file
  13107. std::remove(temp_invalid_ca);
  13108. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13109. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13110. // Note: SSL_CTX_load_verify_locations typically fails first,
  13111. // but our error handling code path is still exercised
  13112. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13113. }
  13114. }
  13115. TEST(VerifyCallbackTest, VerifyContextFields) {
  13116. using namespace httplib::tls;
  13117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13118. ASSERT_TRUE(svr.is_valid());
  13119. svr.Get("/test", [](const Request &, Response &res) {
  13120. res.set_content("ok", "text/plain");
  13121. });
  13122. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13123. auto se = detail::scope_exit([&] {
  13124. svr.stop();
  13125. t.join();
  13126. });
  13127. svr.wait_until_ready();
  13128. SSLClient cli(HOST, PORT);
  13129. cli.enable_server_certificate_verification(false);
  13130. cli.set_connection_timeout(30);
  13131. int callback_count = 0;
  13132. bool saw_leaf_cert = false;
  13133. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13134. if (ctx.cert) {
  13135. callback_count++;
  13136. // We should see at least one certificate (the leaf)
  13137. std::string cn = ctx.subject_cn();
  13138. if (!cn.empty()) { saw_leaf_cert = true; }
  13139. // Verify context fields are populated
  13140. EXPECT_NE(ctx.session, nullptr);
  13141. EXPECT_GE(ctx.depth, 0);
  13142. }
  13143. return true;
  13144. });
  13145. auto res = cli.Get("/test");
  13146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13147. EXPECT_GT(callback_count, 0);
  13148. EXPECT_TRUE(saw_leaf_cert);
  13149. }
  13150. // A verifier belongs to the client that set it, not to the thread that set it.
  13151. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13152. using namespace httplib::tls;
  13153. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13154. ASSERT_TRUE(svr.is_valid());
  13155. svr.Get("/test", [](const Request &, Response &res) {
  13156. res.set_content("ok", "text/plain");
  13157. });
  13158. auto port = svr.bind_to_any_port(HOST);
  13159. thread t([&]() { svr.listen_after_bind(); });
  13160. auto se = detail::scope_exit([&] {
  13161. svr.stop();
  13162. t.join();
  13163. });
  13164. svr.wait_until_ready();
  13165. auto rejecting_calls = 0;
  13166. SSLClient rejecting(HOST, port);
  13167. rejecting.enable_server_certificate_verification(false);
  13168. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13169. rejecting_calls++;
  13170. return false;
  13171. });
  13172. auto accepting_calls = 0;
  13173. SSLClient accepting(HOST, port);
  13174. accepting.enable_server_certificate_verification(false);
  13175. // Set on another thread than the requests below.
  13176. thread([&]() {
  13177. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13178. accepting_calls++;
  13179. return true;
  13180. });
  13181. }).join();
  13182. // Requested on another thread than the verifier was set on.
  13183. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13184. EXPECT_GT(rejecting_calls, 0);
  13185. auto res = accepting.Get("/test");
  13186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13187. EXPECT_GT(accepting_calls, 0);
  13188. }
  13189. // VerifyContext::session is the same handle the other tls:: functions take.
  13190. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13191. using namespace httplib::tls;
  13192. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13193. ASSERT_TRUE(svr.is_valid());
  13194. svr.Get("/test", [](const Request &, Response &res) {
  13195. res.set_content("ok", "text/plain");
  13196. });
  13197. auto port = svr.bind_to_any_port(HOST);
  13198. thread t([&]() { svr.listen_after_bind(); });
  13199. auto se = detail::scope_exit([&] {
  13200. svr.stop();
  13201. t.join();
  13202. });
  13203. svr.wait_until_ready();
  13204. SSLClient cli(HOST, port);
  13205. cli.enable_server_certificate_verification(false);
  13206. session_t verifier_session = nullptr;
  13207. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13208. verifier_session = ctx.session;
  13209. return true;
  13210. });
  13211. session_t session_verifier_session = nullptr;
  13212. cli.set_session_verifier([&](session_t session) {
  13213. session_verifier_session = session;
  13214. return SSLVerifierResponse::NoDecisionMade;
  13215. });
  13216. auto res = cli.Get("/test");
  13217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13218. EXPECT_NE(nullptr, verifier_session);
  13219. EXPECT_EQ(session_verifier_session, verifier_session);
  13220. }
  13221. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13222. using httplib::tls::TlsError;
  13223. // Test that verify_error_to_string returns empty for success
  13224. std::string success_str = TlsError::verify_error_to_string(0);
  13225. EXPECT_TRUE(success_str.empty());
  13226. // Test that verify_error_to_string returns non-empty for error codes
  13227. // Using a common error code (certificate expired)
  13228. std::string error_str =
  13229. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13230. EXPECT_FALSE(error_str.empty());
  13231. }
  13232. TEST(SessionVerifierTest, CertificateAccepted) {
  13233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13234. ASSERT_TRUE(svr.is_valid());
  13235. svr.Get("/test", [](const Request &, Response &res) {
  13236. res.set_content("ok", "text/plain");
  13237. });
  13238. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13239. auto se = detail::scope_exit([&] {
  13240. svr.stop();
  13241. t.join();
  13242. });
  13243. svr.wait_until_ready();
  13244. SSLClient cli(HOST, PORT);
  13245. cli.enable_server_certificate_verification(false);
  13246. cli.set_connection_timeout(30);
  13247. bool callback_called = false;
  13248. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13249. EXPECT_NE(session, nullptr);
  13250. callback_called = true;
  13251. return SSLVerifierResponse::CertificateAccepted;
  13252. });
  13253. auto res = cli.Get("/test");
  13254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13255. EXPECT_EQ(200, res->status);
  13256. EXPECT_TRUE(callback_called);
  13257. }
  13258. TEST(SessionVerifierTest, CertificateRejected) {
  13259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13260. ASSERT_TRUE(svr.is_valid());
  13261. svr.Get("/test", [](const Request &, Response &res) {
  13262. res.set_content("ok", "text/plain");
  13263. });
  13264. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13265. auto se = detail::scope_exit([&] {
  13266. svr.stop();
  13267. t.join();
  13268. });
  13269. svr.wait_until_ready();
  13270. SSLClient cli(HOST, PORT);
  13271. cli.enable_server_certificate_verification(false);
  13272. cli.set_connection_timeout(30);
  13273. bool callback_called = false;
  13274. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13275. EXPECT_NE(session, nullptr);
  13276. callback_called = true;
  13277. return SSLVerifierResponse::CertificateRejected;
  13278. });
  13279. auto res = cli.Get("/test");
  13280. EXPECT_FALSE(res);
  13281. EXPECT_TRUE(callback_called);
  13282. }
  13283. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13284. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13285. ASSERT_TRUE(svr.is_valid());
  13286. svr.Get("/test", [](const Request &, Response &res) {
  13287. res.set_content("ok", "text/plain");
  13288. });
  13289. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13290. auto se = detail::scope_exit([&] {
  13291. svr.stop();
  13292. t.join();
  13293. });
  13294. svr.wait_until_ready();
  13295. // NoDecisionMade with verification disabled should succeed (no default check)
  13296. SSLClient cli(HOST, PORT);
  13297. cli.enable_server_certificate_verification(false);
  13298. cli.set_connection_timeout(30);
  13299. bool callback_called = false;
  13300. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13301. EXPECT_NE(session, nullptr);
  13302. callback_called = true;
  13303. return SSLVerifierResponse::NoDecisionMade;
  13304. });
  13305. auto res = cli.Get("/test");
  13306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13307. EXPECT_EQ(200, res->status);
  13308. EXPECT_TRUE(callback_called);
  13309. }
  13310. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13311. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13312. ASSERT_TRUE(svr.is_valid());
  13313. svr.Get("/test", [](const Request &, Response &res) {
  13314. res.set_content("ok", "text/plain");
  13315. });
  13316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13317. auto se = detail::scope_exit([&] {
  13318. svr.stop();
  13319. t.join();
  13320. });
  13321. svr.wait_until_ready();
  13322. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13323. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13324. // so we only check that the request fails, not whether the callback was
  13325. // called.
  13326. SSLClient cli(HOST, PORT);
  13327. cli.enable_server_certificate_verification(true);
  13328. cli.set_connection_timeout(30);
  13329. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13330. EXPECT_NE(session, nullptr);
  13331. return SSLVerifierResponse::NoDecisionMade;
  13332. });
  13333. auto res = cli.Get("/test");
  13334. EXPECT_FALSE(res);
  13335. }
  13336. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13337. // Test SSL server using PemMemory constructor with client CA certificates
  13338. // Read PEM files
  13339. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13340. read_file(SERVER_CERT_FILE, server_cert_pem);
  13341. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13342. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13343. // Create SSLServer with PemMemory constructor including client CA
  13344. SSLServer::PemMemory server_pem = {
  13345. server_cert_pem.c_str(),
  13346. server_cert_pem.size(),
  13347. server_key_pem.c_str(),
  13348. server_key_pem.size(),
  13349. client_ca_pem.c_str(),
  13350. client_ca_pem.size(),
  13351. nullptr // no password for server key
  13352. };
  13353. SSLServer svr(server_pem);
  13354. ASSERT_TRUE(svr.is_valid());
  13355. // No SSL error should be recorded for valid setup
  13356. EXPECT_EQ(0, svr.ssl_last_error());
  13357. // Set up server endpoints
  13358. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13359. res.set_content("ok", "text/plain");
  13360. });
  13361. // Start server in a thread
  13362. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13363. svr.wait_until_ready();
  13364. // Connect with client certificate (using constructor with paths)
  13365. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13366. cli.enable_server_certificate_verification(false);
  13367. auto res = cli.Get("/test-pem-ca");
  13368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13369. EXPECT_EQ(200, res->status);
  13370. EXPECT_EQ("ok", res->body);
  13371. svr.stop();
  13372. server_thread.join();
  13373. }
  13374. #endif
  13375. #ifdef _WIN32
  13376. TEST(CleanupTest, WSACleanup) {
  13377. int ret = WSACleanup();
  13378. ASSERT_EQ(0, ret);
  13379. }
  13380. #endif
  13381. #ifndef CPPHTTPLIB_SSL_ENABLED
  13382. TEST(NoSSLSupport, SimpleInterface) {
  13383. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13384. }
  13385. #endif
  13386. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13387. TEST(InvalidScheme, SimpleInterface) {
  13388. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13389. }
  13390. #endif
  13391. TEST(NoScheme, SimpleInterface) {
  13392. Client cli("yahoo.com:80");
  13393. ASSERT_TRUE(cli.is_valid());
  13394. }
  13395. TEST(SendAPI, SimpleInterface_Online) {
  13396. Client cli("http://yahoo.com");
  13397. Request req;
  13398. req.method = "GET";
  13399. req.path = "/";
  13400. auto res = cli.send(req);
  13401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13402. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13403. }
  13404. TEST(SendAPI, WithParamsInRequest) {
  13405. Server svr;
  13406. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13407. EXPECT_TRUE(req.has_param("test"));
  13408. EXPECT_EQ("test_value", req.get_param_value("test"));
  13409. });
  13410. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13411. auto se = detail::scope_exit([&] {
  13412. svr.stop();
  13413. t.join();
  13414. ASSERT_FALSE(svr.is_running());
  13415. });
  13416. svr.wait_until_ready();
  13417. Client cli(HOST, PORT);
  13418. {
  13419. Request req;
  13420. req.method = "GET";
  13421. req.path = "/";
  13422. req.params.emplace("test", "test_value");
  13423. auto res = cli.send(req);
  13424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13425. }
  13426. {
  13427. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. }
  13430. }
  13431. TEST(ClientImplMethods, GetSocketTest) {
  13432. httplib::Server svr;
  13433. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13434. res.status = StatusCode::OK_200;
  13435. });
  13436. auto port = svr.bind_to_any_port("127.0.0.1");
  13437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13438. auto se = detail::scope_exit([&] {
  13439. svr.stop();
  13440. thread.join();
  13441. ASSERT_FALSE(svr.is_running());
  13442. });
  13443. svr.wait_until_ready();
  13444. {
  13445. httplib::Client cli("127.0.0.1", port);
  13446. cli.set_keep_alive(true);
  13447. // Use the behavior of cpp-httplib of opening the connection
  13448. // only when the first request happens. If that changes,
  13449. // this test would be obsolete.
  13450. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13451. // This also implicitly tests the server. But other tests would fail much
  13452. // earlier than this one to be considered.
  13453. auto res = cli.Get("/");
  13454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13455. EXPECT_EQ(StatusCode::OK_200, res->status);
  13456. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13457. }
  13458. }
  13459. #ifdef CPPHTTPLIB_SSL_ENABLED
  13460. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13461. Client cli("http://yahoo.com");
  13462. auto res = cli.Get("/");
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13465. cli.set_follow_location(true);
  13466. res = cli.Get("/");
  13467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13468. EXPECT_EQ(StatusCode::OK_200, res->status);
  13469. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13470. }
  13471. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13472. Client cli("https://yahoo.com");
  13473. auto res = cli.Get("/");
  13474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13475. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13476. cli.set_follow_location(true);
  13477. res = cli.Get("/");
  13478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13479. EXPECT_EQ(StatusCode::OK_200, res->status);
  13480. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13481. }
  13482. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13483. Client cli("https://yahoo.com");
  13484. auto res = cli.Get("/");
  13485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13486. ASSERT_FALSE(!res);
  13487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13488. ASSERT_FALSE(res == nullptr);
  13489. ASSERT_TRUE(res != nullptr);
  13490. EXPECT_EQ(Error::Success, res.error());
  13491. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13492. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13493. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13494. cli.set_follow_location(true);
  13495. res = cli.Get("/");
  13496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13497. EXPECT_EQ(Error::Success, res.error());
  13498. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13499. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13500. EXPECT_EQ(StatusCode::OK_200, res->status);
  13501. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13502. }
  13503. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13504. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13505. Client cli("https://cdnjs.cloudflare.com");
  13506. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13507. Headers{{"Accept-Encoding", "br"}});
  13508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13509. EXPECT_EQ(StatusCode::OK_200, res->status);
  13510. EXPECT_EQ(287630U, res->body.size());
  13511. EXPECT_EQ("application/javascript; charset=utf-8",
  13512. res->get_header_value("Content-Type"));
  13513. }
  13514. #endif
  13515. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13516. #undef REDIR_HOST // Silence compiler warning
  13517. #define REDIR_HOST "https://httpbingo.org"
  13518. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13519. Client cli(REDIR_HOST);
  13520. cli.set_follow_location(true);
  13521. auto res =
  13522. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13524. EXPECT_EQ(StatusCode::OK_200, res->status);
  13525. }
  13526. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13527. Client cli(REDIR_HOST);
  13528. cli.set_follow_location(true);
  13529. Params params;
  13530. params.emplace("url", "http://example.com");
  13531. params.emplace("status_code", "302");
  13532. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13534. EXPECT_EQ(StatusCode::OK_200, res->status);
  13535. }
  13536. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13537. Client cli(REDIR_HOST);
  13538. cli.set_follow_location(true);
  13539. Params params;
  13540. params.emplace("url", "http://example.com");
  13541. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13543. EXPECT_EQ(StatusCode::OK_200, res->status);
  13544. }
  13545. TEST(HttpToHttpsRedirectTest, CertFile) {
  13546. auto ssl_port = PORT + 1;
  13547. Server svr;
  13548. ASSERT_TRUE(svr.is_valid());
  13549. svr.Get("/index", [&](const Request &, Response &res) {
  13550. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13551. "/index");
  13552. svr.stop();
  13553. });
  13554. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13555. ASSERT_TRUE(ssl_svr.is_valid());
  13556. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13557. res.set_content("test", "text/plain");
  13558. ssl_svr.stop();
  13559. });
  13560. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13561. thread t2 =
  13562. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13563. auto se = detail::scope_exit([&] {
  13564. t2.join();
  13565. t.join();
  13566. ASSERT_FALSE(svr.is_running());
  13567. });
  13568. svr.wait_until_ready();
  13569. ssl_svr.wait_until_ready();
  13570. Client cli("127.0.0.1", PORT);
  13571. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13572. cli.enable_server_certificate_verification(true);
  13573. cli.set_follow_location(true);
  13574. cli.set_connection_timeout(30);
  13575. auto res = cli.Get("/index");
  13576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13577. ASSERT_EQ(StatusCode::OK_200, res->status);
  13578. }
  13579. TEST(SSLClientRedirectTest, CertFile) {
  13580. auto ssl_port = PORT + 1;
  13581. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13582. ASSERT_TRUE(ssl_svr1.is_valid());
  13583. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13584. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13585. "/index");
  13586. ssl_svr1.stop();
  13587. });
  13588. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13589. ASSERT_TRUE(ssl_svr2.is_valid());
  13590. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13591. res.set_content("test", "text/plain");
  13592. ssl_svr2.stop();
  13593. });
  13594. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13595. thread t2 =
  13596. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13597. auto se = detail::scope_exit([&] {
  13598. t2.join();
  13599. t.join();
  13600. ASSERT_FALSE(ssl_svr1.is_running());
  13601. });
  13602. ssl_svr1.wait_until_ready();
  13603. ssl_svr2.wait_until_ready();
  13604. SSLClient cli("127.0.0.1", PORT);
  13605. std::string cert;
  13606. read_file(SERVER_CERT2_FILE, cert);
  13607. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13608. cli.enable_server_certificate_verification(true);
  13609. cli.set_follow_location(true);
  13610. cli.set_connection_timeout(30);
  13611. auto res = cli.Get("/index");
  13612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13613. ASSERT_EQ(StatusCode::OK_200, res->status);
  13614. }
  13615. #endif
  13616. #ifdef CPPHTTPLIB_SSL_ENABLED
  13617. // Test that set_ca_cert_store() skips system certs (consistent with
  13618. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13619. // should be trusted - system certs should NOT be loaded.
  13620. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13621. // Load a specific cert that is NOT a system CA cert
  13622. std::string cert;
  13623. read_file(SERVER_CERT2_FILE, cert);
  13624. SSLClient cli("google.com");
  13625. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13626. cli.enable_server_certificate_verification(true);
  13627. // This should FAIL because:
  13628. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13629. // 2. System certs should NOT be loaded when custom store is set
  13630. // If system certs WERE loaded, this would succeed
  13631. auto res = cli.Get("/");
  13632. ASSERT_FALSE(res);
  13633. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13634. }
  13635. // Same as above, but through the native store handle path. Regression test:
  13636. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13637. // merged system certs into the user-provided store.
  13638. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13639. std::string cert;
  13640. read_file(SERVER_CERT2_FILE, cert);
  13641. SSLClient cli("google.com");
  13642. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13643. cli.enable_server_certificate_verification(true);
  13644. auto res = cli.Get("/");
  13645. ASSERT_FALSE(res);
  13646. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13647. }
  13648. // A custom store set via the native handle must still verify a server whose
  13649. // cert it does contain.
  13650. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13651. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13652. ASSERT_TRUE(svr.is_valid());
  13653. svr.Get("/test", [&](const Request &, Response &res) {
  13654. res.set_content("test", "text/plain");
  13655. });
  13656. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13657. auto se = detail::scope_exit([&] {
  13658. svr.stop();
  13659. t.join();
  13660. ASSERT_FALSE(svr.is_running());
  13661. });
  13662. svr.wait_until_ready();
  13663. SSLClient cli("127.0.0.1", PORT);
  13664. std::string cert;
  13665. read_file(SERVER_CERT2_FILE, cert);
  13666. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13667. cli.enable_server_certificate_verification(true);
  13668. cli.set_connection_timeout(30);
  13669. auto res = cli.Get("/test");
  13670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13671. ASSERT_EQ(StatusCode::OK_200, res->status);
  13672. }
  13673. // CA certs loaded through the universal Client must be transferred to the
  13674. // client created internally for following an HTTPS redirect. Regression test:
  13675. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13676. // the CA data for redirect transfer.
  13677. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13678. auto ssl_port = PORT + 1;
  13679. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13680. ASSERT_TRUE(ssl_svr1.is_valid());
  13681. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13682. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13683. "/index");
  13684. });
  13685. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13686. ASSERT_TRUE(ssl_svr2.is_valid());
  13687. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13688. res.set_content("test", "text/plain");
  13689. });
  13690. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13691. thread t2 =
  13692. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13693. auto se = detail::scope_exit([&] {
  13694. ssl_svr2.stop();
  13695. ssl_svr1.stop();
  13696. t2.join();
  13697. t.join();
  13698. ASSERT_FALSE(ssl_svr1.is_running());
  13699. });
  13700. ssl_svr1.wait_until_ready();
  13701. ssl_svr2.wait_until_ready();
  13702. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13703. std::string cert;
  13704. read_file(SERVER_CERT2_FILE, cert);
  13705. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13706. cli.enable_server_certificate_verification(true);
  13707. cli.set_follow_location(true);
  13708. cli.set_connection_timeout(30);
  13709. auto res = cli.Get("/index");
  13710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13711. ASSERT_EQ(StatusCode::OK_200, res->status);
  13712. }
  13713. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13714. // so a host signed by a system CA verifies even though a custom CA is set
  13715. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13716. std::string cert;
  13717. read_file(SERVER_CERT2_FILE, cert);
  13718. SSLClient cli("google.com");
  13719. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13720. cli.enable_system_ca(true);
  13721. cli.enable_server_certificate_verification(true);
  13722. auto res = cli.Get("/");
  13723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13724. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13725. }
  13726. // The custom CA remains effective when combined with the system CA
  13727. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13728. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13729. ASSERT_TRUE(svr.is_valid());
  13730. svr.Get("/test", [&](const Request &, Response &res) {
  13731. res.set_content("test", "text/plain");
  13732. });
  13733. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13734. auto se = detail::scope_exit([&] {
  13735. svr.stop();
  13736. t.join();
  13737. ASSERT_FALSE(svr.is_running());
  13738. });
  13739. svr.wait_until_ready();
  13740. SSLClient cli("127.0.0.1", PORT);
  13741. std::string cert;
  13742. read_file(SERVER_CERT2_FILE, cert);
  13743. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13744. cli.enable_system_ca(true);
  13745. cli.enable_server_certificate_verification(true);
  13746. cli.set_connection_timeout(30);
  13747. auto res = cli.Get("/test");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. ASSERT_EQ(StatusCode::OK_200, res->status);
  13750. }
  13751. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13752. // skip chain verification entirely (only the certificate identity was
  13753. // checked), so a server presenting an untrusted certificate with a matching
  13754. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13755. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13756. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13757. ASSERT_TRUE(svr.is_valid());
  13758. svr.Get("/test", [&](const Request &, Response &res) {
  13759. res.set_content("test", "text/plain");
  13760. });
  13761. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13762. auto se = detail::scope_exit([&] {
  13763. svr.stop();
  13764. t.join();
  13765. ASSERT_FALSE(svr.is_running());
  13766. });
  13767. svr.wait_until_ready();
  13768. SSLClient cli("127.0.0.1", PORT);
  13769. std::string cert;
  13770. // A trusted CA that did not sign the server certificate. The server cert
  13771. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13772. // this connection.
  13773. read_file(CLIENT_CA_CERT_FILE, cert);
  13774. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13775. cli.enable_server_certificate_verification(true);
  13776. cli.set_connection_timeout(30);
  13777. auto res = cli.Get("/test");
  13778. ASSERT_FALSE(res);
  13779. }
  13780. // enable_system_ca(false) prevents system CA loading entirely
  13781. TEST(SSLClientTest, DisableSystemCa_Online) {
  13782. SSLClient cli("google.com");
  13783. cli.enable_system_ca(false);
  13784. cli.enable_server_certificate_verification(true);
  13785. auto res = cli.Get("/");
  13786. ASSERT_FALSE(res);
  13787. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13788. // itself when the CA chain is empty
  13789. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13790. res.error() == Error::SSLConnection);
  13791. }
  13792. // The universal Client forwards enable_system_ca()
  13793. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13794. std::string cert;
  13795. read_file(SERVER_CERT2_FILE, cert);
  13796. Client cli("https://google.com");
  13797. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13798. cli.enable_system_ca(true);
  13799. cli.enable_server_certificate_verification(true);
  13800. auto res = cli.Get("/");
  13801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13802. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13803. }
  13804. // The system CA policy must carry over to the client created internally for
  13805. // following a cross-host HTTPS redirect
  13806. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13807. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13808. ASSERT_TRUE(svr.is_valid());
  13809. svr.Get("/index", [&](const Request &, Response &res) {
  13810. res.set_redirect("https://www.google.com/");
  13811. });
  13812. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13813. auto se = detail::scope_exit([&] {
  13814. svr.stop();
  13815. t.join();
  13816. ASSERT_FALSE(svr.is_running());
  13817. });
  13818. svr.wait_until_ready();
  13819. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13820. std::string cert;
  13821. read_file(SERVER_CERT2_FILE, cert);
  13822. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13823. cli.enable_system_ca(true);
  13824. cli.enable_server_certificate_verification(true);
  13825. cli.set_follow_location(true);
  13826. cli.set_connection_timeout(30);
  13827. // Receiving any response proves the redirect client completed the TLS
  13828. // handshake with a system-CA-signed host
  13829. auto res = cli.Get("/index");
  13830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13831. }
  13832. TEST(MultipartFormDataTest, LargeData) {
  13833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13835. const ContentReader &content_reader) {
  13836. if (req.is_multipart_form_data()) {
  13837. std::vector<FormData> items;
  13838. content_reader(
  13839. [&](const FormData &file) {
  13840. items.push_back(file);
  13841. return true;
  13842. },
  13843. [&](const char *data, size_t data_length) {
  13844. items.back().content.append(data, data_length);
  13845. return true;
  13846. });
  13847. EXPECT_TRUE(std::string(items[0].name) == "document");
  13848. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13849. EXPECT_TRUE(items[0].filename == "2MB_data");
  13850. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13851. EXPECT_TRUE(items[1].name == "hello");
  13852. EXPECT_TRUE(items[1].content == "world");
  13853. EXPECT_TRUE(items[1].filename == "");
  13854. EXPECT_TRUE(items[1].content_type == "");
  13855. } else {
  13856. std::string body;
  13857. content_reader([&](const char *data, size_t data_length) {
  13858. body.append(data, data_length);
  13859. return true;
  13860. });
  13861. }
  13862. });
  13863. auto port = svr.bind_to_any_port(HOST);
  13864. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13865. auto se = detail::scope_exit([&] {
  13866. svr.stop();
  13867. t.join();
  13868. ASSERT_FALSE(svr.is_running());
  13869. });
  13870. svr.wait_until_ready();
  13871. {
  13872. std::string data(1024 * 1024 * 2, '.');
  13873. std::stringstream buffer;
  13874. buffer << data;
  13875. SSLClient cli(HOST, port);
  13876. cli.enable_server_certificate_verification(false);
  13877. UploadFormDataItems items{
  13878. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13879. {"hello", "world", "", ""},
  13880. };
  13881. auto res = cli.Post("/post", items);
  13882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13883. ASSERT_EQ(StatusCode::OK_200, res->status);
  13884. }
  13885. }
  13886. TEST(MultipartFormDataTest, DataProviderItems) {
  13887. std::random_device seed_gen;
  13888. std::mt19937 random(seed_gen());
  13889. std::string rand1;
  13890. rand1.resize(1000);
  13891. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13892. std::string rand2;
  13893. rand2.resize(3000);
  13894. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13895. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13896. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13897. const ContentReader &content_reader) {
  13898. ASSERT_FALSE(req.is_multipart_form_data());
  13899. std::string body;
  13900. content_reader([&](const char *data, size_t data_length) {
  13901. body.append(data, data_length);
  13902. return true;
  13903. });
  13904. EXPECT_EQ(body, "");
  13905. });
  13906. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13907. const ContentReader &content_reader) {
  13908. ASSERT_TRUE(req.is_multipart_form_data());
  13909. std::vector<FormData> items;
  13910. content_reader(
  13911. [&](const FormData &file) {
  13912. items.push_back(file);
  13913. return true;
  13914. },
  13915. [&](const char *data, size_t data_length) {
  13916. items.back().content.append(data, data_length);
  13917. return true;
  13918. });
  13919. ASSERT_TRUE(items.size() == 2);
  13920. EXPECT_EQ(std::string(items[0].name), "name1");
  13921. EXPECT_EQ(items[0].content, "Testing123");
  13922. EXPECT_EQ(items[0].filename, "filename1");
  13923. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13924. EXPECT_EQ(items[1].name, "name2");
  13925. EXPECT_EQ(items[1].content, "Testing456");
  13926. EXPECT_EQ(items[1].filename, "");
  13927. EXPECT_EQ(items[1].content_type, "");
  13928. });
  13929. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13930. const ContentReader &content_reader) {
  13931. ASSERT_TRUE(req.is_multipart_form_data());
  13932. std::vector<FormData> items;
  13933. content_reader(
  13934. [&](const FormData &file) {
  13935. items.push_back(file);
  13936. return true;
  13937. },
  13938. [&](const char *data, size_t data_length) {
  13939. items.back().content.append(data, data_length);
  13940. return true;
  13941. });
  13942. ASSERT_TRUE(items.size() == 2);
  13943. EXPECT_EQ(items[0].name, "name3");
  13944. EXPECT_EQ(items[0].content, rand1);
  13945. EXPECT_EQ(items[0].filename, "filename3");
  13946. EXPECT_EQ(items[0].content_type, "");
  13947. EXPECT_EQ(items[1].name, "name4");
  13948. EXPECT_EQ(items[1].content, rand2);
  13949. EXPECT_EQ(items[1].filename, "filename4");
  13950. EXPECT_EQ(items[1].content_type, "");
  13951. });
  13952. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13953. const ContentReader &content_reader) {
  13954. ASSERT_TRUE(req.is_multipart_form_data());
  13955. std::vector<FormData> items;
  13956. content_reader(
  13957. [&](const FormData &file) {
  13958. items.push_back(file);
  13959. return true;
  13960. },
  13961. [&](const char *data, size_t data_length) {
  13962. items.back().content.append(data, data_length);
  13963. return true;
  13964. });
  13965. ASSERT_TRUE(items.size() == 4);
  13966. EXPECT_EQ(std::string(items[0].name), "name1");
  13967. EXPECT_EQ(items[0].content, "Testing123");
  13968. EXPECT_EQ(items[0].filename, "filename1");
  13969. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13970. EXPECT_EQ(items[1].name, "name2");
  13971. EXPECT_EQ(items[1].content, "Testing456");
  13972. EXPECT_EQ(items[1].filename, "");
  13973. EXPECT_EQ(items[1].content_type, "");
  13974. EXPECT_EQ(items[2].name, "name3");
  13975. EXPECT_EQ(items[2].content, rand1);
  13976. EXPECT_EQ(items[2].filename, "filename3");
  13977. EXPECT_EQ(items[2].content_type, "");
  13978. EXPECT_EQ(items[3].name, "name4");
  13979. EXPECT_EQ(items[3].content, rand2);
  13980. EXPECT_EQ(items[3].filename, "filename4");
  13981. EXPECT_EQ(items[3].content_type, "");
  13982. });
  13983. auto port = svr.bind_to_any_port("localhost");
  13984. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. t.join();
  13988. ASSERT_FALSE(svr.is_running());
  13989. });
  13990. svr.wait_until_ready();
  13991. {
  13992. SSLClient cli("localhost", port);
  13993. cli.enable_server_certificate_verification(false);
  13994. UploadFormDataItems items{
  13995. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13996. {"name2", "Testing456", "", ""}, // not a file
  13997. };
  13998. {
  13999. auto res = cli.Post("/post-none", {}, {}, {});
  14000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14001. ASSERT_EQ(StatusCode::OK_200, res->status);
  14002. }
  14003. FormDataProviderItems providers;
  14004. {
  14005. auto res =
  14006. cli.Post("/post-items", {}, items, providers); // empty providers
  14007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14008. ASSERT_EQ(StatusCode::OK_200, res->status);
  14009. }
  14010. providers.push_back({"name3",
  14011. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14012. // test the offset is given correctly at each step
  14013. if (!offset)
  14014. sink.os.write(rand1.data(), 30);
  14015. else if (offset == 30)
  14016. sink.os.write(rand1.data() + 30, 300);
  14017. else if (offset == 330)
  14018. sink.os.write(rand1.data() + 330, 670);
  14019. else if (offset == rand1.size())
  14020. sink.done();
  14021. return true;
  14022. },
  14023. "filename3",
  14024. {}});
  14025. providers.push_back({"name4",
  14026. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14027. // test the offset is given correctly at each step
  14028. if (!offset)
  14029. sink.os.write(rand2.data(), 2000);
  14030. else if (offset == 2000)
  14031. sink.os.write(rand2.data() + 2000, 1);
  14032. else if (offset == 2001)
  14033. sink.os.write(rand2.data() + 2001, 999);
  14034. else if (offset == rand2.size())
  14035. sink.done();
  14036. return true;
  14037. },
  14038. "filename4",
  14039. {}});
  14040. {
  14041. auto res = cli.Post("/post-providers", {}, {}, providers);
  14042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14043. ASSERT_EQ(StatusCode::OK_200, res->status);
  14044. }
  14045. {
  14046. auto res = cli.Post("/post-both", {}, items, providers);
  14047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14048. ASSERT_EQ(StatusCode::OK_200, res->status);
  14049. }
  14050. }
  14051. }
  14052. TEST(MultipartFormDataTest, BadHeader) {
  14053. Server svr;
  14054. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14055. res.set_content("ok", "text/plain");
  14056. });
  14057. thread t = thread([&] { svr.listen(HOST, PORT); });
  14058. auto se = detail::scope_exit([&] {
  14059. svr.stop();
  14060. t.join();
  14061. ASSERT_FALSE(svr.is_running());
  14062. });
  14063. svr.wait_until_ready();
  14064. const std::string body =
  14065. "This is the preamble. It is to be ignored, though it\r\n"
  14066. "is a handy place for composition agents to include an\r\n"
  14067. "explanatory note to non-MIME conformant readers.\r\n"
  14068. "\r\n"
  14069. "\r\n"
  14070. "--simple boundary\r\n"
  14071. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14072. ": BAD...\r\n"
  14073. "\r\n"
  14074. "value1\r\n"
  14075. "--simple boundary\r\n"
  14076. "Content-Disposition: form-data; name=\"field2\"; "
  14077. "filename=\"example.txt\"\r\n"
  14078. "\r\n"
  14079. "value2\r\n"
  14080. "--simple boundary--\r\n"
  14081. "This is the epilogue. It is also to be ignored.\r\n";
  14082. std::string content_type =
  14083. R"(multipart/form-data; boundary="simple boundary")";
  14084. Client cli(HOST, PORT);
  14085. auto res = cli.Post("/post", body, content_type.c_str());
  14086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14087. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14088. }
  14089. TEST(MultipartFormDataTest, WithPreamble) {
  14090. Server svr;
  14091. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14092. res.set_content("ok", "text/plain");
  14093. });
  14094. thread t = thread([&] { svr.listen(HOST, PORT); });
  14095. auto se = detail::scope_exit([&] {
  14096. svr.stop();
  14097. t.join();
  14098. ASSERT_FALSE(svr.is_running());
  14099. });
  14100. svr.wait_until_ready();
  14101. const std::string body =
  14102. "This is the preamble. It is to be ignored, though it\r\n"
  14103. "is a handy place for composition agents to include an\r\n"
  14104. "explanatory note to non-MIME conformant readers.\r\n"
  14105. "\r\n"
  14106. "\r\n"
  14107. "--simple boundary\r\n"
  14108. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14109. "\r\n"
  14110. "value1\r\n"
  14111. "--simple boundary\r\n"
  14112. "Content-Disposition: form-data; name=\"field2\"; "
  14113. "filename=\"example.txt\"\r\n"
  14114. "\r\n"
  14115. "value2\r\n"
  14116. "--simple boundary--\r\n"
  14117. "This is the epilogue. It is also to be ignored.\r\n";
  14118. std::string content_type =
  14119. R"(multipart/form-data; boundary="simple boundary")";
  14120. Client cli(HOST, PORT);
  14121. auto res = cli.Post("/post", body, content_type.c_str());
  14122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14123. EXPECT_EQ(StatusCode::OK_200, res->status);
  14124. }
  14125. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14126. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14127. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14128. const ContentReader &content_reader) {
  14129. if (req.is_multipart_form_data()) {
  14130. std::vector<FormData> items;
  14131. content_reader(
  14132. [&](const FormData &file) {
  14133. items.push_back(file);
  14134. return true;
  14135. },
  14136. [&](const char *data, size_t data_length) {
  14137. items.back().content.append(data, data_length);
  14138. return true;
  14139. });
  14140. EXPECT_TRUE(std::string(items[0].name) == "document");
  14141. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14142. EXPECT_TRUE(items[0].filename == "2MB_data");
  14143. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14144. EXPECT_TRUE(items[1].name == "hello");
  14145. EXPECT_TRUE(items[1].content == "world");
  14146. EXPECT_TRUE(items[1].filename == "");
  14147. EXPECT_TRUE(items[1].content_type == "");
  14148. } else {
  14149. std::string body;
  14150. content_reader([&](const char *data, size_t data_length) {
  14151. body.append(data, data_length);
  14152. return true;
  14153. });
  14154. }
  14155. });
  14156. auto port = svr.bind_to_any_port("localhost");
  14157. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14158. auto se = detail::scope_exit([&] {
  14159. svr.stop();
  14160. t.join();
  14161. ASSERT_FALSE(svr.is_running());
  14162. });
  14163. svr.wait_until_ready();
  14164. {
  14165. std::string data(1024 * 1024 * 2, '.');
  14166. std::stringstream buffer;
  14167. buffer << data;
  14168. SSLClient cli("localhost", port);
  14169. cli.enable_server_certificate_verification(false);
  14170. UploadFormDataItems items{
  14171. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14172. {"hello", "world", "", ""},
  14173. };
  14174. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14176. ASSERT_EQ(StatusCode::OK_200, res->status);
  14177. }
  14178. }
  14179. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14180. std::string data(1024 * 1024 * 2, '&');
  14181. std::stringstream buffer;
  14182. buffer << data;
  14183. Client cli("https://localhost:8080");
  14184. UploadFormDataItems items{
  14185. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14186. {"hello", "world", "", ""},
  14187. };
  14188. for (const char &c : " \t\r\n") {
  14189. auto res =
  14190. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14191. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14192. ASSERT_FALSE(res);
  14193. }
  14194. }
  14195. TEST(MultipartFormDataTest, PutFormData) {
  14196. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14197. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14198. const ContentReader &content_reader) {
  14199. if (req.is_multipart_form_data()) {
  14200. std::vector<FormData> items;
  14201. content_reader(
  14202. [&](const FormData &file) {
  14203. items.push_back(file);
  14204. return true;
  14205. },
  14206. [&](const char *data, size_t data_length) {
  14207. items.back().content.append(data, data_length);
  14208. return true;
  14209. });
  14210. EXPECT_TRUE(std::string(items[0].name) == "document");
  14211. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14212. EXPECT_TRUE(items[0].filename == "2MB_data");
  14213. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14214. EXPECT_TRUE(items[1].name == "hello");
  14215. EXPECT_TRUE(items[1].content == "world");
  14216. EXPECT_TRUE(items[1].filename == "");
  14217. EXPECT_TRUE(items[1].content_type == "");
  14218. } else {
  14219. std::string body;
  14220. content_reader([&](const char *data, size_t data_length) {
  14221. body.append(data, data_length);
  14222. return true;
  14223. });
  14224. }
  14225. });
  14226. auto port = svr.bind_to_any_port("localhost");
  14227. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14228. auto se = detail::scope_exit([&] {
  14229. svr.stop();
  14230. t.join();
  14231. ASSERT_FALSE(svr.is_running());
  14232. });
  14233. svr.wait_until_ready();
  14234. {
  14235. std::string data(1024 * 1024 * 2, '&');
  14236. std::stringstream buffer;
  14237. buffer << data;
  14238. SSLClient cli("localhost", port);
  14239. cli.enable_server_certificate_verification(false);
  14240. UploadFormDataItems items{
  14241. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14242. {"hello", "world", "", ""},
  14243. };
  14244. auto res = cli.Put("/put", items);
  14245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14246. ASSERT_EQ(StatusCode::OK_200, res->status);
  14247. }
  14248. }
  14249. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14251. svr.Put("/put_customboundary",
  14252. [&](const Request &req, const Response & /*res*/,
  14253. const ContentReader &content_reader) {
  14254. if (req.is_multipart_form_data()) {
  14255. std::vector<FormData> items;
  14256. content_reader(
  14257. [&](const FormData &file) {
  14258. items.push_back(file);
  14259. return true;
  14260. },
  14261. [&](const char *data, size_t data_length) {
  14262. items.back().content.append(data, data_length);
  14263. return true;
  14264. });
  14265. EXPECT_TRUE(std::string(items[0].name) == "document");
  14266. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14267. EXPECT_TRUE(items[0].filename == "2MB_data");
  14268. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14269. EXPECT_TRUE(items[1].name == "hello");
  14270. EXPECT_TRUE(items[1].content == "world");
  14271. EXPECT_TRUE(items[1].filename == "");
  14272. EXPECT_TRUE(items[1].content_type == "");
  14273. } else {
  14274. std::string body;
  14275. content_reader([&](const char *data, size_t data_length) {
  14276. body.append(data, data_length);
  14277. return true;
  14278. });
  14279. }
  14280. });
  14281. auto port = svr.bind_to_any_port("localhost");
  14282. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14283. auto se = detail::scope_exit([&] {
  14284. svr.stop();
  14285. t.join();
  14286. ASSERT_FALSE(svr.is_running());
  14287. });
  14288. svr.wait_until_ready();
  14289. {
  14290. std::string data(1024 * 1024 * 2, '&');
  14291. std::stringstream buffer;
  14292. buffer << data;
  14293. SSLClient cli("localhost", port);
  14294. cli.enable_server_certificate_verification(false);
  14295. UploadFormDataItems items{
  14296. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14297. {"hello", "world", "", ""},
  14298. };
  14299. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14301. ASSERT_EQ(StatusCode::OK_200, res->status);
  14302. }
  14303. }
  14304. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14305. std::string data(1024 * 1024 * 2, '&');
  14306. std::stringstream buffer;
  14307. buffer << data;
  14308. Client cli("https://localhost:8080");
  14309. cli.enable_server_certificate_verification(false);
  14310. UploadFormDataItems items{
  14311. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14312. {"hello", "world", "", ""},
  14313. };
  14314. for (const char &c : " \t\r\n") {
  14315. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14316. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14317. ASSERT_FALSE(res);
  14318. }
  14319. }
  14320. TEST(MultipartFormDataTest, AlternateFilename) {
  14321. auto handled = false;
  14322. Server svr;
  14323. svr.Post("/test", [&](const Request &req, Response &res) {
  14324. ASSERT_EQ(2u, req.form.files.size());
  14325. ASSERT_EQ(1u, req.form.fields.size());
  14326. // Test files
  14327. const auto &file1 = req.form.get_file("file1");
  14328. ASSERT_EQ("file1", file1.name);
  14329. ASSERT_EQ("A.txt", file1.filename);
  14330. ASSERT_EQ("text/plain", file1.content_type);
  14331. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14332. const auto &file2 = req.form.get_file("file2");
  14333. ASSERT_EQ("file2", file2.name);
  14334. ASSERT_EQ("a.html", file2.filename);
  14335. ASSERT_EQ("text/html", file2.content_type);
  14336. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14337. file2.content);
  14338. // Test text field
  14339. const auto &text = req.form.get_field("text");
  14340. ASSERT_EQ("text default", text);
  14341. res.set_content("ok", "text/plain");
  14342. handled = true;
  14343. });
  14344. thread t = thread([&] { svr.listen(HOST, PORT); });
  14345. auto se = detail::scope_exit([&] {
  14346. svr.stop();
  14347. t.join();
  14348. ASSERT_FALSE(svr.is_running());
  14349. ASSERT_TRUE(handled);
  14350. });
  14351. svr.wait_until_ready();
  14352. auto req = "POST /test HTTP/1.1\r\n"
  14353. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14354. "Content-Length: 399\r\n"
  14355. "\r\n"
  14356. "----------\r\n"
  14357. "Content-Disposition: form-data; name=\"text\"\r\n"
  14358. "\r\n"
  14359. "text default\r\n"
  14360. "----------\r\n"
  14361. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14362. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14363. "Content-Type: text/plain\r\n"
  14364. "\r\n"
  14365. "Content of a.txt.\r\n"
  14366. "\r\n"
  14367. "----------\r\n"
  14368. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14369. "\"a.html\"\r\n"
  14370. "Content-Type: text/html\r\n"
  14371. "\r\n"
  14372. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14373. "\r\n"
  14374. "------------\r\n";
  14375. ASSERT_TRUE(send_request(1, req));
  14376. }
  14377. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14378. auto handled = false;
  14379. Server svr;
  14380. svr.Post("/test", [&](const Request &req, Response &res) {
  14381. // Case-insensitive "utf-8''" prefix with a long value
  14382. const auto &file = req.form.get_file("file1");
  14383. ASSERT_EQ("file1", file.name);
  14384. // 8000 chars exercises both the Content-Disposition parser and the
  14385. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14386. // Prior to the fix, std::regex_match on this header would cause O(N)
  14387. // stack recursion in libstdc++, leading to SIGSEGV.
  14388. std::string expected_filename(8000, 'A');
  14389. ASSERT_EQ(expected_filename, file.filename);
  14390. res.set_content("ok", "text/plain");
  14391. handled = true;
  14392. });
  14393. thread t = thread([&] { svr.listen(HOST, PORT); });
  14394. auto se = detail::scope_exit([&] {
  14395. svr.stop();
  14396. t.join();
  14397. ASSERT_FALSE(svr.is_running());
  14398. ASSERT_TRUE(handled);
  14399. });
  14400. svr.wait_until_ready();
  14401. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14402. // Regression test for GHSA-qq6v-r583-3h69
  14403. std::string long_filename(8000, 'A');
  14404. std::string body = "----------\r\n"
  14405. "Content-Disposition: form-data; name=\"file1\"; "
  14406. "filename*=\"Utf-8''" +
  14407. long_filename +
  14408. "\"\r\n"
  14409. "\r\n"
  14410. "hello\r\n"
  14411. "------------\r\n";
  14412. auto req = "POST /test HTTP/1.1\r\n"
  14413. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14414. "Content-Length: " +
  14415. std::to_string(body.size()) + "\r\n\r\n" + body;
  14416. ASSERT_TRUE(send_request(1, req));
  14417. }
  14418. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14419. auto handled = false;
  14420. Server svr;
  14421. svr.Post("/test", [&](const Request &req, Response &) {
  14422. ASSERT_EQ(2u, req.form.fields.size());
  14423. const auto &text1 = req.form.get_field("text1");
  14424. ASSERT_EQ("text1", text1);
  14425. const auto &text2 = req.form.get_field("text2");
  14426. ASSERT_EQ("text2", text2);
  14427. handled = true;
  14428. });
  14429. thread t = thread([&] { svr.listen(HOST, PORT); });
  14430. auto se = detail::scope_exit([&] {
  14431. svr.stop();
  14432. t.join();
  14433. ASSERT_FALSE(svr.is_running());
  14434. ASSERT_TRUE(handled);
  14435. });
  14436. svr.wait_until_ready();
  14437. auto req = "POST /test HTTP/1.1\r\n"
  14438. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14439. "Content-Length: 146\r\n"
  14440. "\r\n----------\r\n"
  14441. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14442. "\r\n"
  14443. "text1"
  14444. "\r\n----------\r\n"
  14445. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14446. "\r\n"
  14447. "text2"
  14448. "\r\n------------";
  14449. std::string response;
  14450. ASSERT_TRUE(send_request(1, req, &response));
  14451. ASSERT_EQ("200", response.substr(9, 3));
  14452. }
  14453. TEST(MultipartFormDataTest, ContentLength) {
  14454. auto handled = false;
  14455. Server svr;
  14456. svr.Post("/test", [&](const Request &req, Response &) {
  14457. ASSERT_EQ(2u, req.form.fields.size());
  14458. const auto &text1 = req.form.get_field("text1");
  14459. ASSERT_EQ("text1", text1);
  14460. const auto &text2 = req.form.get_field("text2");
  14461. ASSERT_EQ("text2", text2);
  14462. handled = true;
  14463. });
  14464. thread t = thread([&] { svr.listen(HOST, PORT); });
  14465. auto se = detail::scope_exit([&] {
  14466. svr.stop();
  14467. t.join();
  14468. ASSERT_FALSE(svr.is_running());
  14469. ASSERT_TRUE(handled);
  14470. });
  14471. svr.wait_until_ready();
  14472. auto req = "POST /test HTTP/1.1\r\n"
  14473. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14474. "Content-Length: 167\r\n"
  14475. "\r\n----------\r\n"
  14476. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14477. "Content-Length: 5\r\n"
  14478. "\r\n"
  14479. "text1"
  14480. "\r\n----------\r\n"
  14481. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14482. "\r\n"
  14483. "text2"
  14484. "\r\n------------\r\n";
  14485. std::string response;
  14486. ASSERT_TRUE(send_request(1, req, &response));
  14487. ASSERT_EQ("200", response.substr(9, 3));
  14488. }
  14489. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14490. auto handled = false;
  14491. Server svr;
  14492. svr.Post("/test", [&](const Request &req, Response &) {
  14493. ASSERT_EQ(2u, req.form.fields.size());
  14494. const auto &text1 = req.form.get_field("text1");
  14495. ASSERT_EQ("text1", text1);
  14496. // TODO: Add header access for text fields if needed
  14497. const auto &text2 = req.form.get_field("text2");
  14498. ASSERT_EQ("text2", text2);
  14499. // TODO: Header access for text fields needs to be implemented
  14500. // auto &headers = it->second.headers;
  14501. // ASSERT_EQ(3U, headers.size());
  14502. // auto custom_header = headers.find("x-whatever");
  14503. // ASSERT_TRUE(custom_header != headers.end());
  14504. // ASSERT_NE("customvalue", custom_header->second);
  14505. // ASSERT_EQ("CustomValue", custom_header->second);
  14506. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14507. handled = true;
  14508. });
  14509. thread t = thread([&] { svr.listen(HOST, PORT); });
  14510. auto se = detail::scope_exit([&] {
  14511. svr.stop();
  14512. t.join();
  14513. ASSERT_FALSE(svr.is_running());
  14514. ASSERT_TRUE(handled);
  14515. });
  14516. svr.wait_until_ready();
  14517. auto req = "POST /test HTTP/1.1\r\n"
  14518. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14519. "Content-Length: 232\r\n"
  14520. "\r\n----------\r\n"
  14521. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14522. "Content-Length: 5\r\n"
  14523. "X-Test: 1\r\n"
  14524. "\r\n"
  14525. "text1"
  14526. "\r\n----------\r\n"
  14527. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14528. "Content-Type: text/plain\r\n"
  14529. "X-Whatever: CustomValue\r\n"
  14530. "\r\n"
  14531. "text2"
  14532. "\r\n------------\r\n"
  14533. "That should be disregarded. Not even read";
  14534. std::string response;
  14535. ASSERT_TRUE(send_request(1, req, &response));
  14536. ASSERT_EQ("200", response.substr(9, 3));
  14537. }
  14538. TEST(MultipartFormDataTest, LargeHeader) {
  14539. auto handled = false;
  14540. Server svr;
  14541. svr.Post("/test", [&](const Request &req, Response &) {
  14542. ASSERT_EQ(1u, req.form.fields.size());
  14543. const auto &text = req.form.get_field("name1");
  14544. ASSERT_EQ("text1", text);
  14545. handled = true;
  14546. });
  14547. thread t = thread([&] { svr.listen(HOST, PORT); });
  14548. auto se = detail::scope_exit([&] {
  14549. svr.stop();
  14550. t.join();
  14551. ASSERT_FALSE(svr.is_running());
  14552. ASSERT_TRUE(handled);
  14553. });
  14554. svr.wait_until_ready();
  14555. auto boundary = std::string("cpp-httplib-multipart-data");
  14556. std::string content = "--" + boundary +
  14557. "\r\n"
  14558. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14559. "\r\n"
  14560. "text1\r\n"
  14561. "--" +
  14562. boundary + "--\r\n";
  14563. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14564. "Content-Type: multipart/form-data;boundary=" +
  14565. boundary +
  14566. "\r\n"
  14567. "Content-Length: " +
  14568. std::to_string(content.size()) +
  14569. "\r\n"
  14570. "Dummy-Header: ";
  14571. std::string header_suffix = "\r\n"
  14572. "\r\n";
  14573. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14574. size_t header_dummy_size =
  14575. read_buff_size -
  14576. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14577. auto header_dummy = std::string(header_dummy_size, '@');
  14578. auto req = header_prefix + header_dummy + header_suffix + content;
  14579. std::string response;
  14580. ASSERT_TRUE(send_request(1, req, &response));
  14581. ASSERT_EQ("200", response.substr(9, 3));
  14582. }
  14583. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14584. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14585. // (not chunked Transfer-Encoding) after the streaming refactor.
  14586. auto handled = false;
  14587. Server svr;
  14588. svr.Post("/upload", [&](const Request &req, Response &res) {
  14589. auto cl_it = req.headers.find("Content-Length");
  14590. EXPECT_TRUE(cl_it != req.headers.end());
  14591. auto te_it = req.headers.find("Transfer-Encoding");
  14592. EXPECT_TRUE(te_it == req.headers.end());
  14593. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14594. res.set_content("ok", "text/plain");
  14595. handled = true;
  14596. });
  14597. auto port = svr.bind_to_any_port(HOST);
  14598. auto t = thread([&] { svr.listen_after_bind(); });
  14599. auto se = detail::scope_exit([&] {
  14600. svr.stop();
  14601. t.join();
  14602. ASSERT_FALSE(svr.is_running());
  14603. ASSERT_TRUE(handled);
  14604. });
  14605. svr.wait_until_ready();
  14606. UploadFormDataItems items = {
  14607. {"field1", "hello", "", "text/plain"},
  14608. {"file1", "world", "test.txt", "application/octet-stream"},
  14609. };
  14610. Client cli(HOST, port);
  14611. auto res = cli.Post("/upload", {}, items);
  14612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14613. EXPECT_EQ(StatusCode::OK_200, res->status);
  14614. }
  14615. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14616. // Verify that make_multipart_content_provider coalesces many small segments
  14617. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14618. constexpr size_t kItemCount = 1000;
  14619. UploadFormDataItems items;
  14620. items.reserve(kItemCount);
  14621. for (size_t i = 0; i < kItemCount; i++) {
  14622. items.push_back(
  14623. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14624. }
  14625. const std::string boundary = "----test-boundary";
  14626. auto content_length = detail::get_multipart_content_length(items, boundary);
  14627. auto provider = detail::make_multipart_content_provider(items, boundary);
  14628. // Drive the provider the same way write_content_with_progress does
  14629. size_t write_count = 0;
  14630. size_t total_bytes = 0;
  14631. DataSink sink;
  14632. size_t offset = 0;
  14633. sink.write = [&](const char *d, size_t l) -> bool {
  14634. (void)d;
  14635. write_count++;
  14636. total_bytes += l;
  14637. offset += l;
  14638. return true;
  14639. };
  14640. sink.is_writable = []() -> bool { return true; };
  14641. while (offset < content_length) {
  14642. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14643. }
  14644. EXPECT_EQ(content_length, total_bytes);
  14645. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14646. // With buffering into 64KB blocks, write_count should be much smaller.
  14647. auto segment_count = 3 * kItemCount + 1;
  14648. EXPECT_LT(write_count, segment_count / 10);
  14649. }
  14650. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14651. // Integration test: send many UploadFormDataItems and verify the server
  14652. // receives all of them correctly (#2410).
  14653. constexpr size_t kItemCount = 500;
  14654. auto handled = false;
  14655. Server svr;
  14656. svr.Post("/upload", [&](const Request &req, Response &res) {
  14657. EXPECT_EQ(kItemCount, req.form.fields.size());
  14658. for (size_t i = 0; i < kItemCount; i++) {
  14659. auto key = "field" + std::to_string(i);
  14660. auto val = "value" + std::to_string(i);
  14661. auto it = req.form.fields.find(key);
  14662. if (it != req.form.fields.end()) {
  14663. EXPECT_EQ(val, it->second.content);
  14664. } else {
  14665. ADD_FAILURE() << "Missing field: " << key;
  14666. }
  14667. }
  14668. res.set_content("ok", "text/plain");
  14669. handled = true;
  14670. });
  14671. auto port = svr.bind_to_any_port(HOST);
  14672. auto t = thread([&] { svr.listen_after_bind(); });
  14673. auto se = detail::scope_exit([&] {
  14674. svr.stop();
  14675. t.join();
  14676. ASSERT_FALSE(svr.is_running());
  14677. ASSERT_TRUE(handled);
  14678. });
  14679. svr.wait_until_ready();
  14680. UploadFormDataItems items;
  14681. items.reserve(kItemCount);
  14682. for (size_t i = 0; i < kItemCount; i++) {
  14683. items.push_back(
  14684. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14685. }
  14686. Client cli(HOST, port);
  14687. auto res = cli.Post("/upload", items);
  14688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14689. EXPECT_EQ(StatusCode::OK_200, res->status);
  14690. }
  14691. TEST(MultipartFormDataTest, MakeFileProvider) {
  14692. // Verify make_file_provider sends a file's contents correctly.
  14693. const std::string file_content(4096, 'Z');
  14694. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14695. {
  14696. std::ofstream ofs(tmp_path, std::ios::binary);
  14697. ofs.write(file_content.data(),
  14698. static_cast<std::streamsize>(file_content.size()));
  14699. }
  14700. auto handled = false;
  14701. Server svr;
  14702. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14703. const ContentReader &content_reader) {
  14704. ASSERT_TRUE(req.is_multipart_form_data());
  14705. std::vector<FormData> items;
  14706. content_reader(
  14707. [&](const FormData &file) {
  14708. items.push_back(file);
  14709. return true;
  14710. },
  14711. [&](const char *data, size_t data_length) {
  14712. items.back().content.append(data, data_length);
  14713. return true;
  14714. });
  14715. ASSERT_EQ(1u, items.size());
  14716. EXPECT_EQ("myfile", items[0].name);
  14717. EXPECT_EQ("data.bin", items[0].filename);
  14718. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14719. EXPECT_EQ(file_content, items[0].content);
  14720. handled = true;
  14721. });
  14722. auto port = svr.bind_to_any_port(HOST);
  14723. auto t = thread([&] { svr.listen_after_bind(); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. ASSERT_FALSE(svr.is_running());
  14728. ASSERT_TRUE(handled);
  14729. std::remove(tmp_path.c_str());
  14730. });
  14731. svr.wait_until_ready();
  14732. FormDataProviderItems providers;
  14733. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14734. "application/octet-stream"));
  14735. Client cli(HOST, port);
  14736. auto res = cli.Post("/upload", {}, {}, providers);
  14737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14738. EXPECT_EQ(StatusCode::OK_200, res->status);
  14739. }
  14740. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14741. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14742. // (100) headers is rejected with a 400 Bad Request response.
  14743. Server svr;
  14744. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14745. res.set_content("ok", "text/plain");
  14746. });
  14747. thread t = thread([&] { svr.listen(HOST, PORT); });
  14748. auto se = detail::scope_exit([&] {
  14749. svr.stop();
  14750. t.join();
  14751. ASSERT_FALSE(svr.is_running());
  14752. });
  14753. svr.wait_until_ready();
  14754. // Build a multipart part with 101 custom headers (exceeding
  14755. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14756. std::stringstream body;
  14757. body << "--simpleboundary\r\n"
  14758. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14759. for (int i = 0; i < 101; i++) {
  14760. body << "X-Custom-Header-" << i << ": value\r\n";
  14761. }
  14762. body << "\r\n"
  14763. << "value1\r\n"
  14764. << "--simpleboundary--\r\n";
  14765. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14766. Client cli(HOST, PORT);
  14767. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14769. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14770. }
  14771. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14772. // A body that never contains the declared boundary must not be accumulated
  14773. // while the parser waits for it. Buffering it would also make every read
  14774. // rescan everything seen so far, which is quadratic in the body size.
  14775. Server svr;
  14776. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14777. res.set_content("ok", "text/plain");
  14778. });
  14779. auto port = svr.bind_to_any_port(HOST);
  14780. thread t = thread([&] { svr.listen_after_bind(); });
  14781. auto se = detail::scope_exit([&] {
  14782. svr.stop();
  14783. t.join();
  14784. ASSERT_FALSE(svr.is_running());
  14785. });
  14786. svr.wait_until_ready();
  14787. Client cli(HOST, port);
  14788. cli.set_read_timeout(60, 0);
  14789. cli.set_write_timeout(60, 0);
  14790. // '-' is the worst case: it matches the first character of the boundary, so
  14791. // every position has to be checked against it.
  14792. auto post_dashes = [&](size_t size) {
  14793. const std::string body(size, '-');
  14794. auto start = std::chrono::steady_clock::now();
  14795. auto res =
  14796. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14797. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14798. std::chrono::steady_clock::now() - start)
  14799. .count();
  14800. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14801. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14802. return ms;
  14803. };
  14804. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14805. // Windows.
  14806. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14807. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14808. // Comparing the two sizes rather than checking an absolute duration keeps
  14809. // this meaningful across build types and CI load, both of which move the
  14810. // absolute numbers by more than an order of magnitude. Four times the bytes
  14811. // costs about four times the time when parsing is linear, and about sixteen
  14812. // times when the body is buffered and rescanned.
  14813. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14814. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14815. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14816. << "ms, which suggests the body is being buffered and rescanned";
  14817. }
  14818. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14819. // A boundary can only be followed by CRLF or by "--", so anything else is
  14820. // malformed no matter what comes next. The parser must say so right away
  14821. // instead of buffering the rest of the declared body.
  14822. Server svr;
  14823. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14824. res.set_content("ok", "text/plain");
  14825. });
  14826. auto port = svr.bind_to_any_port(HOST);
  14827. thread t = thread([&] { svr.listen_after_bind(); });
  14828. auto se = detail::scope_exit([&] {
  14829. svr.stop();
  14830. t.join();
  14831. ASSERT_FALSE(svr.is_running());
  14832. });
  14833. svr.wait_until_ready();
  14834. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14835. // buffers instead of failing would still be waiting for the remaining bytes.
  14836. const std::string body = "--zzzz\r\n"
  14837. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14838. "\r\n"
  14839. "text1"
  14840. "\r\n--zzzzXX";
  14841. const std::string req = "POST /post HTTP/1.1\r\n"
  14842. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14843. "Content-Length: 1048576\r\n"
  14844. "\r\n" +
  14845. body;
  14846. std::string response;
  14847. ASSERT_TRUE(send_request(3, req, &response, port));
  14848. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14849. EXPECT_EQ("400", response.substr(9, 3));
  14850. }
  14851. // Posts a multipart body split into two writes, so that the server sees the
  14852. // split at whatever offset the caller chose, and expects the single "text1"
  14853. // field to come through.
  14854. static void expect_split_multipart_ok(const std::string &body1,
  14855. const std::string &body2) {
  14856. auto handled = false;
  14857. Server svr;
  14858. svr.Post("/post", [&](const Request &req, Response &) {
  14859. EXPECT_EQ(1u, req.form.fields.size());
  14860. EXPECT_EQ("text1", req.form.get_field("text1"));
  14861. handled = true;
  14862. });
  14863. auto port = svr.bind_to_any_port(HOST);
  14864. thread t = thread([&] { svr.listen_after_bind(); });
  14865. auto se = detail::scope_exit([&] {
  14866. svr.stop();
  14867. t.join();
  14868. ASSERT_FALSE(svr.is_running());
  14869. ASSERT_TRUE(handled);
  14870. });
  14871. svr.wait_until_ready();
  14872. // "Connection: close" makes the server close once it has answered, so the
  14873. // response drain ends immediately instead of idling until the read timeout.
  14874. const std::string head =
  14875. "POST /post HTTP/1.1\r\n"
  14876. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14877. "Connection: close\r\n"
  14878. "Content-Length: " +
  14879. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14880. std::string response;
  14881. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14882. ASSERT_GE(response.size(), 12u) << "no response";
  14883. EXPECT_EQ("200", response.substr(9, 3));
  14884. }
  14885. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14886. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14887. // ignored, including when it does not arrive in the same read as the
  14888. // close-delimiter itself.
  14889. expect_split_multipart_ok("--zzzz\r\n"
  14890. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14891. "\r\n"
  14892. "text1"
  14893. "\r\n--zzzz--",
  14894. "\r\nthis epilogue must be ignored\r\n");
  14895. }
  14896. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14897. // The initial boundary may be preceded by a preamble of any length and may
  14898. // straddle a read boundary. Discarding data while waiting for it must not
  14899. // throw away a partial boundary sitting at the end of the buffer.
  14900. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14901. "zz\r\n"
  14902. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14903. "\r\n"
  14904. "text1"
  14905. "\r\n--zzzz--\r\n");
  14906. }
  14907. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14908. // The received boundary was only checked for being non-empty, so it could be
  14909. // as long as a header is allowed to be. The parser scans the body for
  14910. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14911. // costs a nearly full comparison at nearly every position, making the
  14912. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14913. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14914. Server svr;
  14915. svr.Post("/post", [](const Request &req, Response &res) {
  14916. EXPECT_EQ(1u, req.form.fields.size());
  14917. EXPECT_EQ("text1", req.form.get_field("text1"));
  14918. res.set_content("ok", "text/plain");
  14919. });
  14920. auto port = svr.bind_to_any_port(HOST);
  14921. thread t = thread([&] { svr.listen_after_bind(); });
  14922. auto se = detail::scope_exit([&] {
  14923. svr.stop();
  14924. t.join();
  14925. ASSERT_FALSE(svr.is_running());
  14926. });
  14927. svr.wait_until_ready();
  14928. Client cli(HOST, port);
  14929. auto post_with_boundary_of_length = [&](size_t len) {
  14930. const std::string boundary(len, 'a');
  14931. const std::string body =
  14932. "--" + boundary +
  14933. "\r\n"
  14934. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14935. "\r\n"
  14936. "text1"
  14937. "\r\n--" +
  14938. boundary + "--\r\n";
  14939. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14940. };
  14941. auto res = post_with_boundary_of_length(70);
  14942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14943. EXPECT_EQ(StatusCode::OK_200, res->status);
  14944. res = post_with_boundary_of_length(71);
  14945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14946. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14947. }
  14948. TEST(MakeFileBodyTest, Basic) {
  14949. const std::string file_content(4096, 'Z');
  14950. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14951. {
  14952. std::ofstream ofs(tmp_path, std::ios::binary);
  14953. ofs.write(file_content.data(),
  14954. static_cast<std::streamsize>(file_content.size()));
  14955. }
  14956. auto handled = false;
  14957. Server svr;
  14958. svr.Post("/upload", [&](const Request &req, Response &res) {
  14959. EXPECT_EQ(file_content, req.body);
  14960. handled = true;
  14961. res.status = StatusCode::OK_200;
  14962. });
  14963. auto port = svr.bind_to_any_port(HOST);
  14964. auto t = thread([&] { svr.listen_after_bind(); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. ASSERT_TRUE(handled);
  14970. std::remove(tmp_path.c_str());
  14971. });
  14972. svr.wait_until_ready();
  14973. auto fb = make_file_body(tmp_path);
  14974. ASSERT_GT(fb.first, 0u);
  14975. Client cli(HOST, port);
  14976. auto res =
  14977. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14979. EXPECT_EQ(StatusCode::OK_200, res->status);
  14980. }
  14981. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14982. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14983. {
  14984. std::ofstream ofs(path, std::ios::binary);
  14985. const std::string content(100, 'A');
  14986. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14987. }
  14988. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14989. auto body = make_file_body(path);
  14990. ASSERT_EQ(100u, body.first);
  14991. ASSERT_TRUE(static_cast<bool>(body.second));
  14992. // Rewritten shorter after its length was measured - and, on a server, after
  14993. // that length has already gone out as Content-Length.
  14994. {
  14995. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14996. const std::string content(10, 'A');
  14997. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14998. }
  14999. std::string written;
  15000. DataSink sink;
  15001. sink.write = [&](const char *d, size_t l) {
  15002. written.append(d, l);
  15003. return true;
  15004. };
  15005. // The provider has to report failure. write_content_with_progress() advances
  15006. // its offset only by what was written, so a provider that returns true
  15007. // without completing the length it promised is called again straight away,
  15008. // and again.
  15009. EXPECT_FALSE(body.second(0, body.first, sink));
  15010. EXPECT_EQ(std::string(10, 'A'), written);
  15011. }
  15012. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15013. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15014. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15015. {
  15016. std::ofstream ofs(path, std::ios::binary);
  15017. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15018. }
  15019. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15020. auto body = make_file_body(path);
  15021. ASSERT_EQ(content.size(), body.first);
  15022. ASSERT_TRUE(static_cast<bool>(body.second));
  15023. std::string written;
  15024. DataSink sink;
  15025. sink.write = [&](const char *d, size_t l) {
  15026. written.append(d, l);
  15027. return true;
  15028. };
  15029. EXPECT_TRUE(body.second(0, body.first, sink));
  15030. EXPECT_EQ(content, written);
  15031. }
  15032. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15033. static constexpr unsigned int number_of_tasks{1000000};
  15034. std::atomic_uint count{0};
  15035. std::unique_ptr<TaskQueue> task_queue{
  15036. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15037. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15038. auto queued = task_queue->enqueue(
  15039. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15040. EXPECT_TRUE(queued);
  15041. }
  15042. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15043. task_queue->shutdown();
  15044. #else
  15045. EXPECT_NO_THROW(task_queue->shutdown());
  15046. #endif
  15047. EXPECT_EQ(number_of_tasks, count.load());
  15048. }
  15049. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15050. static constexpr unsigned int number_of_tasks{1000000};
  15051. static constexpr unsigned int qlimit{2};
  15052. unsigned int queued_count{0};
  15053. std::atomic_uint count{0};
  15054. std::unique_ptr<TaskQueue> task_queue{
  15055. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15056. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15057. if (task_queue->enqueue(
  15058. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15059. queued_count++;
  15060. }
  15061. }
  15062. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15063. task_queue->shutdown();
  15064. #else
  15065. EXPECT_NO_THROW(task_queue->shutdown());
  15066. #endif
  15067. EXPECT_EQ(queued_count, count.load());
  15068. EXPECT_TRUE(queued_count <= number_of_tasks);
  15069. EXPECT_TRUE(queued_count >= qlimit);
  15070. }
  15071. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15072. // Use a short idle timeout so a dynamic thread spawns, times out and
  15073. // exits during the test, and the pool keeps working afterwards.
  15074. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15075. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15076. /*idle_timeout_sec=*/1}};
  15077. std::atomic_uint count{0};
  15078. std::condition_variable cv;
  15079. std::mutex mtx;
  15080. bool release = false;
  15081. // Block the base thread so the second task spawns a dynamic thread.
  15082. EXPECT_TRUE(task_queue->enqueue([&] {
  15083. std::unique_lock<std::mutex> lock(mtx);
  15084. while (!release) {
  15085. cv.wait(lock);
  15086. }
  15087. count++;
  15088. }));
  15089. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15090. // Let the dynamic thread finish its task and exceed the idle timeout.
  15091. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15092. {
  15093. std::unique_lock<std::mutex> lock(mtx);
  15094. release = true;
  15095. }
  15096. cv.notify_all();
  15097. // The pool must still accept and run tasks after the dynamic thread exited.
  15098. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15099. task_queue->shutdown();
  15100. EXPECT_EQ(3u, count.load());
  15101. }
  15102. TEST(TaskQueueTest, MaxQueuedRequests) {
  15103. static constexpr unsigned int qlimit{3};
  15104. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15105. std::condition_variable sem_cv;
  15106. std::mutex sem_mtx;
  15107. int credits = 0;
  15108. bool queued;
  15109. /* Fill up the queue with tasks that will block until we give them credits to
  15110. * complete. */
  15111. for (unsigned int n = 0; n <= qlimit;) {
  15112. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15113. std::unique_lock<std::mutex> lock(sem_mtx);
  15114. while (credits <= 0) {
  15115. sem_cv.wait(lock);
  15116. }
  15117. /* Consume the credit and signal the test code if they are all gone. */
  15118. if (--credits == 0) { sem_cv.notify_one(); }
  15119. });
  15120. if (n < qlimit) {
  15121. /* The first qlimit enqueues must succeed. */
  15122. EXPECT_TRUE(queued);
  15123. } else {
  15124. /* The last one will succeed only when the worker thread
  15125. * starts and dequeues the first blocking task. Although
  15126. * not necessary for the correctness of this test, we sleep for
  15127. * a short while to avoid busy waiting. */
  15128. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15129. }
  15130. if (queued) { n++; }
  15131. }
  15132. /* Further enqueues must fail since the queue is full. */
  15133. for (auto i = 0; i < 4; i++) {
  15134. queued = task_queue->enqueue([] {});
  15135. EXPECT_FALSE(queued);
  15136. }
  15137. /* Give the credits to allow the previous tasks to complete. */
  15138. {
  15139. std::unique_lock<std::mutex> lock(sem_mtx);
  15140. credits += qlimit + 1;
  15141. }
  15142. sem_cv.notify_all();
  15143. /* Wait for all the credits to be consumed. */
  15144. {
  15145. std::unique_lock<std::mutex> lock(sem_mtx);
  15146. while (credits > 0) {
  15147. sem_cv.wait(lock);
  15148. }
  15149. }
  15150. /* Check that we are able again to enqueue at least qlimit tasks. */
  15151. for (unsigned int i = 0; i < qlimit; i++) {
  15152. queued = task_queue->enqueue([] {});
  15153. EXPECT_TRUE(queued);
  15154. }
  15155. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15156. task_queue->shutdown();
  15157. #else
  15158. EXPECT_NO_THROW(task_queue->shutdown());
  15159. #endif
  15160. }
  15161. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15162. Server svr;
  15163. std::string method;
  15164. std::string body;
  15165. auto has_content_length = false;
  15166. auto has_transfer_encoding = false;
  15167. std::atomic<int> bad_requests{0};
  15168. // Leftover body bytes get parsed as a malformed request and answered with
  15169. // 400
  15170. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15171. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15172. });
  15173. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15174. res.set_redirect("/down", StatusCode::SeeOther_303);
  15175. });
  15176. svr.Get("/down", [&](const Request &req, Response &res) {
  15177. method = req.method;
  15178. body = req.body;
  15179. has_content_length = req.has_header("Content-Length");
  15180. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15181. res.set_content("ok", "text/plain");
  15182. });
  15183. auto port = svr.bind_to_any_port(HOST);
  15184. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15185. auto se = detail::scope_exit([&] {
  15186. svr.stop();
  15187. thread.join();
  15188. ASSERT_FALSE(svr.is_running());
  15189. });
  15190. svr.wait_until_ready();
  15191. const std::string payload = "SECRET-BODY";
  15192. auto check = [&](Client &cli, const Result &res) {
  15193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15194. EXPECT_EQ(StatusCode::OK_200, res->status);
  15195. EXPECT_EQ("ok", res->body);
  15196. EXPECT_EQ("GET", method);
  15197. EXPECT_TRUE(body.empty());
  15198. EXPECT_FALSE(has_content_length);
  15199. EXPECT_FALSE(has_transfer_encoding);
  15200. // Nothing of the original body may be left on the connection
  15201. auto res2 = cli.Get("/down");
  15202. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15203. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15204. EXPECT_EQ("ok", res2->body);
  15205. EXPECT_EQ(0, bad_requests);
  15206. };
  15207. // With content length
  15208. {
  15209. Client cli(HOST, port);
  15210. cli.set_keep_alive(true);
  15211. cli.set_follow_location(true);
  15212. auto res = cli.Post(
  15213. "/up", payload.size(),
  15214. [&](size_t offset, size_t length, DataSink &sink) {
  15215. return sink.write(payload.data() + offset, length);
  15216. },
  15217. "text/plain");
  15218. check(cli, res);
  15219. }
  15220. // Without content length (chunked)
  15221. {
  15222. Client cli(HOST, port);
  15223. cli.set_keep_alive(true);
  15224. cli.set_follow_location(true);
  15225. auto res = cli.Post(
  15226. "/up",
  15227. [&](size_t /*offset*/, DataSink &sink) {
  15228. sink.write(payload.data(), payload.size());
  15229. sink.done();
  15230. return true;
  15231. },
  15232. "text/plain");
  15233. check(cli, res);
  15234. }
  15235. }
  15236. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15237. Server svr;
  15238. std::string target;
  15239. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15240. // Echo the still-encoded name back in the Location
  15241. const std::string prefix = "/start/";
  15242. res.status = StatusCode::Found_302;
  15243. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15244. });
  15245. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15246. target = req.target;
  15247. res.set_content("ok", "text/plain");
  15248. });
  15249. auto port = svr.bind_to_any_port(HOST);
  15250. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15251. auto se = detail::scope_exit([&] {
  15252. svr.stop();
  15253. thread.join();
  15254. ASSERT_FALSE(svr.is_running());
  15255. });
  15256. svr.wait_until_ready();
  15257. // Decoding the Location path would turn the first four into a path
  15258. // separator, a query delimiter, a fragment delimiter and a different
  15259. // percent-encoded octet. The rest must keep reaching the server as they are.
  15260. const std::vector<std::string> names = {
  15261. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15262. };
  15263. for (auto path_encode : {true, false}) {
  15264. Client cli(HOST, port);
  15265. cli.set_follow_location(true);
  15266. cli.set_path_encode(path_encode);
  15267. for (const auto &name : names) {
  15268. target.clear();
  15269. auto res = cli.Get("/start/" + name);
  15270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15271. EXPECT_EQ(StatusCode::OK_200, res->status);
  15272. EXPECT_EQ("/dest/" + name, target);
  15273. }
  15274. }
  15275. }
  15276. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15277. Server svr;
  15278. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15279. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15280. });
  15281. svr.Get("/hello", [](const Request &req, Response &res) {
  15282. res.set_content(req.get_param_value("key"), "text/plain");
  15283. });
  15284. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15285. auto se = detail::scope_exit([&] {
  15286. svr.stop();
  15287. thread.join();
  15288. ASSERT_FALSE(svr.is_running());
  15289. });
  15290. svr.wait_until_ready();
  15291. {
  15292. Client cli(HOST, PORT);
  15293. cli.set_follow_location(true);
  15294. auto res = cli.Get("/");
  15295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15296. EXPECT_EQ(StatusCode::OK_200, res->status);
  15297. EXPECT_EQ("val&key2=val2", res->body);
  15298. }
  15299. }
  15300. #endif
  15301. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15302. Server svr;
  15303. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15304. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15305. });
  15306. svr.Get("/hello", [](const Request &req, Response &res) {
  15307. res.set_content(req.get_param_value("key"), "text/plain");
  15308. });
  15309. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. thread.join();
  15313. ASSERT_FALSE(svr.is_running());
  15314. });
  15315. svr.wait_until_ready();
  15316. {
  15317. Client cli(HOST, PORT);
  15318. cli.set_follow_location(true);
  15319. auto res = cli.Get("/");
  15320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15321. EXPECT_EQ(StatusCode::OK_200, res->status);
  15322. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15323. }
  15324. }
  15325. TEST(RedirectTest, RedirectWithPlusInPath) {
  15326. Server svr;
  15327. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15328. res.set_redirect("/a+b");
  15329. });
  15330. // Route pattern uses regex; escape + as \\+
  15331. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15332. res.set_content(req.path, "text/plain");
  15333. });
  15334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15335. auto se = detail::scope_exit([&] {
  15336. svr.stop();
  15337. thread.join();
  15338. ASSERT_FALSE(svr.is_running());
  15339. });
  15340. svr.wait_until_ready();
  15341. {
  15342. Client cli(HOST, PORT);
  15343. cli.set_follow_location(true);
  15344. auto res = cli.Get("/");
  15345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15346. EXPECT_EQ(StatusCode::OK_200, res->status);
  15347. EXPECT_EQ("/a+b", res->body);
  15348. }
  15349. }
  15350. TEST(RedirectTest, ResolveRelativeLocation) {
  15351. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15352. const std::vector<std::pair<std::string, std::string>> cases = {
  15353. {"g", "/b/c/g"},
  15354. {"./g", "/b/c/g"},
  15355. {"g/", "/b/c/g/"},
  15356. {"?y", "/b/c/d;p?y"},
  15357. {"g?y", "/b/c/g?y"},
  15358. {"#s", "/b/c/d;p?q#s"},
  15359. {"g#s", "/b/c/g#s"},
  15360. {"g?y#s", "/b/c/g?y#s"},
  15361. {";x", "/b/c/;x"},
  15362. {"g;x", "/b/c/g;x"},
  15363. {".", "/b/c/"},
  15364. {"./", "/b/c/"},
  15365. {"..", "/b/"},
  15366. {"../", "/b/"},
  15367. {"../g", "/b/g"},
  15368. {"../..", "/"},
  15369. {"../../", "/"},
  15370. {"../../g", "/g"},
  15371. {"../../../g", "/g"},
  15372. {"g.", "/b/c/g."},
  15373. {".g", "/b/c/.g"},
  15374. {"g..", "/b/c/g.."},
  15375. {"..g", "/b/c/..g"},
  15376. {"./../g", "/b/g"},
  15377. {"./g/.", "/b/c/g/"},
  15378. {"g/./h", "/b/c/g/h"},
  15379. {"g/../h", "/b/c/h"},
  15380. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15381. {"g;x=1/../y", "/b/c/y"},
  15382. {"g?y/./x", "/b/c/g?y/./x"},
  15383. {"g#s/../x", "/b/c/g#s/../x"},
  15384. // Not relative-path references, so left for parse_url.
  15385. {"/g", "/g"},
  15386. {"//g", "//g"},
  15387. {"http://g/x", "http://g/x"},
  15388. {"g:h", "g:h"},
  15389. };
  15390. for (const auto &c : cases) {
  15391. EXPECT_EQ(c.second,
  15392. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15393. << c.first;
  15394. }
  15395. }
  15396. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15397. Server svr;
  15398. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15399. res.set_redirect(req.get_param_value("to"));
  15400. });
  15401. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15402. res.set_content(req.target, "text/plain");
  15403. });
  15404. svr.Get("/other", [](const Request &req, Response &res) {
  15405. res.set_content(req.target, "text/plain");
  15406. });
  15407. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15408. auto se = detail::scope_exit([&] {
  15409. svr.stop();
  15410. thread.join();
  15411. ASSERT_FALSE(svr.is_running());
  15412. });
  15413. svr.wait_until_ready();
  15414. const std::vector<std::pair<std::string, std::string>> cases = {
  15415. {"next", "/dir/next"},
  15416. {"./next?x=1", "/dir/next?x=1"},
  15417. {"../other", "/other"},
  15418. };
  15419. for (const auto &c : cases) {
  15420. Client cli(HOST, PORT);
  15421. cli.set_follow_location(true);
  15422. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15423. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15424. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15425. EXPECT_EQ(c.second, res->body) << c.first;
  15426. }
  15427. }
  15428. #ifdef CPPHTTPLIB_SSL_ENABLED
  15429. TEST(RedirectTest, Issue2185_Online) {
  15430. SSLClient client("github.com");
  15431. client.set_follow_location(true);
  15432. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15433. "Coollab-Windows.zip");
  15434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15435. EXPECT_EQ(StatusCode::OK_200, res->status);
  15436. EXPECT_EQ(9920427U, res->body.size());
  15437. }
  15438. #endif
  15439. TEST(VulnerabilityTest, CRLFInjection) {
  15440. Server svr;
  15441. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15442. res.set_content("Hello 1", "text/plain");
  15443. });
  15444. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15445. res.set_content("Hello 2", "text/plain");
  15446. });
  15447. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15448. res.set_content("Hello 3", "text/plain");
  15449. });
  15450. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15451. res.set_content("Hello 4", "text/plain");
  15452. });
  15453. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15454. for (const auto &x : req.headers) {
  15455. auto key = x.first;
  15456. EXPECT_STRNE("evil", key.c_str());
  15457. }
  15458. });
  15459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15460. auto se = detail::scope_exit([&] {
  15461. svr.stop();
  15462. thread.join();
  15463. ASSERT_FALSE(svr.is_running());
  15464. });
  15465. svr.wait_until_ready();
  15466. {
  15467. Client cli(HOST, PORT);
  15468. cli.Post("/test1", "A=B",
  15469. "application/x-www-form-urlencoded\r\nevil: hello1");
  15470. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15471. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15472. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15473. }
  15474. }
  15475. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15476. auto server_thread = std::thread([] {
  15477. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15478. default_socket_options(srv);
  15479. sockaddr_in addr{};
  15480. addr.sin_family = AF_INET;
  15481. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15482. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15483. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15484. ::listen(srv, 1);
  15485. sockaddr_in cli_addr{};
  15486. socklen_t cli_len = sizeof(cli_addr);
  15487. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15489. std::string buf_all;
  15490. char buf[2048];
  15491. ssize_t n;
  15492. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15493. buf_all.append(buf, static_cast<size_t>(n));
  15494. size_t pos;
  15495. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15496. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15497. auto e = request_block.find("\r\n");
  15498. if (e != std::string::npos) {
  15499. auto request_line = request_block.substr(0, e);
  15500. std::string msg =
  15501. "CRLF injection detected in request line: '" + request_line + "'";
  15502. EXPECT_FALSE(true) << msg;
  15503. }
  15504. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15505. ::send(cli,
  15506. #ifdef _WIN32
  15507. static_cast<const char *>(resp.c_str()),
  15508. static_cast<int>(resp.size()),
  15509. #else
  15510. resp.c_str(), resp.size(),
  15511. #endif
  15512. 0);
  15513. buf_all.erase(0, pos + 4);
  15514. }
  15515. }
  15516. detail::close_socket(cli);
  15517. detail::close_socket(srv);
  15518. });
  15519. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15520. auto cli = Client("127.0.0.1", PORT + 1);
  15521. auto headers = Headers{
  15522. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15523. {"Connection", "keep-alive"}};
  15524. auto res = cli.Get("/hi", headers);
  15525. EXPECT_FALSE(res);
  15526. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15527. server_thread.join();
  15528. }
  15529. // A request rejected before any byte reaches the socket must fail right away
  15530. // instead of waiting for a response the server will never send.
  15531. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15532. // The kernel completes the TCP handshake from the listen backlog, so the
  15533. // client connects, but nothing ever reads, responds or closes.
  15534. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15535. default_socket_options(srv);
  15536. sockaddr_in addr{};
  15537. addr.sin_family = AF_INET;
  15538. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15539. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15540. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15541. ASSERT_EQ(0, ::listen(srv, 8));
  15542. auto cli = Client("127.0.0.1", PORT + 1);
  15543. cli.set_read_timeout(10, 0);
  15544. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15545. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15546. std::chrono::steady_clock::now() - start)
  15547. .count();
  15548. };
  15549. {
  15550. Request req;
  15551. req.method = "GE T";
  15552. req.path = "/";
  15553. auto start = std::chrono::steady_clock::now();
  15554. auto res = cli.send(req);
  15555. EXPECT_FALSE(res);
  15556. EXPECT_EQ(Error::Write, res.error());
  15557. EXPECT_LT(elapsed_ms(start), 1000);
  15558. }
  15559. {
  15560. auto start = std::chrono::steady_clock::now();
  15561. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15562. EXPECT_FALSE(res);
  15563. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15564. EXPECT_LT(elapsed_ms(start), 1000);
  15565. }
  15566. EXPECT_FALSE(cli.is_socket_open());
  15567. detail::close_socket(srv);
  15568. }
  15569. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15570. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15571. default_socket_options(srv);
  15572. sockaddr_in addr{};
  15573. addr.sin_family = AF_INET;
  15574. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15575. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15576. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15577. ASSERT_EQ(0, ::listen(srv, 1));
  15578. std::string received;
  15579. auto server_thread = std::thread([&] {
  15580. auto sock = ::accept(srv, nullptr, nullptr);
  15581. if (sock == INVALID_SOCKET) { return; }
  15582. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15583. char buf[2048];
  15584. ssize_t n;
  15585. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15586. received.append(buf, static_cast<size_t>(n));
  15587. }
  15588. detail::close_socket(sock);
  15589. });
  15590. {
  15591. auto cli = Client("127.0.0.1", PORT + 1);
  15592. // "Z" sorts after the default headers, so writing straight to the socket
  15593. // would have sent the request line and those headers before the rejection.
  15594. auto handle =
  15595. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15596. EXPECT_FALSE(handle.is_valid());
  15597. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15598. }
  15599. server_thread.join();
  15600. detail::close_socket(srv);
  15601. EXPECT_TRUE(received.empty()) << received;
  15602. }
  15603. TEST(PathParamsTest, StaticMatch) {
  15604. const auto pattern = "/users/all";
  15605. detail::PathParamsMatcher matcher(pattern);
  15606. Request request;
  15607. request.path = "/users/all";
  15608. ASSERT_TRUE(matcher.match(request));
  15609. std::unordered_map<std::string, std::string> expected_params = {};
  15610. EXPECT_EQ(request.path_params, expected_params);
  15611. }
  15612. TEST(PathParamsTest, StaticMismatch) {
  15613. const auto pattern = "/users/all";
  15614. detail::PathParamsMatcher matcher(pattern);
  15615. Request request;
  15616. request.path = "/users/1";
  15617. ASSERT_FALSE(matcher.match(request));
  15618. }
  15619. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15620. const auto pattern = "/users/:id/subscriptions";
  15621. detail::PathParamsMatcher matcher(pattern);
  15622. Request request;
  15623. request.path = "/users/42/subscriptions";
  15624. ASSERT_TRUE(matcher.match(request));
  15625. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15626. EXPECT_EQ(request.path_params, expected_params);
  15627. }
  15628. TEST(PathParamsTest, SingleParamInTheEnd) {
  15629. const auto pattern = "/users/:id";
  15630. detail::PathParamsMatcher matcher(pattern);
  15631. Request request;
  15632. request.path = "/users/24";
  15633. ASSERT_TRUE(matcher.match(request));
  15634. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15635. EXPECT_EQ(request.path_params, expected_params);
  15636. }
  15637. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15638. const auto pattern = "/users/:id/";
  15639. detail::PathParamsMatcher matcher(pattern);
  15640. Request request;
  15641. request.path = "/users/42/";
  15642. ASSERT_TRUE(matcher.match(request));
  15643. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15644. EXPECT_EQ(request.path_params, expected_params);
  15645. }
  15646. TEST(PathParamsTest, EmptyParam) {
  15647. const auto pattern = "/users/:id/";
  15648. detail::PathParamsMatcher matcher(pattern);
  15649. Request request;
  15650. request.path = "/users//";
  15651. ASSERT_TRUE(matcher.match(request));
  15652. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15653. EXPECT_EQ(request.path_params, expected_params);
  15654. }
  15655. TEST(PathParamsTest, FragmentMismatch) {
  15656. const auto pattern = "/users/:id/";
  15657. detail::PathParamsMatcher matcher(pattern);
  15658. Request request;
  15659. request.path = "/admins/24/";
  15660. ASSERT_FALSE(matcher.match(request));
  15661. }
  15662. TEST(PathParamsTest, ExtraFragments) {
  15663. const auto pattern = "/users/:id";
  15664. detail::PathParamsMatcher matcher(pattern);
  15665. Request request;
  15666. request.path = "/users/42/subscriptions";
  15667. ASSERT_FALSE(matcher.match(request));
  15668. }
  15669. TEST(PathParamsTest, MissingTrailingParam) {
  15670. const auto pattern = "/users/:id";
  15671. detail::PathParamsMatcher matcher(pattern);
  15672. Request request;
  15673. request.path = "/users";
  15674. ASSERT_FALSE(matcher.match(request));
  15675. }
  15676. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15677. const auto pattern = "/users/:id/subscriptions";
  15678. detail::PathParamsMatcher matcher(pattern);
  15679. Request request;
  15680. request.path = "/users/subscriptions";
  15681. ASSERT_FALSE(matcher.match(request));
  15682. }
  15683. TEST(PathParamsTest, MultipleParams) {
  15684. const auto pattern = "/users/:userid/subscriptions/:subid";
  15685. detail::PathParamsMatcher matcher(pattern);
  15686. Request request;
  15687. request.path = "/users/42/subscriptions/2";
  15688. ASSERT_TRUE(matcher.match(request));
  15689. std::unordered_map<std::string, std::string> expected_params = {
  15690. {"userid", "42"}, {"subid", "2"}};
  15691. EXPECT_EQ(request.path_params, expected_params);
  15692. }
  15693. TEST(PathParamsTest, SequenceOfParams) {
  15694. const auto pattern = "/values/:x/:y/:z";
  15695. detail::PathParamsMatcher matcher(pattern);
  15696. Request request;
  15697. request.path = "/values/1/2/3";
  15698. ASSERT_TRUE(matcher.match(request));
  15699. std::unordered_map<std::string, std::string> expected_params = {
  15700. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15701. EXPECT_EQ(request.path_params, expected_params);
  15702. }
  15703. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15704. const auto pattern = "/prefix:suffix";
  15705. detail::PathParamsMatcher matcher(pattern);
  15706. Request request;
  15707. request.path = "/prefix:suffix";
  15708. ASSERT_TRUE(matcher.match(request));
  15709. const std::unordered_map<std::string, std::string> expected_params = {};
  15710. EXPECT_EQ(request.path_params, expected_params);
  15711. }
  15712. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15713. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15714. // calling thread's stack on a long enough path for a quantified pattern;
  15715. // RegexMatcher must refuse to run regex matching on paths beyond
  15716. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15717. detail::RegexMatcher matcher("/files/(.*)");
  15718. Request within_limit;
  15719. within_limit.path = "/files/" + std::string(10, 'A');
  15720. EXPECT_TRUE(matcher.match(within_limit));
  15721. Request over_limit;
  15722. over_limit.path =
  15723. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15724. EXPECT_FALSE(matcher.match(over_limit));
  15725. }
  15726. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15727. Server svr;
  15728. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15729. res.set_content("ok", "text/plain");
  15730. });
  15731. auto port = svr.bind_to_any_port(HOST);
  15732. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15733. auto se = detail::scope_exit([&] {
  15734. svr.stop();
  15735. thread.join();
  15736. ASSERT_FALSE(svr.is_running());
  15737. });
  15738. svr.wait_until_ready();
  15739. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15740. // request URI limit; this used to be able to crash the process.
  15741. std::string path =
  15742. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15743. std::string req = "GET " + path +
  15744. " HTTP/1.1\r\n"
  15745. "Host: " +
  15746. std::string(HOST) + ":" + std::to_string(port) +
  15747. "\r\n"
  15748. "Connection: close\r\n"
  15749. "\r\n";
  15750. std::string response;
  15751. ASSERT_TRUE(send_request(5, req, &response, port));
  15752. EXPECT_NE(std::string::npos, response.find("404"));
  15753. }
  15754. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15755. Server svr;
  15756. auto handler = [](const Request & /*req*/, Response &res) {
  15757. res.set_content("hit", "text/plain");
  15758. };
  15759. // No regex metacharacter, so this one is compared literally
  15760. svr.Get("/literal/route", handler);
  15761. // '.' is a regex metacharacter, so this one must keep regex semantics
  15762. svr.Get("/a.c", handler);
  15763. auto port = svr.bind_to_any_port(HOST);
  15764. std::thread t([&]() { svr.listen_after_bind(); });
  15765. auto se = detail::scope_exit([&] {
  15766. svr.stop();
  15767. t.join();
  15768. ASSERT_FALSE(svr.is_running());
  15769. });
  15770. svr.wait_until_ready();
  15771. Client cli(HOST, port);
  15772. struct {
  15773. const char *path;
  15774. int status;
  15775. } cases[] = {
  15776. {"/literal/route", StatusCode::OK_200},
  15777. {"/literal/routes", StatusCode::NotFound_404},
  15778. {"/literal/rout", StatusCode::NotFound_404},
  15779. {"/abc", StatusCode::OK_200},
  15780. {"/a.c", StatusCode::OK_200},
  15781. };
  15782. for (const auto &x : cases) {
  15783. auto res = cli.Get(x.path);
  15784. ASSERT_TRUE(res) << x.path;
  15785. EXPECT_EQ(x.status, res->status) << x.path;
  15786. }
  15787. }
  15788. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15789. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15790. // from exhausting the stack, so it must only constrain routes that actually
  15791. // run a regular expression. A literal route is matched by comparison and
  15792. // stays usable at any length.
  15793. Server svr;
  15794. const std::string pattern =
  15795. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15796. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15797. res.set_content("hit", "text/plain");
  15798. });
  15799. auto port = svr.bind_to_any_port(HOST);
  15800. std::thread t([&]() { svr.listen_after_bind(); });
  15801. auto se = detail::scope_exit([&] {
  15802. svr.stop();
  15803. t.join();
  15804. ASSERT_FALSE(svr.is_running());
  15805. });
  15806. svr.wait_until_ready();
  15807. Client cli(HOST, port);
  15808. auto res = cli.Get(pattern);
  15809. ASSERT_TRUE(res);
  15810. EXPECT_EQ(StatusCode::OK_200, res->status);
  15811. }
  15812. TEST(ParseUrlTest, VariousPatterns) {
  15813. {
  15814. detail::UrlComponents uc;
  15815. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15816. EXPECT_EQ("http", uc.scheme);
  15817. EXPECT_EQ("example.com", uc.host);
  15818. EXPECT_EQ("8080", uc.port);
  15819. EXPECT_EQ("/path", uc.path);
  15820. EXPECT_EQ("?q=1", uc.query);
  15821. }
  15822. {
  15823. detail::UrlComponents uc;
  15824. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15825. EXPECT_EQ("https", uc.scheme);
  15826. EXPECT_EQ("example.com", uc.host);
  15827. EXPECT_TRUE(uc.port.empty());
  15828. EXPECT_EQ("/path", uc.path);
  15829. }
  15830. {
  15831. detail::UrlComponents uc;
  15832. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15833. EXPECT_EQ("::1", uc.host);
  15834. EXPECT_EQ("8080", uc.port);
  15835. EXPECT_EQ("/path", uc.path);
  15836. }
  15837. {
  15838. detail::UrlComponents uc;
  15839. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15840. }
  15841. {
  15842. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15843. // the path while the connection still targets the bracketed host.
  15844. detail::UrlComponents uc;
  15845. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15846. }
  15847. {
  15848. detail::UrlComponents uc;
  15849. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15850. }
  15851. {
  15852. detail::UrlComponents uc;
  15853. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15854. EXPECT_EQ("::1", uc.host);
  15855. EXPECT_TRUE(uc.port.empty());
  15856. EXPECT_EQ("/path", uc.path);
  15857. }
  15858. {
  15859. detail::UrlComponents uc;
  15860. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15861. EXPECT_TRUE(uc.scheme.empty());
  15862. EXPECT_EQ("example.com", uc.host);
  15863. EXPECT_EQ("/path", uc.path);
  15864. EXPECT_EQ("?q=1", uc.query);
  15865. }
  15866. {
  15867. detail::UrlComponents uc;
  15868. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15869. EXPECT_TRUE(uc.host.empty());
  15870. EXPECT_EQ("/path", uc.path);
  15871. EXPECT_EQ("?q=1", uc.query);
  15872. }
  15873. {
  15874. detail::UrlComponents uc;
  15875. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15876. EXPECT_EQ("example.com", uc.host);
  15877. EXPECT_EQ("8080", uc.port);
  15878. }
  15879. {
  15880. // Unix socket path — must not be parsed as host
  15881. detail::UrlComponents uc;
  15882. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15883. EXPECT_TRUE(uc.host.empty());
  15884. }
  15885. {
  15886. detail::UrlComponents uc;
  15887. ASSERT_TRUE(detail::parse_url("", uc));
  15888. EXPECT_TRUE(uc.host.empty());
  15889. EXPECT_TRUE(uc.path.empty());
  15890. }
  15891. {
  15892. detail::UrlComponents uc;
  15893. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15894. }
  15895. {
  15896. detail::UrlComponents uc;
  15897. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15898. }
  15899. {
  15900. // Accepted by parse_url; callers restrict to http/https
  15901. detail::UrlComponents uc;
  15902. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15903. EXPECT_EQ("ftp", uc.scheme);
  15904. }
  15905. {
  15906. detail::UrlComponents uc;
  15907. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15908. }
  15909. {
  15910. detail::UrlComponents uc;
  15911. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15912. }
  15913. }
  15914. TEST(ParseUrlTest, FragmentHandling) {
  15915. {
  15916. detail::UrlComponents uc;
  15917. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15918. EXPECT_EQ("/path", uc.path);
  15919. EXPECT_TRUE(uc.query.empty());
  15920. }
  15921. {
  15922. detail::UrlComponents uc;
  15923. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15924. EXPECT_TRUE(uc.path.empty());
  15925. EXPECT_TRUE(uc.query.empty());
  15926. }
  15927. }
  15928. TEST(ParseUrlTest, UserinfoHandling) {
  15929. // Userinfo with @ but no colon — host includes @
  15930. detail::UrlComponents uc;
  15931. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15932. EXPECT_EQ("user@host.com", uc.host);
  15933. EXPECT_EQ("/path", uc.path);
  15934. }
  15935. TEST(ParseUrlTest, IPv6EdgeCases) {
  15936. {
  15937. detail::UrlComponents uc;
  15938. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15939. EXPECT_TRUE(uc.scheme.empty());
  15940. EXPECT_EQ("::1", uc.host);
  15941. EXPECT_EQ("8080", uc.port);
  15942. }
  15943. {
  15944. // Zone ID '%25' is not in [a-fA-F0-9:]
  15945. detail::UrlComponents uc;
  15946. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15947. }
  15948. }
  15949. TEST(ParseUrlTest, SchemeEdgeCases) {
  15950. {
  15951. detail::UrlComponents uc;
  15952. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15953. }
  15954. {
  15955. detail::UrlComponents uc;
  15956. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15957. }
  15958. {
  15959. detail::UrlComponents uc;
  15960. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15961. }
  15962. }
  15963. TEST(ParseUrlTest, PortEdgeCases) {
  15964. {
  15965. detail::UrlComponents uc;
  15966. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15967. EXPECT_TRUE(uc.port.empty());
  15968. EXPECT_EQ("/path", uc.path);
  15969. }
  15970. {
  15971. // parse_url accepts any port string; validation is done by parse_port
  15972. detail::UrlComponents uc;
  15973. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15974. EXPECT_EQ("abc", uc.port);
  15975. }
  15976. }
  15977. TEST(ParseUrlTest, WebSocketPatterns) {
  15978. {
  15979. detail::UrlComponents uc;
  15980. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15981. EXPECT_EQ("ws", uc.scheme);
  15982. EXPECT_EQ("echo.example.com", uc.host);
  15983. EXPECT_EQ("8080", uc.port);
  15984. EXPECT_EQ("/ws", uc.path);
  15985. }
  15986. {
  15987. detail::UrlComponents uc;
  15988. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15989. EXPECT_EQ("wss", uc.scheme);
  15990. EXPECT_EQ("echo.example.com", uc.host);
  15991. EXPECT_TRUE(uc.port.empty());
  15992. EXPECT_EQ("/ws", uc.path);
  15993. }
  15994. }
  15995. TEST(ParseUrlTest, QueryOnly) {
  15996. detail::UrlComponents uc;
  15997. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15998. EXPECT_TRUE(uc.host.empty());
  15999. EXPECT_TRUE(uc.path.empty());
  16000. EXPECT_EQ("?q=1&r=2", uc.query);
  16001. }
  16002. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16003. detail::UrlComponents uc;
  16004. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16005. EXPECT_TRUE(uc.scheme.empty());
  16006. EXPECT_EQ("example.com", uc.host);
  16007. EXPECT_EQ("443", uc.port);
  16008. EXPECT_EQ("/path", uc.path);
  16009. }
  16010. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16011. // If ipv6 regex working, regex match codepath is taken.
  16012. // else port will default to 80 in Client impl
  16013. int clientImplMagicPort = 80;
  16014. int port = 4321;
  16015. // above ports must be different to avoid false negative
  16016. EXPECT_NE(clientImplMagicPort, port);
  16017. std::string ipV6TestURL = "http://[ff06::c3]";
  16018. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16019. CLIENT_PRIVATE_KEY_FILE);
  16020. EXPECT_EQ(cli.port(), port);
  16021. }
  16022. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16023. auto file_path = "./www/dir/index.html";
  16024. auto dir_path = "./www/dir";
  16025. detail::FileStat stat_file(file_path);
  16026. EXPECT_TRUE(stat_file.is_file());
  16027. EXPECT_FALSE(stat_file.is_dir());
  16028. detail::FileStat stat_dir(dir_path);
  16029. EXPECT_FALSE(stat_dir.is_file());
  16030. EXPECT_TRUE(stat_dir.is_dir());
  16031. }
  16032. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16033. // IPv4 with default HTTP port (80)
  16034. EXPECT_EQ("example.com",
  16035. detail::make_host_and_port_string("example.com", 80, false));
  16036. // IPv4 with default HTTPS port (443)
  16037. EXPECT_EQ("example.com",
  16038. detail::make_host_and_port_string("example.com", 443, true));
  16039. // IPv4 with non-default HTTP port
  16040. EXPECT_EQ("example.com:8080",
  16041. detail::make_host_and_port_string("example.com", 8080, false));
  16042. // IPv4 with non-default HTTPS port
  16043. EXPECT_EQ("example.com:8443",
  16044. detail::make_host_and_port_string("example.com", 8443, true));
  16045. // IPv6 with default HTTP port (80)
  16046. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16047. // IPv6 with default HTTPS port (443)
  16048. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16049. // IPv6 with non-default HTTP port
  16050. EXPECT_EQ("[::1]:8080",
  16051. detail::make_host_and_port_string("::1", 8080, false));
  16052. // IPv6 with non-default HTTPS port
  16053. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16054. // IPv6 full address with default port
  16055. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16056. detail::make_host_and_port_string(
  16057. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16058. // IPv6 full address with non-default port
  16059. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16060. detail::make_host_and_port_string(
  16061. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16062. // IPv6 localhost with non-default port
  16063. EXPECT_EQ("[::1]:3000",
  16064. detail::make_host_and_port_string("::1", 3000, false));
  16065. // IPv6 with zone ID (link-local address) with default port
  16066. EXPECT_EQ("[fe80::1%eth0]",
  16067. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16068. // IPv6 with zone ID (link-local address) with non-default port
  16069. EXPECT_EQ("[fe80::1%eth0]:8080",
  16070. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16071. // Edge case: Port 443 with is_ssl=false (should add port)
  16072. EXPECT_EQ("example.com:443",
  16073. detail::make_host_and_port_string("example.com", 443, false));
  16074. // Edge case: Port 80 with is_ssl=true (should add port)
  16075. EXPECT_EQ("example.com:80",
  16076. detail::make_host_and_port_string("example.com", 80, true));
  16077. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16078. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16079. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16080. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16081. // Security fix: Already bracketed IPv6 should not get double brackets
  16082. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16083. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16084. EXPECT_EQ("[::1]:8080",
  16085. detail::make_host_and_port_string("[::1]", 8080, false));
  16086. EXPECT_EQ("[2001:db8::1]:8080",
  16087. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16088. EXPECT_EQ("[fe80::1%eth0]",
  16089. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16090. EXPECT_EQ("[fe80::1%eth0]:8080",
  16091. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16092. // Edge case: Empty host (should return as-is)
  16093. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16094. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16095. // This is a known limitation but shouldn't crash
  16096. EXPECT_EQ("[host:name]",
  16097. detail::make_host_and_port_string("host:name", 80, false));
  16098. // Port number edge cases (no validation, but should not crash)
  16099. EXPECT_EQ("example.com:0",
  16100. detail::make_host_and_port_string("example.com", 0, false));
  16101. EXPECT_EQ("example.com:-1",
  16102. detail::make_host_and_port_string("example.com", -1, false));
  16103. EXPECT_EQ("example.com:65535",
  16104. detail::make_host_and_port_string("example.com", 65535, false));
  16105. EXPECT_EQ("example.com:65536",
  16106. detail::make_host_and_port_string("example.com", 65536, false));
  16107. }
  16108. #ifdef CPPHTTPLIB_SSL_ENABLED
  16109. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16110. httplib::SSLClient cli("roblox.com", 443);
  16111. cli.set_follow_location(true);
  16112. auto res = cli.Get("/");
  16113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16114. EXPECT_EQ(StatusCode::OK_200, res->status);
  16115. }
  16116. #endif
  16117. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16118. Server svr;
  16119. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16120. EXPECT_EQ(res.status, 400);
  16121. });
  16122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16123. auto se = detail::scope_exit([&] {
  16124. svr.stop();
  16125. thread.join();
  16126. ASSERT_FALSE(svr.is_running());
  16127. });
  16128. svr.wait_until_ready();
  16129. Client cli(HOST, PORT);
  16130. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16131. }
  16132. TEST(InvalidHeaderCharsTest, is_field_name) {
  16133. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16134. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16135. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16136. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16137. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16138. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16139. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16140. EXPECT_FALSE(detail::fields::is_field_name(""));
  16141. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16142. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16143. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16144. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16145. }
  16146. TEST(InvalidHeaderCharsTest, is_field_value) {
  16147. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16148. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16149. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16150. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16151. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16152. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16153. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16154. EXPECT_TRUE(detail::fields::is_field_value(""));
  16155. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16156. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16157. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16158. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16159. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16160. }
  16161. TEST(InvalidHeaderCharsTest, OnServer) {
  16162. Server svr;
  16163. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16164. std::string header = "Not Set";
  16165. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16166. res.set_header(header, "value");
  16167. res.set_content("Page Content Page Content", "text/plain");
  16168. });
  16169. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16170. std::string header = "Not Set";
  16171. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16172. res.set_header("X-Test", header);
  16173. res.set_content("Page Content Page Content", "text/plain");
  16174. });
  16175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16176. auto se = detail::scope_exit([&] {
  16177. svr.stop();
  16178. thread.join();
  16179. ASSERT_FALSE(svr.is_running());
  16180. });
  16181. svr.wait_until_ready();
  16182. Client cli(HOST, PORT);
  16183. {
  16184. auto res = cli.Get(
  16185. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16187. EXPECT_EQ("Page Content Page Content", res->body);
  16188. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16189. }
  16190. {
  16191. auto res = cli.Get(
  16192. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16194. EXPECT_EQ("Page Content Page Content", res->body);
  16195. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16196. }
  16197. }
  16198. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16199. auto handled = false;
  16200. Server svr;
  16201. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16202. thread t = thread([&] { svr.listen(HOST, PORT); });
  16203. auto se = detail::scope_exit([&] {
  16204. svr.stop();
  16205. t.join();
  16206. ASSERT_FALSE(svr.is_running());
  16207. ASSERT_FALSE(handled);
  16208. });
  16209. svr.wait_until_ready();
  16210. auto req = "POST /test HTTP/1.1\r\n"
  16211. "Content-Length: x\r\n"
  16212. "\r\n";
  16213. std::string response;
  16214. ASSERT_TRUE(send_request(1, req, &response));
  16215. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16216. response.substr(0, response.find("\r\n")));
  16217. }
  16218. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16219. // case-insensitive, and a server that receives a 100-continue expectation in
  16220. // an HTTP/1.0 request MUST ignore it.
  16221. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16222. std::string response;
  16223. ASSERT_TRUE(send_request(1, req, &response, port));
  16224. *got_100 = response.find("100 Continue") != std::string::npos;
  16225. }
  16226. class ExpectTokenTest : public ::testing::Test {
  16227. protected:
  16228. void SetUp() override {
  16229. svr_.Post("/p", [](const Request &, Response &res) {
  16230. res.set_content("ok", "text/plain");
  16231. });
  16232. port_ = svr_.bind_to_any_port(HOST);
  16233. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16234. svr_.wait_until_ready();
  16235. }
  16236. void TearDown() override {
  16237. svr_.stop();
  16238. if (thread_.joinable()) { thread_.join(); }
  16239. }
  16240. std::string request(const char *version, const char *expect_value) const {
  16241. return std::string("POST /p ") + version +
  16242. "\r\n"
  16243. "Host: localhost\r\n"
  16244. "Content-Length: 2\r\n"
  16245. "Connection: close\r\n"
  16246. "Expect: " +
  16247. expect_value +
  16248. "\r\n"
  16249. "\r\n"
  16250. "hi";
  16251. }
  16252. Server svr_;
  16253. int port_ = 0;
  16254. thread thread_;
  16255. };
  16256. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16257. bool got_100 = false;
  16258. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16259. EXPECT_TRUE(got_100);
  16260. }
  16261. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16262. bool got_100 = true;
  16263. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16264. EXPECT_FALSE(got_100);
  16265. }
  16266. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16267. bool got_100 = false;
  16268. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16269. EXPECT_TRUE(got_100);
  16270. }
  16271. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16272. bool got_100 = false;
  16273. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16274. EXPECT_TRUE(got_100);
  16275. }
  16276. // `100 Continue` is sent only when the server starts reading the body, so a
  16277. // request rejected before that never invites the client to send it. The
  16278. // requests below carry the expectation but withhold the body, as a client
  16279. // waiting for `100 Continue` would.
  16280. // A POST that expects `100 Continue` and withholds its two-byte body.
  16281. static std::string expect_headers_only(const std::string &path) {
  16282. return "POST " + path +
  16283. " HTTP/1.1\r\n"
  16284. "Host: localhost\r\n"
  16285. "Content-Length: 2\r\n"
  16286. "Expect: 100-continue\r\n"
  16287. "\r\n";
  16288. }
  16289. class ExpectLazyContinueTest : public ::testing::Test {
  16290. protected:
  16291. void SetUp() override {
  16292. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16293. if (req.path == "/pre-routing") {
  16294. res.status = StatusCode::Unauthorized_401;
  16295. return Server::HandlerResponse::Handled;
  16296. }
  16297. return Server::HandlerResponse::Unhandled;
  16298. });
  16299. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16300. if (req.matched_route == "/pre-request") {
  16301. res.status = StatusCode::Forbidden_403;
  16302. return Server::HandlerResponse::Handled;
  16303. }
  16304. return Server::HandlerResponse::Unhandled;
  16305. });
  16306. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16307. res.set_content("ok", "text/plain");
  16308. });
  16309. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16310. res.set_content("ok", "text/plain");
  16311. });
  16312. svr_.Post("/reader-used", [](const Request &, Response &res,
  16313. const ContentReader &content_reader) {
  16314. std::string body;
  16315. content_reader([&](const char *data, size_t len) {
  16316. body.append(data, len);
  16317. return true;
  16318. });
  16319. res.set_content(body, "text/plain");
  16320. });
  16321. svr_.Post("/reader-unused",
  16322. [](const Request &, Response &res, const ContentReader &) {
  16323. res.set_content("ignored", "text/plain");
  16324. });
  16325. port_ = svr_.bind_to_any_port(HOST);
  16326. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16327. svr_.wait_until_ready();
  16328. }
  16329. void TearDown() override {
  16330. svr_.stop();
  16331. if (thread_.joinable()) { thread_.join(); }
  16332. }
  16333. // Sends `req` and reads until the server closes the connection. Returns
  16334. // false if the read had to wait for the client-side timeout instead.
  16335. bool send_until_closed(const std::string &req, std::string *resp) const {
  16336. auto start = std::chrono::steady_clock::now();
  16337. if (!send_request(3, req, resp, port_)) { return false; }
  16338. auto elapsed = std::chrono::steady_clock::now() - start;
  16339. return elapsed < std::chrono::seconds(2);
  16340. }
  16341. // The final response comes without `100 Continue`, and the server closes
  16342. // the connection since the body may or may not follow.
  16343. void expect_final_without_interim(const std::string &path,
  16344. const char *status_line) const {
  16345. std::string resp;
  16346. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16347. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16348. EXPECT_EQ(0u, resp.find(status_line));
  16349. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16350. }
  16351. Server svr_;
  16352. int port_ = 0;
  16353. thread thread_;
  16354. };
  16355. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16356. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16357. }
  16358. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16359. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16360. }
  16361. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16362. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16363. }
  16364. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16365. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16366. }
  16367. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16368. // The body follows once `100 Continue` has had time to arrive.
  16369. auto req = expect_headers_only("/reader-used");
  16370. req.insert(req.size() - 2, "Connection: close\r\n");
  16371. std::string resp;
  16372. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16373. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16374. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16375. EXPECT_NE(std::string::npos, resp.find("hi"));
  16376. }
  16377. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16378. // Large enough for the client to add `Expect: 100-continue` itself.
  16379. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16380. std::atomic<bool> body_sent{false};
  16381. Client cli(HOST, port_);
  16382. auto res = cli.Post(
  16383. "/pre-request", length,
  16384. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16385. body_sent = true;
  16386. std::string chunk(len, 'x');
  16387. sink.write(chunk.data(), chunk.size());
  16388. return true;
  16389. },
  16390. "application/octet-stream");
  16391. ASSERT_TRUE(res);
  16392. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16393. EXPECT_FALSE(body_sent);
  16394. }
  16395. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16396. Server svr;
  16397. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16398. return StatusCode::ExpectationFailed_417;
  16399. });
  16400. svr.Post("/p", [](const Request &, Response &res) {
  16401. res.set_content("ok", "text/plain");
  16402. });
  16403. auto port = svr.bind_to_any_port(HOST);
  16404. thread t = thread([&] { svr.listen_after_bind(); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. });
  16409. svr.wait_until_ready();
  16410. std::string resp;
  16411. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16412. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16413. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16414. // Exactly one response: the route handler must not run after the 417.
  16415. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16416. }
  16417. #ifndef _WIN32
  16418. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16419. static constexpr char reject[] = "Unauthorized";
  16420. static constexpr char accept[] = "Upload accepted";
  16421. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16422. Server svr;
  16423. svr.set_expect_100_continue_handler(
  16424. [](const Request & /*req*/, Response &res) {
  16425. res.status = StatusCode::Unauthorized_401;
  16426. res.set_content(reject, "text/plain");
  16427. return res.status;
  16428. });
  16429. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16430. res.set_content(accept, "text/plain");
  16431. });
  16432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16433. auto se = detail::scope_exit([&] {
  16434. svr.stop();
  16435. thread.join();
  16436. ASSERT_FALSE(svr.is_running());
  16437. });
  16438. svr.wait_until_ready();
  16439. {
  16440. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16441. curl_easy_init(), &curl_easy_cleanup};
  16442. ASSERT_NE(curl, nullptr);
  16443. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16444. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16445. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16446. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16447. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16448. &curl_slist_free_all};
  16449. ASSERT_NE(list, nullptr);
  16450. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16451. struct read_data {
  16452. size_t read_size;
  16453. size_t total_size;
  16454. } data = {0, total_size};
  16455. using read_callback_t =
  16456. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16457. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16458. void *userdata) -> size_t {
  16459. read_data *d = (read_data *)userdata;
  16460. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16461. std::fill_n(ptr, size * nmemb, 'A');
  16462. d->read_size += size * nmemb;
  16463. return size * nmemb;
  16464. };
  16465. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16466. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16467. std::vector<char> buffer;
  16468. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16469. using write_callback_t =
  16470. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16471. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16472. void *userdata) -> size_t {
  16473. std::vector<char> *buf = (std::vector<char> *)userdata;
  16474. buf->reserve(buf->size() + size * nmemb + 1);
  16475. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16476. return size * nmemb;
  16477. };
  16478. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16479. {
  16480. const auto res = curl_easy_perform(curl.get());
  16481. ASSERT_EQ(res, CURLE_OK);
  16482. }
  16483. {
  16484. auto response_code = long{};
  16485. const auto res =
  16486. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16487. ASSERT_EQ(res, CURLE_OK);
  16488. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16489. }
  16490. {
  16491. auto dl = curl_off_t{};
  16492. const auto res =
  16493. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16494. ASSERT_EQ(res, CURLE_OK);
  16495. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16496. }
  16497. {
  16498. buffer.push_back('\0');
  16499. ASSERT_STRCASEEQ(buffer.data(), reject);
  16500. }
  16501. }
  16502. }
  16503. #endif
  16504. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16505. // Regression test for #2458.
  16506. //
  16507. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16508. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16509. // ticket can make the client socket spuriously readable during the
  16510. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16511. // the client withholds the body and then blocks reading a response that never
  16512. // comes, failing with `Failed to read connection`.
  16513. //
  16514. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16515. // within the timeout. This raw OpenSSL server deliberately never sends
  16516. // `100 Continue`; the client must still deliver the body and receive 200.
  16517. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16518. signal(SIGPIPE, SIG_IGN);
  16519. const auto port = PORT + 4;
  16520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16521. ASSERT_NE(srv, INVALID_SOCKET);
  16522. int opt = 1;
  16523. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16524. sockaddr_in addr{};
  16525. addr.sin_family = AF_INET;
  16526. addr.sin_port = htons(static_cast<uint16_t>(port));
  16527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16528. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16529. ASSERT_EQ(0, ::listen(srv, 1));
  16530. std::atomic<size_t> server_body_bytes{0};
  16531. auto server_thread = std::thread([&] {
  16532. sockaddr_in cli_addr{};
  16533. socklen_t cli_len = sizeof(cli_addr);
  16534. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16535. if (cli == INVALID_SOCKET) { return; }
  16536. // Bound the lifetime of the server side so a buggy client (which never
  16537. // sends the body) cannot make this thread block forever on join.
  16538. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16539. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16540. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16541. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16542. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16543. SSL *ssl = SSL_new(ctx);
  16544. SSL_set_fd(ssl, static_cast<int>(cli));
  16545. if (SSL_accept(ssl) > 0) {
  16546. // Read the request headers. Reading here also flushes the TLS 1.3
  16547. // session tickets to the client. Deliberately do NOT send
  16548. // `100 Continue`.
  16549. std::string buf;
  16550. char tmp[1024];
  16551. while (buf.find("\r\n\r\n") == std::string::npos) {
  16552. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16553. if (n <= 0) { break; }
  16554. buf.append(tmp, static_cast<size_t>(n));
  16555. }
  16556. // A correct client sends the body now; count what arrives.
  16557. auto pos = buf.find("\r\n\r\n");
  16558. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16559. while (body < 4096) {
  16560. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16561. if (n <= 0) { break; }
  16562. body += static_cast<size_t>(n);
  16563. }
  16564. server_body_bytes = body;
  16565. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16566. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16567. SSL_shutdown(ssl);
  16568. }
  16569. SSL_free(ssl);
  16570. detail::close_socket(cli);
  16571. SSL_CTX_free(ctx);
  16572. });
  16573. auto se = detail::scope_exit([&] {
  16574. server_thread.join();
  16575. detail::close_socket(srv);
  16576. });
  16577. SSLClient cli("127.0.0.1", port);
  16578. cli.enable_server_certificate_verification(false);
  16579. cli.set_connection_timeout(5, 0);
  16580. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16581. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16582. std::string body(4096, 'A');
  16583. auto res = cli.Put("/api/test", body, "application/json");
  16584. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16585. EXPECT_EQ(StatusCode::OK_200, res->status);
  16586. EXPECT_EQ(body.size(), server_body_bytes.load());
  16587. }
  16588. #endif
  16589. template <typename S, typename C>
  16590. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16591. svr.Get("/stream", [&](const Request &, Response &res) {
  16592. auto data = new std::string("01234567890123456789");
  16593. res.set_content_provider(
  16594. data->size(), "text/plain",
  16595. [&, data](size_t offset, size_t length, DataSink &sink) {
  16596. const size_t DATA_CHUNK_SIZE = 4;
  16597. const auto &d = *data;
  16598. std::this_thread::sleep_for(std::chrono::seconds(1));
  16599. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16600. return true;
  16601. },
  16602. [data](bool success) {
  16603. EXPECT_FALSE(success);
  16604. delete data;
  16605. });
  16606. });
  16607. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16608. auto i = new size_t(0);
  16609. res.set_content_provider(
  16610. "text/plain",
  16611. [i](size_t, DataSink &sink) {
  16612. if (*i < 5) {
  16613. std::this_thread::sleep_for(std::chrono::seconds(1));
  16614. sink.write("abcd", 4);
  16615. (*i)++;
  16616. } else {
  16617. sink.done();
  16618. }
  16619. return true;
  16620. },
  16621. [i](bool success) {
  16622. EXPECT_FALSE(success);
  16623. delete i;
  16624. });
  16625. });
  16626. svr.Get("/chunked", [&](const Request &, Response &res) {
  16627. auto i = new size_t(0);
  16628. res.set_chunked_content_provider(
  16629. "text/plain",
  16630. [i](size_t, DataSink &sink) {
  16631. if (*i < 5) {
  16632. std::this_thread::sleep_for(std::chrono::seconds(1));
  16633. sink.os << "abcd";
  16634. (*i)++;
  16635. } else {
  16636. sink.done();
  16637. }
  16638. return true;
  16639. },
  16640. [i](bool success) {
  16641. EXPECT_FALSE(success);
  16642. delete i;
  16643. });
  16644. });
  16645. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16646. auto se = detail::scope_exit([&] {
  16647. svr.stop();
  16648. listen_thread.join();
  16649. ASSERT_FALSE(svr.is_running());
  16650. });
  16651. svr.wait_until_ready();
  16652. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16653. {
  16654. auto start = std::chrono::steady_clock::now();
  16655. auto res = cli.Get("/stream");
  16656. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16657. std::chrono::steady_clock::now() - start)
  16658. .count();
  16659. ASSERT_FALSE(res);
  16660. EXPECT_EQ(Error::Read, res.error());
  16661. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16662. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16663. }
  16664. {
  16665. auto start = std::chrono::steady_clock::now();
  16666. auto res = cli.Get("/stream_without_length");
  16667. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16668. std::chrono::steady_clock::now() - start)
  16669. .count();
  16670. ASSERT_FALSE(res);
  16671. EXPECT_EQ(Error::Read, res.error());
  16672. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16673. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16674. }
  16675. {
  16676. auto start = std::chrono::steady_clock::now();
  16677. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16678. EXPECT_EQ("abcd", string(data, data_length));
  16679. return true;
  16680. });
  16681. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16682. std::chrono::steady_clock::now() - start)
  16683. .count();
  16684. ASSERT_FALSE(res);
  16685. EXPECT_EQ(Error::Read, res.error());
  16686. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16687. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16688. }
  16689. }
  16690. TEST(MaxTimeoutTest, ContentStream) {
  16691. time_t timeout = 2000;
  16692. time_t threshold = 200;
  16693. Server svr;
  16694. Client cli("localhost", PORT);
  16695. max_timeout_test(svr, cli, timeout, threshold);
  16696. }
  16697. #ifdef CPPHTTPLIB_SSL_ENABLED
  16698. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16699. time_t timeout = 2000;
  16700. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16702. SSLClient cli("localhost", PORT);
  16703. cli.enable_server_certificate_verification(false);
  16704. max_timeout_test(svr, cli, timeout, threshold);
  16705. }
  16706. #endif
  16707. class EventDispatcher {
  16708. public:
  16709. EventDispatcher() {}
  16710. bool wait_event(DataSink *sink) {
  16711. unique_lock<mutex> lk(m_);
  16712. int id = id_;
  16713. // Wait with timeout to prevent hanging if client disconnects
  16714. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16715. [&] { return cid_ == id; })) {
  16716. return false; // Timeout occurred
  16717. }
  16718. sink->write(message_.data(), message_.size());
  16719. return true;
  16720. }
  16721. void send_event(const string &message) {
  16722. lock_guard<mutex> lk(m_);
  16723. cid_ = id_++;
  16724. message_ = message;
  16725. cv_.notify_all();
  16726. }
  16727. private:
  16728. mutex m_;
  16729. condition_variable cv_;
  16730. atomic_int id_{0};
  16731. atomic_int cid_{-1};
  16732. string message_;
  16733. };
  16734. TEST(ClientInThreadTest, Issue2068) {
  16735. EventDispatcher ed;
  16736. Server svr;
  16737. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16738. res.set_chunked_content_provider("text/event-stream",
  16739. [&](size_t /*offset*/, DataSink &sink) {
  16740. return ed.wait_event(&sink);
  16741. });
  16742. });
  16743. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16744. svr.wait_until_ready();
  16745. thread event_thread([&] {
  16746. int id = 0;
  16747. while (svr.is_running()) {
  16748. this_thread::sleep_for(chrono::milliseconds(500));
  16749. std::stringstream ss;
  16750. ss << "data: " << id << "\n\n";
  16751. ed.send_event(ss.str());
  16752. id++;
  16753. }
  16754. });
  16755. auto se = detail::scope_exit([&] {
  16756. svr.stop();
  16757. listen_thread.join();
  16758. event_thread.join();
  16759. ASSERT_FALSE(svr.is_running());
  16760. });
  16761. {
  16762. auto client = detail::make_unique<Client>(HOST, PORT);
  16763. client->set_read_timeout(std::chrono::minutes(10));
  16764. std::atomic<bool> stop{false};
  16765. std::thread t([&] {
  16766. client->Get("/event1",
  16767. [&](const char *, size_t) -> bool { return !stop; });
  16768. });
  16769. std::this_thread::sleep_for(std::chrono::seconds(2));
  16770. stop = true;
  16771. client->stop();
  16772. t.join();
  16773. // Reset client after thread has finished
  16774. client.reset();
  16775. }
  16776. }
  16777. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16778. auto handled = false;
  16779. Server svr;
  16780. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16781. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16782. auto se = detail::scope_exit([&] {
  16783. svr.stop();
  16784. t.join();
  16785. ASSERT_FALSE(svr.is_running());
  16786. ASSERT_FALSE(handled);
  16787. });
  16788. svr.wait_until_ready();
  16789. // Two Content-Length headers with different values — must be rejected
  16790. auto req = "POST /test HTTP/1.1\r\n"
  16791. "Content-Length: 5\r\n"
  16792. "Content-Length: 10\r\n"
  16793. "\r\n"
  16794. "hello";
  16795. std::string response;
  16796. ASSERT_TRUE(send_request(1, req, &response));
  16797. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16798. response.substr(0, response.find("\r\n")));
  16799. }
  16800. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16801. auto handled = false;
  16802. Server svr;
  16803. svr.Post("/test", [&](const Request &, Response &res) {
  16804. handled = true;
  16805. res.set_content("ok", "text/plain");
  16806. });
  16807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16808. auto se = detail::scope_exit([&] {
  16809. svr.stop();
  16810. t.join();
  16811. ASSERT_FALSE(svr.is_running());
  16812. ASSERT_TRUE(handled);
  16813. });
  16814. svr.wait_until_ready();
  16815. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16816. auto req = "POST /test HTTP/1.1\r\n"
  16817. "Content-Length: 5\r\n"
  16818. "Content-Length: 5\r\n"
  16819. "\r\n"
  16820. "hello";
  16821. std::string response;
  16822. ASSERT_TRUE(send_request(1, req, &response));
  16823. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16824. }
  16825. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16826. Server svr;
  16827. svr.Get("/test", [](const Request &, Response &res) {
  16828. res.set_content("ok", "text/plain");
  16829. });
  16830. auto port = svr.bind_to_any_port(HOST);
  16831. thread t = thread([&] { svr.listen_after_bind(); });
  16832. auto se = detail::scope_exit([&] {
  16833. svr.stop();
  16834. t.join();
  16835. ASSERT_FALSE(svr.is_running());
  16836. });
  16837. svr.wait_until_ready();
  16838. auto status_line = [&](const std::string &host_lines) {
  16839. std::string res;
  16840. send_request(
  16841. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16842. &res, port);
  16843. return res.substr(0, res.find("\r\n"));
  16844. };
  16845. const char *accepted[] = {
  16846. "Host: localhost\r\n",
  16847. "Host: a.example:8080\r\n",
  16848. "Host: my_service\r\n",
  16849. "Host: [::1]:8080\r\n",
  16850. "Host: [fe80::1%25eth0]\r\n",
  16851. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16852. };
  16853. for (auto host_lines : accepted) {
  16854. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16855. }
  16856. const char *rejected[] = {
  16857. "Host: a.example\r\nHost: b.example\r\n",
  16858. "Host: a.example\r\nHost: a.example\r\n",
  16859. "Host: a@b.example\r\n",
  16860. "Host: a.example/b\r\n",
  16861. "Host: a.example\\b\r\n",
  16862. "Host: a.example?b\r\n",
  16863. "Host: a.example#b\r\n",
  16864. "Host: a.example b.example\r\n",
  16865. };
  16866. for (auto host_lines : rejected) {
  16867. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16868. << host_lines;
  16869. }
  16870. }
  16871. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16872. Server svr;
  16873. svr.Get("/", [](const Request &req, Response &res) {
  16874. EXPECT_EQ(2U, req.trailers.size());
  16875. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16876. // Denied
  16877. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16878. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16879. // Accepted
  16880. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16881. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16882. EXPECT_TRUE(req.has_trailer("X-World"));
  16883. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16884. res.set_content("ok", "text/plain");
  16885. });
  16886. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16887. auto se = detail::scope_exit([&] {
  16888. svr.stop();
  16889. t.join();
  16890. ASSERT_FALSE(svr.is_running());
  16891. });
  16892. svr.wait_until_ready();
  16893. const std::string req = "GET / HTTP/1.1\r\n"
  16894. "Transfer-Encoding: chunked\r\n"
  16895. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16896. "\r\n"
  16897. "0\r\n"
  16898. "Content-Length: 10\r\n"
  16899. "Host: internal.local\r\n"
  16900. "Content-Type: malicious/content\r\n"
  16901. "Cookie: any\r\n"
  16902. "Set-Cookie: any\r\n"
  16903. "X-Forwarded-For: attacker.com\r\n"
  16904. "X-Real-Ip: 1.1.1.1\r\n"
  16905. "X-Hello: hello\r\n"
  16906. "X-World: world\r\n"
  16907. "\r\n";
  16908. std::string res;
  16909. ASSERT_TRUE(send_request(1, req, &res));
  16910. }
  16911. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16912. // several field lines, and the combined value is what has to be parsed. A
  16913. // Trailer field split across lines therefore declares every name it lists;
  16914. // reading only the first line silently drops the trailers the later lines
  16915. // declare. The prohibited-trailer filter still applies to every line.
  16916. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16917. Server svr;
  16918. size_t observed_trailer_count = 0;
  16919. std::string observed_hello;
  16920. std::string observed_world;
  16921. bool observed_content_length = true;
  16922. svr.Get("/", [&](const Request &req, Response &res) {
  16923. observed_trailer_count = req.trailers.size();
  16924. observed_hello = req.get_trailer_value("X-Hello");
  16925. observed_world = req.get_trailer_value("X-World");
  16926. observed_content_length = req.has_trailer("Content-Length");
  16927. res.set_content("ok", "text/plain");
  16928. });
  16929. auto port = svr.bind_to_any_port(HOST);
  16930. thread t = thread([&]() { svr.listen_after_bind(); });
  16931. auto se = detail::scope_exit([&] {
  16932. svr.stop();
  16933. t.join();
  16934. ASSERT_FALSE(svr.is_running());
  16935. });
  16936. svr.wait_until_ready();
  16937. const std::string req = "GET / HTTP/1.1\r\n"
  16938. "Transfer-Encoding: chunked\r\n"
  16939. "Trailer: X-Hello\r\n"
  16940. "Trailer: X-World, Content-Length\r\n"
  16941. "\r\n"
  16942. "0\r\n"
  16943. "X-Hello: hello\r\n"
  16944. "X-World: world\r\n"
  16945. "Content-Length: 10\r\n"
  16946. "\r\n";
  16947. std::string res;
  16948. ASSERT_TRUE(send_request(1, req, &res, port));
  16949. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16950. // Accepted: both field lines contribute to the declared set
  16951. EXPECT_EQ(2U, observed_trailer_count);
  16952. EXPECT_EQ(observed_hello, "hello");
  16953. EXPECT_EQ(observed_world, "world");
  16954. // Denied: a prohibited name stays prohibited on a later field line
  16955. EXPECT_FALSE(observed_content_length);
  16956. }
  16957. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16958. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16959. // unbounded run of fields that are never declared, because the counter would
  16960. // only advance for declared fields.
  16961. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16962. Server svr;
  16963. bool handler_called = false;
  16964. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16965. handler_called = true;
  16966. res.set_content("ok", "text/plain");
  16967. });
  16968. auto port = svr.bind_to_any_port(HOST);
  16969. thread t = thread([&]() { svr.listen_after_bind(); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. t.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. });
  16975. svr.wait_until_ready();
  16976. // Declare nothing, then send far more undeclared trailer fields than the
  16977. // header-count limit. Parsing must stop and reject the request rather than
  16978. // read every line.
  16979. std::string req = "GET / HTTP/1.1\r\n"
  16980. "Transfer-Encoding: chunked\r\n"
  16981. "\r\n"
  16982. "0\r\n";
  16983. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16984. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16985. }
  16986. req += "\r\n";
  16987. std::string res;
  16988. ASSERT_TRUE(send_request(1, req, &res, port));
  16989. // The request is rejected before the handler runs.
  16990. EXPECT_FALSE(handler_called);
  16991. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16992. }
  16993. // The set of declared trailer names is capped so a peer cannot grow it without
  16994. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16995. // declared past the cap is not honored, even if the field is actually sent.
  16996. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16997. Server svr;
  16998. // One name inside the cap and one past it, so the test tracks the cap rather
  16999. // than a fixed count.
  17000. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17001. const std::string within_cap_name = "X-T-0";
  17002. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17003. bool observed_within_cap = false;
  17004. bool observed_past_cap = false;
  17005. svr.Get("/", [&](const Request &req, Response &res) {
  17006. observed_within_cap = req.has_trailer(within_cap_name);
  17007. observed_past_cap = req.has_trailer(past_cap_name);
  17008. res.set_content("ok", "text/plain");
  17009. });
  17010. auto port = svr.bind_to_any_port(HOST);
  17011. thread t = thread([&]() { svr.listen_after_bind(); });
  17012. auto se = detail::scope_exit([&] {
  17013. svr.stop();
  17014. t.join();
  17015. ASSERT_FALSE(svr.is_running());
  17016. });
  17017. svr.wait_until_ready();
  17018. // Declare more trailer names than the cap in a single Trailer field, then
  17019. // actually send the first (within the cap) and the last (past it).
  17020. std::string trailer_decl = "Trailer: ";
  17021. for (int i = 0; i < declared_count; i++) {
  17022. if (i != 0) { trailer_decl += ", "; }
  17023. trailer_decl += "X-T-" + std::to_string(i);
  17024. }
  17025. trailer_decl += "\r\n";
  17026. const std::string req = "GET / HTTP/1.1\r\n"
  17027. "Transfer-Encoding: chunked\r\n" +
  17028. trailer_decl +
  17029. "\r\n"
  17030. "0\r\n" +
  17031. within_cap_name + ": a\r\n" + past_cap_name +
  17032. ": b\r\n"
  17033. "\r\n";
  17034. std::string res;
  17035. ASSERT_TRUE(send_request(1, req, &res, port));
  17036. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17037. // A name within the cap is honored; one declared past the cap is dropped.
  17038. EXPECT_TRUE(observed_within_cap);
  17039. EXPECT_FALSE(observed_past_cap);
  17040. }
  17041. // A direct client that is not listed in trusted_proxies must not be able to
  17042. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17043. // the peer address on the actual TCP connection determines whether the
  17044. // header is honored.
  17045. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17046. Server svr;
  17047. // Deliberately does NOT include the loopback address the test client
  17048. // actually connects from, so the direct connection is not a trusted proxy.
  17049. svr.set_trusted_proxies({"203.0.113.66"});
  17050. std::string observed_remote_addr;
  17051. svr.Get("/ip", [&](const Request &req, Response &res) {
  17052. observed_remote_addr = req.remote_addr;
  17053. res.set_content("ok", "text/plain");
  17054. });
  17055. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17056. auto se = detail::scope_exit([&] {
  17057. svr.stop();
  17058. t.join();
  17059. ASSERT_FALSE(svr.is_running());
  17060. });
  17061. svr.wait_until_ready();
  17062. Client cli(HOST, PORT);
  17063. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17065. EXPECT_EQ(StatusCode::OK_200, res->status);
  17066. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17067. // ignored entirely and the real connection-level address retained.
  17068. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17069. observed_remote_addr == "127.0.0.1");
  17070. }
  17071. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17072. Server svr;
  17073. std::string observed_remote_addr;
  17074. std::string observed_xff;
  17075. svr.Get("/ip", [&](const Request &req, Response &res) {
  17076. observed_remote_addr = req.remote_addr;
  17077. observed_xff = req.get_header_value("X-Forwarded-For");
  17078. res.set_content("ok", "text/plain");
  17079. });
  17080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17081. auto se = detail::scope_exit([&] {
  17082. svr.stop();
  17083. t.join();
  17084. ASSERT_FALSE(svr.is_running());
  17085. });
  17086. svr.wait_until_ready();
  17087. Client cli(HOST, PORT);
  17088. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17090. EXPECT_EQ(StatusCode::OK_200, res->status);
  17091. EXPECT_EQ(observed_xff, "203.0.113.66");
  17092. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17093. observed_remote_addr == "127.0.0.1");
  17094. }
  17095. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17096. Server svr;
  17097. svr.set_trusted_proxies({"203.0.113.66"});
  17098. std::string observed_remote_addr;
  17099. std::string observed_xff;
  17100. svr.Get("/ip", [&](const Request &req, Response &res) {
  17101. observed_remote_addr = req.remote_addr;
  17102. observed_xff = req.get_header_value("X-Forwarded-For");
  17103. res.set_content("ok", "text/plain");
  17104. });
  17105. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17106. auto se = detail::scope_exit([&] {
  17107. svr.stop();
  17108. t.join();
  17109. ASSERT_FALSE(svr.is_running());
  17110. });
  17111. svr.wait_until_ready();
  17112. Client cli(HOST, PORT);
  17113. auto res = cli.Get("/ip");
  17114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17115. EXPECT_EQ(StatusCode::OK_200, res->status);
  17116. EXPECT_EQ(observed_xff, "");
  17117. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17118. observed_remote_addr == "127.0.0.1");
  17119. }
  17120. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17121. Server svr;
  17122. // Include the loopback address the test client actually connects from, so
  17123. // the direct connection itself is recognized as the trusted proxy hop.
  17124. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17125. std::string observed_remote_addr;
  17126. std::string observed_xff;
  17127. svr.Get("/ip", [&](const Request &req, Response &res) {
  17128. observed_remote_addr = req.remote_addr;
  17129. observed_xff = req.get_header_value("X-Forwarded-For");
  17130. res.set_content("ok", "text/plain");
  17131. });
  17132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. t.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. });
  17138. svr.wait_until_ready();
  17139. Client cli(HOST, PORT);
  17140. auto res = cli.Get(
  17141. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17143. EXPECT_EQ(StatusCode::OK_200, res->status);
  17144. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17145. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17146. }
  17147. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17148. Server svr;
  17149. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17150. std::string observed_remote_addr;
  17151. std::string observed_xff;
  17152. svr.Get("/ip", [&](const Request &req, Response &res) {
  17153. observed_remote_addr = req.remote_addr;
  17154. observed_xff = req.get_header_value("X-Forwarded-For");
  17155. res.set_content("ok", "text/plain");
  17156. });
  17157. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17158. auto se = detail::scope_exit([&] {
  17159. svr.stop();
  17160. t.join();
  17161. ASSERT_FALSE(svr.is_running());
  17162. });
  17163. svr.wait_until_ready();
  17164. Client cli(HOST, PORT);
  17165. auto res = cli.Get(
  17166. "/ip",
  17167. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17169. EXPECT_EQ(StatusCode::OK_200, res->status);
  17170. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17171. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17172. }
  17173. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17174. Server svr;
  17175. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17176. std::string observed_remote_addr;
  17177. std::string observed_xff;
  17178. svr.Get("/ip", [&](const Request &req, Response &res) {
  17179. observed_remote_addr = req.remote_addr;
  17180. observed_xff = req.get_header_value("X-Forwarded-For");
  17181. res.set_content("ok", "text/plain");
  17182. });
  17183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17184. auto se = detail::scope_exit([&] {
  17185. svr.stop();
  17186. t.join();
  17187. ASSERT_FALSE(svr.is_running());
  17188. });
  17189. svr.wait_until_ready();
  17190. Client cli(HOST, PORT);
  17191. auto res = cli.Get(
  17192. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17194. EXPECT_EQ(StatusCode::OK_200, res->status);
  17195. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17196. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17197. // and must not be selected.
  17198. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17199. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17200. }
  17201. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17202. Server svr;
  17203. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17204. std::string observed_remote_addr;
  17205. svr.Get("/ip", [&](const Request &req, Response &res) {
  17206. observed_remote_addr = req.remote_addr;
  17207. res.set_content("ok", "text/plain");
  17208. });
  17209. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17210. auto se = detail::scope_exit([&] {
  17211. svr.stop();
  17212. t.join();
  17213. ASSERT_FALSE(svr.is_running());
  17214. });
  17215. svr.wait_until_ready();
  17216. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17217. // a forged address and the trusted proxy's own address; the forged value must
  17218. // not win over the address the trusted proxy actually recorded.
  17219. Client cli(HOST, PORT);
  17220. auto res = cli.Get(
  17221. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17223. EXPECT_EQ(StatusCode::OK_200, res->status);
  17224. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17225. }
  17226. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17227. Server svr;
  17228. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17229. std::string observed_remote_addr;
  17230. std::string observed_xff;
  17231. svr.Get("/ip", [&](const Request &req, Response &res) {
  17232. observed_remote_addr = req.remote_addr;
  17233. observed_xff = req.get_header_value("X-Forwarded-For");
  17234. res.set_content("ok", "text/plain");
  17235. });
  17236. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17237. auto se = detail::scope_exit([&] {
  17238. svr.stop();
  17239. t.join();
  17240. ASSERT_FALSE(svr.is_running());
  17241. });
  17242. svr.wait_until_ready();
  17243. Client cli(HOST, PORT);
  17244. auto res = cli.Get(
  17245. "/ip",
  17246. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17248. EXPECT_EQ(StatusCode::OK_200, res->status);
  17249. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17250. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17251. }
  17252. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17253. Server svr;
  17254. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17255. std::string observed_remote_addr;
  17256. std::string observed_xff;
  17257. svr.Get("/ip", [&](const Request &req, Response &res) {
  17258. observed_remote_addr = req.remote_addr;
  17259. observed_xff = req.get_header_value("X-Forwarded-For");
  17260. res.set_content("ok", "text/plain");
  17261. });
  17262. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17263. auto se = detail::scope_exit([&] {
  17264. svr.stop();
  17265. t.join();
  17266. ASSERT_FALSE(svr.is_running());
  17267. });
  17268. svr.wait_until_ready();
  17269. std::string raw_req =
  17270. "GET /ip HTTP/1.1\r\n"
  17271. "Host: localhost\r\n"
  17272. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17273. "Connection: close\r\n"
  17274. "\r\n";
  17275. std::string out;
  17276. ASSERT_TRUE(send_request(5, raw_req, &out));
  17277. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17278. // Header parser trims surrounding whitespace of the header value
  17279. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17280. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17281. }
  17282. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17283. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17284. // their own X-Forwarded-For as a separate field line rather than extending the
  17285. // one the client sent, so every occurrence has to be taken into account.
  17286. // Reading only the first one hands back the address the client chose.
  17287. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17288. Server svr;
  17289. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17290. std::string observed_remote_addr;
  17291. size_t observed_xff_count = 0;
  17292. svr.Get("/ip", [&](const Request &req, Response &res) {
  17293. observed_remote_addr = req.remote_addr;
  17294. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17295. res.set_content("ok", "text/plain");
  17296. });
  17297. auto port = svr.bind_to_any_port(HOST);
  17298. thread t = thread([&]() { svr.listen_after_bind(); });
  17299. auto se = detail::scope_exit([&] {
  17300. svr.stop();
  17301. t.join();
  17302. ASSERT_FALSE(svr.is_running());
  17303. });
  17304. svr.wait_until_ready();
  17305. // The client supplies the first field line; the trusted proxy appends the
  17306. // address it observed as a second one.
  17307. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17308. "Host: localhost\r\n"
  17309. "X-Forwarded-For: 1.2.3.4\r\n"
  17310. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17311. "Connection: close\r\n"
  17312. "\r\n";
  17313. std::string out;
  17314. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17315. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17316. EXPECT_EQ(observed_xff_count, 2U);
  17317. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17318. // The same chain spread over one field line per hop derives the same client
  17319. // address, i.e. the split and the comma-joined representations agree.
  17320. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17321. "Host: localhost\r\n"
  17322. "X-Forwarded-For: 1.2.3.4\r\n"
  17323. "X-Forwarded-For: 198.51.100.23\r\n"
  17324. "X-Forwarded-For: 192.0.2.45\r\n"
  17325. "Connection: close\r\n"
  17326. "\r\n";
  17327. out.clear();
  17328. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17329. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17330. EXPECT_EQ(observed_xff_count, 3U);
  17331. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17332. }
  17333. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17334. // crash the server (it used to call front() on an empty vector inside
  17335. // get_client_ip). The connection-level remote address must be retained instead.
  17336. static void run_malformed_xff_test(const std::string &xff_value) {
  17337. Server svr;
  17338. svr.set_trusted_proxies({"192.0.2.45"});
  17339. std::string observed_remote_addr;
  17340. svr.Get("/ip", [&](const Request &req, Response &res) {
  17341. observed_remote_addr = req.remote_addr;
  17342. res.set_content("ok", "text/plain");
  17343. });
  17344. int port = 0;
  17345. thread t = thread([&]() {
  17346. port = svr.bind_to_any_port(HOST);
  17347. svr.listen_after_bind();
  17348. });
  17349. auto se = detail::scope_exit([&] {
  17350. svr.stop();
  17351. t.join();
  17352. ASSERT_FALSE(svr.is_running());
  17353. });
  17354. svr.wait_until_ready();
  17355. Client cli(HOST, port);
  17356. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17358. EXPECT_EQ(StatusCode::OK_200, res->status);
  17359. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17360. observed_remote_addr == "127.0.0.1");
  17361. }
  17362. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17363. run_malformed_xff_test("");
  17364. }
  17365. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17366. run_malformed_xff_test(",");
  17367. }
  17368. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17369. run_malformed_xff_test(", , ,");
  17370. }
  17371. // The same rule applies to Accept: a request whose acceptable types are spread
  17372. // over several field lines must be negotiated against all of them.
  17373. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17374. // case-insensitive connection options. Comparing the whole field value against
  17375. // one option misses a client that sends several of them, and misses every
  17376. // casing but the one written in the comparison.
  17377. //
  17378. // Sends req, reads the response, then reuses the same socket for a second
  17379. // request to find out whether the server kept the connection.
  17380. static void probe_connection_reuse(int port, const std::string &req,
  17381. bool *announced_close, bool *reusable) {
  17382. auto error = Error::Success;
  17383. auto sock = detail::create_client_socket(
  17384. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17385. /*connection_timeout_sec=*/5, 0,
  17386. /*read_timeout_sec=*/1, 0,
  17387. /*write_timeout_sec=*/5, 0, std::string(), error);
  17388. ASSERT_NE(sock, INVALID_SOCKET);
  17389. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17390. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17391. "Host: localhost\r\n"
  17392. "Connection: close\r\n"
  17393. "\r\n";
  17394. std::string first_response;
  17395. std::string second_response;
  17396. detail::process_client_socket(
  17397. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17398. [&](Stream &strm) {
  17399. if (strm.write(req.data(), req.size()) !=
  17400. static_cast<ssize_t>(req.size())) {
  17401. return false;
  17402. }
  17403. char buf[512];
  17404. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17405. // Headers plus the two-byte body of the handler below
  17406. while (reader.getline()) {
  17407. first_response += reader.ptr();
  17408. if (first_response.find("ok") != std::string::npos) { break; }
  17409. }
  17410. if (strm.write(second.data(), second.size()) !=
  17411. static_cast<ssize_t>(second.size())) {
  17412. return true;
  17413. }
  17414. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17415. while (reader2.getline()) {
  17416. second_response += reader2.ptr();
  17417. if (second_response.find("ok") != std::string::npos) { break; }
  17418. }
  17419. return true;
  17420. });
  17421. *announced_close =
  17422. first_response.find("Connection: close") != std::string::npos;
  17423. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17424. }
  17425. class ConnectionTokenTest : public ::testing::Test {
  17426. protected:
  17427. void SetUp() override {
  17428. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17429. res.set_content("ok", "text/plain");
  17430. });
  17431. port_ = svr_.bind_to_any_port(HOST);
  17432. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17433. svr_.wait_until_ready();
  17434. }
  17435. void TearDown() override {
  17436. svr_.stop();
  17437. if (thread_.joinable()) { thread_.join(); }
  17438. }
  17439. Server svr_;
  17440. int port_ = 0;
  17441. thread thread_;
  17442. };
  17443. // "close" alongside another option still closes the connection, and the
  17444. // response says so rather than leaving the peer to discover it.
  17445. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17446. bool announced_close = false;
  17447. bool reusable = true;
  17448. probe_connection_reuse(port_,
  17449. "GET /keepalive HTTP/1.1\r\n"
  17450. "Host: localhost\r\n"
  17451. "Connection: keep-alive, close\r\n"
  17452. "\r\n",
  17453. &announced_close, &reusable);
  17454. EXPECT_TRUE(announced_close);
  17455. EXPECT_FALSE(reusable);
  17456. }
  17457. // "close" split over two field lines is the same list, so it is honored too.
  17458. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17459. bool announced_close = false;
  17460. bool reusable = true;
  17461. probe_connection_reuse(port_,
  17462. "GET /keepalive HTTP/1.1\r\n"
  17463. "Host: localhost\r\n"
  17464. "Connection: keep-alive\r\n"
  17465. "Connection: close\r\n"
  17466. "\r\n",
  17467. &announced_close, &reusable);
  17468. EXPECT_TRUE(announced_close);
  17469. EXPECT_FALSE(reusable);
  17470. }
  17471. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17472. // keep-alive in the spelling everyone actually sends keeps its connection.
  17473. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17474. bool announced_close = false;
  17475. bool reusable = false;
  17476. probe_connection_reuse(port_,
  17477. "GET /keepalive HTTP/1.0\r\n"
  17478. "Host: localhost\r\n"
  17479. "Connection: keep-alive\r\n"
  17480. "\r\n",
  17481. &announced_close, &reusable);
  17482. EXPECT_FALSE(announced_close);
  17483. EXPECT_TRUE(reusable);
  17484. }
  17485. // A token the value merely contains is not the token itself.
  17486. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17487. bool announced_close = false;
  17488. bool reusable = false;
  17489. probe_connection_reuse(port_,
  17490. "GET /keepalive HTTP/1.1\r\n"
  17491. "Host: localhost\r\n"
  17492. "Connection: notclose\r\n"
  17493. "\r\n",
  17494. &announced_close, &reusable);
  17495. EXPECT_FALSE(announced_close);
  17496. EXPECT_TRUE(reusable);
  17497. }
  17498. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17499. Server svr;
  17500. std::vector<std::string> observed_types;
  17501. svr.Get("/", [&](const Request &req, Response &res) {
  17502. observed_types = req.accept_content_types;
  17503. res.set_content("ok", "text/plain");
  17504. });
  17505. auto port = svr.bind_to_any_port(HOST);
  17506. thread t = thread([&]() { svr.listen_after_bind(); });
  17507. auto se = detail::scope_exit([&] {
  17508. svr.stop();
  17509. t.join();
  17510. ASSERT_FALSE(svr.is_running());
  17511. });
  17512. svr.wait_until_ready();
  17513. Client cli(HOST, port);
  17514. Headers headers;
  17515. headers.emplace("Accept", "text/plain;q=0.5");
  17516. headers.emplace("Accept", "application/json");
  17517. auto res = cli.Get("/", headers);
  17518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17519. EXPECT_EQ(StatusCode::OK_200, res->status);
  17520. // Sorted by q-value, so the second field line's type comes first
  17521. ASSERT_EQ(2U, observed_types.size());
  17522. EXPECT_EQ("application/json", observed_types[0]);
  17523. EXPECT_EQ("text/plain", observed_types[1]);
  17524. }
  17525. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17526. // empty field line must not contribute a bare comma to the combined value.
  17527. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17528. Server svr;
  17529. std::vector<std::string> observed_types;
  17530. svr.Get("/", [&](const Request &req, Response &res) {
  17531. observed_types = req.accept_content_types;
  17532. res.set_content("ok", "text/plain");
  17533. });
  17534. auto port = svr.bind_to_any_port(HOST);
  17535. thread t = thread([&]() { svr.listen_after_bind(); });
  17536. auto se = detail::scope_exit([&] {
  17537. svr.stop();
  17538. t.join();
  17539. ASSERT_FALSE(svr.is_running());
  17540. });
  17541. svr.wait_until_ready();
  17542. // Empty first field line, then a real one
  17543. std::string raw_req = "GET / HTTP/1.1\r\n"
  17544. "Host: localhost\r\n"
  17545. "Accept:\r\n"
  17546. "Accept: application/json\r\n"
  17547. "Connection: close\r\n"
  17548. "\r\n";
  17549. std::string out;
  17550. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17551. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17552. ASSERT_EQ(1U, observed_types.size());
  17553. EXPECT_EQ("application/json", observed_types[0]);
  17554. }
  17555. // The skip in get_combined_header_value() is what keeps an empty field line
  17556. // from contributing a bare comma. Only a trailing empty field line exercises
  17557. // it: a leading one is already covered by the "combined is still empty" check,
  17558. // and parse_accept_header() now ignores the empty element either way, so the
  17559. // request-level test above can no longer tell the two apart.
  17560. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17561. Headers headers;
  17562. headers.emplace("Accept", "text/html");
  17563. headers.emplace("Accept", "");
  17564. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17565. headers.clear();
  17566. headers.emplace("Accept", "");
  17567. headers.emplace("Accept", "application/json");
  17568. EXPECT_EQ("application/json",
  17569. detail::get_combined_header_value(headers, "Accept"));
  17570. }
  17571. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17572. // An encoding offered on a later Accept-Encoding field line is still offered.
  17573. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17574. Server svr;
  17575. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17576. res.set_content(std::string(1024, 'x'), "text/plain");
  17577. });
  17578. auto port = svr.bind_to_any_port(HOST);
  17579. thread t = thread([&]() { svr.listen_after_bind(); });
  17580. auto se = detail::scope_exit([&] {
  17581. svr.stop();
  17582. t.join();
  17583. ASSERT_FALSE(svr.is_running());
  17584. });
  17585. svr.wait_until_ready();
  17586. Client cli(HOST, port);
  17587. cli.set_decompress(false);
  17588. Headers headers;
  17589. headers.emplace("Accept-Encoding", "identity");
  17590. headers.emplace("Accept-Encoding", "gzip");
  17591. auto res = cli.Get("/", headers);
  17592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17593. EXPECT_EQ(StatusCode::OK_200, res->status);
  17594. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17595. }
  17596. #endif
  17597. #ifndef _WIN32
  17598. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17599. Server svr;
  17600. svr.Post("/post", [&](const Request &req, Response &res) {
  17601. res.set_content(req.body, "text/plain");
  17602. });
  17603. svr.Put("/put", [&](const Request &req, Response &res) {
  17604. res.set_content(req.body, "text/plain");
  17605. });
  17606. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17607. res.set_content(req.body, "text/plain");
  17608. });
  17609. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17610. res.set_content(req.body, "text/plain");
  17611. });
  17612. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17613. auto se = detail::scope_exit([&] {
  17614. svr.stop();
  17615. t.join();
  17616. ASSERT_FALSE(svr.is_running());
  17617. });
  17618. svr.wait_until_ready();
  17619. std::string resp;
  17620. // POST without Content-Length
  17621. ASSERT_TRUE(send_request(5,
  17622. "POST /post HTTP/1.1\r\n"
  17623. "Host: localhost\r\n"
  17624. "Connection: close\r\n"
  17625. "\r\n",
  17626. &resp));
  17627. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17628. // PUT without Content-Length
  17629. resp.clear();
  17630. ASSERT_TRUE(send_request(5,
  17631. "PUT /put HTTP/1.1\r\n"
  17632. "Host: localhost\r\n"
  17633. "Connection: close\r\n"
  17634. "\r\n",
  17635. &resp));
  17636. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17637. // PATCH without Content-Length
  17638. resp.clear();
  17639. ASSERT_TRUE(send_request(5,
  17640. "PATCH /patch HTTP/1.1\r\n"
  17641. "Host: localhost\r\n"
  17642. "Connection: close\r\n"
  17643. "\r\n",
  17644. &resp));
  17645. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17646. // DELETE without Content-Length
  17647. resp.clear();
  17648. ASSERT_TRUE(send_request(5,
  17649. "DELETE /delete HTTP/1.1\r\n"
  17650. "Host: localhost\r\n"
  17651. "Connection: close\r\n"
  17652. "\r\n",
  17653. &resp));
  17654. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17655. }
  17656. #endif
  17657. //==============================================================================
  17658. // open_stream() Tests
  17659. //==============================================================================
  17660. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17661. std::string result;
  17662. char buf[8192];
  17663. ssize_t n;
  17664. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17665. result.append(buf, static_cast<size_t>(n));
  17666. }
  17667. return result;
  17668. }
  17669. // Mock stream for unit tests
  17670. class MockStream : public Stream {
  17671. public:
  17672. std::string data;
  17673. size_t pos = 0;
  17674. ssize_t error_after = -1; // -1 = no error
  17675. explicit MockStream(const std::string &d, ssize_t err = -1)
  17676. : data(d), error_after(err) {}
  17677. bool is_readable() const override { return true; }
  17678. bool wait_readable() const override { return true; }
  17679. bool wait_writable() const override { return true; }
  17680. ssize_t read(char *ptr, size_t size) override {
  17681. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17682. if (pos >= data.size()) return 0;
  17683. size_t limit =
  17684. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17685. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17686. std::memcpy(ptr, data.data() + pos, to_read);
  17687. pos += to_read;
  17688. return static_cast<ssize_t>(to_read);
  17689. }
  17690. ssize_t write(const char *, size_t) override { return -1; }
  17691. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17692. ip = "127.0.0.1";
  17693. port = 0;
  17694. }
  17695. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17696. ip = "127.0.0.1";
  17697. port = 0;
  17698. }
  17699. socket_t socket() const override { return INVALID_SOCKET; }
  17700. time_t duration() const override { return 0; }
  17701. };
  17702. TEST(StreamHandleTest, Basic) {
  17703. ClientImpl::StreamHandle handle;
  17704. EXPECT_FALSE(handle.is_valid());
  17705. handle.response = detail::make_unique<Response>();
  17706. handle.error = Error::Connection;
  17707. EXPECT_FALSE(handle.is_valid());
  17708. handle.error = Error::Success;
  17709. EXPECT_TRUE(handle.is_valid());
  17710. }
  17711. TEST(BodyReaderTest, Basic) {
  17712. MockStream stream("Hello, World!");
  17713. detail::BodyReader reader;
  17714. reader.stream = &stream;
  17715. reader.content_length = 13;
  17716. char buf[32];
  17717. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17718. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17719. EXPECT_TRUE(reader.eof);
  17720. }
  17721. TEST(BodyReaderTest, NoStream) {
  17722. detail::BodyReader reader;
  17723. char buf[32];
  17724. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17725. EXPECT_EQ(Error::Connection, reader.last_error);
  17726. }
  17727. TEST(BodyReaderTest, Error) {
  17728. MockStream stream("Hello, World!", 5);
  17729. detail::BodyReader reader;
  17730. reader.stream = &stream;
  17731. reader.content_length = 13;
  17732. char buf[32];
  17733. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17734. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17735. EXPECT_EQ(Error::Read, reader.last_error);
  17736. }
  17737. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17738. // Mock-based StreamHandle tests relying on private internals are removed.
  17739. class OpenStreamTest : public ::testing::Test {
  17740. protected:
  17741. void SetUp() override {
  17742. svr_.Get("/hello", [](const Request &, Response &res) {
  17743. res.set_content("Hello World!", "text/plain");
  17744. });
  17745. svr_.Get("/large", [](const Request &, Response &res) {
  17746. res.set_content(std::string(10000, 'X'), "text/plain");
  17747. });
  17748. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17749. res.set_content("Hello World!", "image/jpeg");
  17750. res.set_header("Content-Encoding", "UTF-8");
  17751. });
  17752. svr_.Get("/chunked", [](const Request &, Response &res) {
  17753. res.set_chunked_content_provider("text/plain",
  17754. [](size_t offset, DataSink &sink) {
  17755. if (offset < 15) {
  17756. sink.write("chunk", 5);
  17757. return true;
  17758. }
  17759. sink.done();
  17760. return true;
  17761. });
  17762. });
  17763. svr_.Get("/compressible", [](const Request &, Response &res) {
  17764. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17765. DataSink &sink) {
  17766. if (offset < 100 * 1024) {
  17767. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17768. sink.write(chunk.data(), chunk.size());
  17769. return true;
  17770. }
  17771. sink.done();
  17772. return true;
  17773. });
  17774. });
  17775. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17776. [](const Request & /*req*/, Response &res) {
  17777. auto i = new int(0);
  17778. res.set_header("Trailer", "Content-Length, X-Allowed");
  17779. res.set_chunked_content_provider(
  17780. "text/plain",
  17781. [i](size_t /*offset*/, DataSink &sink) {
  17782. switch (*i) {
  17783. case 0: sink.os << "123"; break;
  17784. case 1: sink.os << "456"; break;
  17785. case 2: sink.os << "789"; break;
  17786. case 3: {
  17787. sink.done_with_trailer(
  17788. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17789. } break;
  17790. }
  17791. (*i)++;
  17792. return true;
  17793. },
  17794. [i](bool success) {
  17795. EXPECT_TRUE(success);
  17796. delete i;
  17797. });
  17798. });
  17799. // Echo headers endpoint for header-related tests
  17800. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17801. std::string body;
  17802. for (const auto &h : req.headers) {
  17803. body.append(h.first);
  17804. body.push_back(':');
  17805. body.append(h.second);
  17806. body.push_back('\n');
  17807. }
  17808. res.set_content(body, "text/plain");
  17809. });
  17810. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17811. std::string body;
  17812. for (const auto &h : req.headers) {
  17813. body.append(h.first);
  17814. body.push_back(':');
  17815. body.append(h.second);
  17816. body.push_back('\n');
  17817. }
  17818. res.set_content(body, "text/plain");
  17819. });
  17820. port_ = svr_.bind_to_any_port("127.0.0.1");
  17821. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17822. svr_.wait_until_ready();
  17823. }
  17824. void TearDown() override {
  17825. svr_.stop();
  17826. if (thread_.joinable()) thread_.join();
  17827. }
  17828. Server svr_;
  17829. std::thread thread_;
  17830. int port_ = 0;
  17831. };
  17832. TEST_F(OpenStreamTest, Basic) {
  17833. Client cli("127.0.0.1", port_);
  17834. auto handle = cli.open_stream("GET", "/hello");
  17835. EXPECT_TRUE(handle.is_valid());
  17836. EXPECT_EQ("Hello World!", read_all(handle));
  17837. }
  17838. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17839. Client cli("127.0.0.1", port_);
  17840. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17841. ASSERT_TRUE(handle.is_valid());
  17842. EXPECT_EQ("Hello World!", read_all(handle));
  17843. }
  17844. TEST_F(OpenStreamTest, SmallBuffer) {
  17845. Client cli("127.0.0.1", port_);
  17846. auto handle = cli.open_stream("GET", "/hello");
  17847. std::string result;
  17848. char buf[4];
  17849. ssize_t n;
  17850. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17851. result.append(buf, static_cast<size_t>(n));
  17852. EXPECT_EQ("Hello World!", result);
  17853. }
  17854. TEST_F(OpenStreamTest, DefaultHeaders) {
  17855. Client cli("127.0.0.1", port_);
  17856. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17857. {
  17858. auto handle = cli.open_stream("GET", "/echo-headers");
  17859. ASSERT_TRUE(handle.is_valid());
  17860. auto body = read_all(handle);
  17861. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17862. std::string::npos);
  17863. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17864. std::string::npos);
  17865. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17866. }
  17867. // open_stream POST with body and no explicit content_type should NOT add
  17868. // text/plain Content-Type (behavior differs from non-streaming path), but
  17869. // should include Content-Length
  17870. {
  17871. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17872. ASSERT_TRUE(handle.is_valid());
  17873. auto body = read_all(handle);
  17874. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17875. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17876. }
  17877. // open_stream POST with explicit Content-Type should preserve it
  17878. {
  17879. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17880. {{"Content-Type", "application/custom"}},
  17881. "{}", "application/custom");
  17882. ASSERT_TRUE(handle.is_valid());
  17883. auto body = read_all(handle);
  17884. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17885. }
  17886. // User-specified User-Agent must not be overwritten for stream API
  17887. {
  17888. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17889. {{"User-Agent", "MyAgent/1.2"}});
  17890. ASSERT_TRUE(handle.is_valid());
  17891. auto body = read_all(handle);
  17892. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17893. }
  17894. }
  17895. TEST_F(OpenStreamTest, Large) {
  17896. Client cli("127.0.0.1", port_);
  17897. auto handle = cli.open_stream("GET", "/large");
  17898. EXPECT_EQ(10000u, read_all(handle).size());
  17899. }
  17900. TEST_F(OpenStreamTest, ConnectionError) {
  17901. Client cli("127.0.0.1", 9999);
  17902. auto handle = cli.open_stream("GET", "/hello");
  17903. EXPECT_FALSE(handle.is_valid());
  17904. }
  17905. TEST_F(OpenStreamTest, Chunked) {
  17906. Client cli("127.0.0.1", port_);
  17907. auto handle = cli.open_stream("GET", "/chunked");
  17908. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17909. "Transfer-Encoding") == "chunked");
  17910. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17911. }
  17912. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17913. Client cli("127.0.0.1", port_);
  17914. auto handle =
  17915. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17916. ASSERT_TRUE(handle.is_valid());
  17917. // Consume body to allow trailers to be received/parsed
  17918. auto body = read_all(handle);
  17919. // Explicitly parse trailers (ensure trailers are available for assertion)
  17920. handle.parse_trailers_if_needed();
  17921. EXPECT_EQ(std::string("123456789"), body);
  17922. // The response should include a Trailer header declaring both names
  17923. ASSERT_TRUE(handle.response);
  17924. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17925. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17926. handle.response->get_header_value("Trailer"));
  17927. // Prohibited trailer must not be present
  17928. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17929. // Allowed trailer should be present
  17930. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17931. EXPECT_EQ(std::string("yes"),
  17932. handle.response->get_trailer_value("X-Allowed"));
  17933. // Verify trailers are NOT present as regular headers
  17934. EXPECT_EQ(std::string(""),
  17935. handle.response->get_header_value("Content-Length"));
  17936. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17937. }
  17938. static std::thread serve_single_response(std::promise<int> &port_promise,
  17939. const std::string &response) {
  17940. return std::thread([&port_promise, response] {
  17941. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17942. default_socket_options(srv);
  17943. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17944. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17945. sockaddr_in addr{};
  17946. addr.sin_family = AF_INET;
  17947. addr.sin_port = htons(0); // Let OS assign a free port
  17948. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17949. int opt = 1;
  17950. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17951. #ifdef _WIN32
  17952. reinterpret_cast<const char *>(&opt),
  17953. #else
  17954. &opt,
  17955. #endif
  17956. sizeof(opt));
  17957. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17958. ::listen(srv, 1) != 0) {
  17959. port_promise.set_value(-1);
  17960. detail::close_socket(srv);
  17961. return;
  17962. }
  17963. socklen_t addr_len = sizeof(addr);
  17964. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17965. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17966. sockaddr_in cli_addr{};
  17967. socklen_t cli_len = sizeof(cli_addr);
  17968. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17969. if (cli != INVALID_SOCKET) {
  17970. // Read the complete HTTP request (until the blank line that terminates
  17971. // headers) before sending the response. If the server closes the socket
  17972. // while the client's request data is still unread in the kernel receive
  17973. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17974. // connection on both sides: it discards the client's receive buffer
  17975. // (which already holds our response) and causes any in-progress write on
  17976. // the client to fail with ECONNRESET. Reading all request data first
  17977. // ensures close() emits a graceful FIN.
  17978. {
  17979. char rbuf[256];
  17980. std::string req;
  17981. while (req.find("\r\n\r\n") == std::string::npos) {
  17982. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17983. if (n <= 0) { break; }
  17984. req.append(rbuf, static_cast<size_t>(n));
  17985. }
  17986. }
  17987. ::send(cli,
  17988. #ifdef _WIN32
  17989. static_cast<const char *>(response.c_str()),
  17990. static_cast<int>(response.size()),
  17991. #else
  17992. response.c_str(), response.size(),
  17993. #endif
  17994. 0);
  17995. detail::close_socket(cli);
  17996. }
  17997. detail::close_socket(srv);
  17998. });
  17999. }
  18000. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18001. #ifndef _WIN32
  18002. signal(SIGPIPE, SIG_IGN);
  18003. #endif
  18004. std::promise<int> port_promise;
  18005. auto port_future = port_promise.get_future();
  18006. auto server_thread =
  18007. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18008. "Content-Type: text/plain\r\n"
  18009. "Content-Length: not-a-number\r\n"
  18010. "Connection: close\r\n"
  18011. "\r\n"
  18012. "hello");
  18013. auto port = port_future.get();
  18014. ASSERT_GT(port, 0);
  18015. Client cli("127.0.0.1", port);
  18016. auto handle = cli.open_stream("GET", "/");
  18017. EXPECT_FALSE(handle.is_valid());
  18018. server_thread.join();
  18019. }
  18020. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18021. #ifndef _WIN32
  18022. signal(SIGPIPE, SIG_IGN);
  18023. #endif
  18024. std::promise<int> port_promise;
  18025. auto port_future = port_promise.get_future();
  18026. auto server_thread = serve_single_response(
  18027. port_promise, "HTTP/1.1 200 OK\r\n"
  18028. "Content-Type: text/plain\r\n"
  18029. "Content-Length: 99999999999999999999999999\r\n"
  18030. "Connection: close\r\n"
  18031. "\r\n"
  18032. "hello");
  18033. auto port = port_future.get();
  18034. ASSERT_GT(port, 0);
  18035. // Historically std::stoull would throw std::out_of_range here and crash
  18036. // the process, then parsing silently clamped to a bogus framing length and
  18037. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18038. // so the stream fails to open, matching the not-a-number case above. The
  18039. // process still must NOT terminate.
  18040. Client cli("127.0.0.1", port);
  18041. auto handle = cli.open_stream("GET", "/");
  18042. EXPECT_FALSE(handle.is_valid());
  18043. server_thread.join();
  18044. }
  18045. // Serves `response` to the single request `fn` makes with a fresh client.
  18046. template <typename Fn>
  18047. static void with_single_response(const std::string &response, Fn fn) {
  18048. #ifndef _WIN32
  18049. signal(SIGPIPE, SIG_IGN);
  18050. #endif
  18051. std::promise<int> port_promise;
  18052. auto port_future = port_promise.get_future();
  18053. auto server_thread = serve_single_response(port_promise, response);
  18054. auto se = detail::scope_exit([&] { server_thread.join(); });
  18055. auto port = port_future.get();
  18056. ASSERT_GT(port, 0);
  18057. Client cli("127.0.0.1", port);
  18058. fn(cli);
  18059. }
  18060. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18061. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18062. // the chunked coding and drop Content-Length, so a front-end that trusts
  18063. // Content-Length would disagree about where the body ends (response
  18064. // smuggling). The client must reject such a response.
  18065. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18066. for (const char *te : {"chunked", "gzip, chunked"}) {
  18067. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18068. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18069. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18070. "5\r\nhello\r\n0\r\n\r\n";
  18071. with_single_response(response, [&](Client &cli) {
  18072. auto res = cli.Get("/");
  18073. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18074. EXPECT_EQ(Error::Read, res.error()) << te;
  18075. });
  18076. with_single_response(response, [&](Client &cli) {
  18077. auto handle = cli.open_stream("GET", "/");
  18078. EXPECT_FALSE(handle.is_valid()) << te;
  18079. EXPECT_EQ(Error::Read, handle.error) << te;
  18080. });
  18081. }
  18082. }
  18083. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18084. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18085. // closing the connection (unlike a request, which must be rejected).
  18086. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18087. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18088. "Transfer-Encoding: chunked\r\n"
  18089. "Connection: close\r\n"
  18090. "\r\n"
  18091. "5\r\nhello\r\n0\r\n\r\n",
  18092. "HTTP/1.1 200 OK\r\n"
  18093. "Transfer-Encoding: gzip\r\n"
  18094. "Connection: close\r\n"
  18095. "\r\n"
  18096. "hello"}) {
  18097. with_single_response(response, [&](Client &cli) {
  18098. auto res = cli.Get("/");
  18099. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18100. EXPECT_EQ("hello", res->body);
  18101. });
  18102. with_single_response(response, [&](Client &cli) {
  18103. auto handle = cli.open_stream("GET", "/");
  18104. ASSERT_TRUE(handle.is_valid()) << response;
  18105. EXPECT_EQ("hello", read_all(handle));
  18106. });
  18107. }
  18108. }
  18109. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18110. // framing headers describe nothing to read and must not be rejected.
  18111. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18112. const std::string framing = "Content-Length: 5\r\n"
  18113. "Transfer-Encoding: chunked\r\n"
  18114. "Connection: close\r\n"
  18115. "\r\n";
  18116. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18117. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18118. });
  18119. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18120. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18121. });
  18122. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18123. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18124. with_single_response(response, [&](Client &cli) {
  18125. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18126. });
  18127. with_single_response(response, [&](Client &cli) {
  18128. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18129. });
  18130. }
  18131. }
  18132. // A payload max length of 0 means no limit, however the body is framed.
  18133. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18134. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18135. "Transfer-Encoding: chunked\r\n"
  18136. "\r\n"
  18137. "5\r\nhello\r\n0\r\n\r\n",
  18138. "HTTP/1.1 200 OK\r\n"
  18139. "Connection: close\r\n"
  18140. "\r\n"
  18141. "hello"}) {
  18142. with_single_response(response, [&](Client &cli) {
  18143. cli.set_payload_max_length(0);
  18144. auto res = cli.Get("/");
  18145. ASSERT_TRUE(res) << response;
  18146. EXPECT_EQ("hello", res->body) << response;
  18147. });
  18148. }
  18149. }
  18150. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18151. Server svr;
  18152. svr.set_payload_max_length(0);
  18153. svr.Post("/echo", [](const Request &req, Response &res) {
  18154. res.set_content(req.body, "text/plain");
  18155. });
  18156. auto port = svr.bind_to_any_port(HOST);
  18157. thread t = thread([&] { svr.listen_after_bind(); });
  18158. auto se = detail::scope_exit([&] {
  18159. svr.stop();
  18160. t.join();
  18161. ASSERT_FALSE(svr.is_running());
  18162. });
  18163. svr.wait_until_ready();
  18164. Client cli(HOST, port);
  18165. auto res = cli.Post(
  18166. "/echo",
  18167. [](size_t /*offset*/, DataSink &sink) {
  18168. sink.write("hello", 5);
  18169. sink.done();
  18170. return true;
  18171. },
  18172. "text/plain");
  18173. ASSERT_TRUE(res);
  18174. EXPECT_EQ(StatusCode::OK_200, res->status);
  18175. EXPECT_EQ("hello", res->body);
  18176. }
  18177. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18178. TEST_F(OpenStreamTest, Gzip) {
  18179. Client cli("127.0.0.1", port_);
  18180. auto handle = cli.open_stream("GET", "/compressible", {},
  18181. {{"Accept-Encoding", "gzip"}});
  18182. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18183. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18184. }
  18185. #endif
  18186. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18187. TEST_F(OpenStreamTest, Brotli) {
  18188. Client cli("127.0.0.1", port_);
  18189. auto handle =
  18190. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18191. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18192. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18193. }
  18194. #endif
  18195. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18196. TEST_F(OpenStreamTest, Zstd) {
  18197. Client cli("127.0.0.1", port_);
  18198. auto handle = cli.open_stream("GET", "/compressible", {},
  18199. {{"Accept-Encoding", "zstd"}});
  18200. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18201. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18202. }
  18203. #endif
  18204. #ifdef CPPHTTPLIB_SSL_ENABLED
  18205. class SSLOpenStreamTest : public ::testing::Test {
  18206. protected:
  18207. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18208. void SetUp() override {
  18209. svr_.Get("/hello", [](const Request &, Response &res) {
  18210. res.set_content("Hello SSL World!", "text/plain");
  18211. });
  18212. svr_.Get("/chunked", [](const Request &, Response &res) {
  18213. res.set_chunked_content_provider("text/plain",
  18214. [](size_t offset, DataSink &sink) {
  18215. if (offset < 15) {
  18216. sink.write("chunk", 5);
  18217. return true;
  18218. }
  18219. sink.done();
  18220. return true;
  18221. });
  18222. });
  18223. svr_.Post("/echo", [](const Request &req, Response &res) {
  18224. res.set_content(req.body, req.get_header_value("Content-Type"));
  18225. });
  18226. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18227. std::string body = req.body;
  18228. res.set_chunked_content_provider(
  18229. "text/plain", [body](size_t offset, DataSink &sink) {
  18230. if (offset < body.size()) {
  18231. sink.write(body.data() + offset, body.size() - offset);
  18232. }
  18233. sink.done();
  18234. return true;
  18235. });
  18236. });
  18237. port_ = svr_.bind_to_any_port("127.0.0.1");
  18238. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18239. svr_.wait_until_ready();
  18240. }
  18241. void TearDown() override {
  18242. svr_.stop();
  18243. if (thread_.joinable()) thread_.join();
  18244. }
  18245. SSLServer svr_;
  18246. std::thread thread_;
  18247. int port_ = 0;
  18248. };
  18249. TEST_F(SSLOpenStreamTest, Basic) {
  18250. SSLClient cli("127.0.0.1", port_);
  18251. cli.enable_server_certificate_verification(false);
  18252. auto handle = cli.open_stream("GET", "/hello");
  18253. ASSERT_TRUE(handle.is_valid());
  18254. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18255. }
  18256. TEST_F(SSLOpenStreamTest, Chunked) {
  18257. SSLClient cli("127.0.0.1", port_);
  18258. cli.enable_server_certificate_verification(false);
  18259. auto handle = cli.open_stream("GET", "/chunked");
  18260. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18261. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18262. "Transfer-Encoding") == "chunked");
  18263. auto body = read_all(handle);
  18264. EXPECT_EQ("chunkchunkchunk", body);
  18265. }
  18266. TEST_F(SSLOpenStreamTest, Post) {
  18267. SSLClient cli("127.0.0.1", port_);
  18268. cli.enable_server_certificate_verification(false);
  18269. auto handle =
  18270. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18271. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18272. EXPECT_EQ(200, handle.response->status);
  18273. auto body = read_all(handle);
  18274. EXPECT_EQ("Hello SSL POST", body);
  18275. }
  18276. TEST_F(SSLOpenStreamTest, PostChunked) {
  18277. SSLClient cli("127.0.0.1", port_);
  18278. cli.enable_server_certificate_verification(false);
  18279. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18280. "Chunked SSL Data", "text/plain");
  18281. ASSERT_TRUE(handle.is_valid());
  18282. EXPECT_EQ(200, handle.response->status);
  18283. auto body = read_all(handle);
  18284. EXPECT_EQ("Chunked SSL Data", body);
  18285. }
  18286. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18287. // Content-Length is terminated by the server closing the connection. When the
  18288. // SSL peer sends a close_notify after the body, the client must treat it as a
  18289. // clean EOF and return a successful response rather than an error.
  18290. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18291. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18292. ASSERT_TRUE(svr.is_valid());
  18293. svr.set_keep_alive_max_count(1);
  18294. const std::string expected_body = "Hello from connection-close response!";
  18295. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18296. res.set_content_provider("text/plain",
  18297. [&](size_t offset, DataSink &sink) -> bool {
  18298. if (offset < expected_body.size()) {
  18299. sink.write(expected_body.data() + offset,
  18300. expected_body.size() - offset);
  18301. }
  18302. sink.done();
  18303. return true;
  18304. });
  18305. });
  18306. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18307. auto se = detail::scope_exit([&] {
  18308. svr.stop();
  18309. listen_thread.join();
  18310. ASSERT_FALSE(svr.is_running());
  18311. });
  18312. svr.wait_until_ready();
  18313. SSLClient cli(HOST, PORT);
  18314. cli.enable_server_certificate_verification(false);
  18315. auto res = cli.Get("/no-content-length");
  18316. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18317. EXPECT_EQ(StatusCode::OK_200, res->status);
  18318. EXPECT_EQ(expected_body, res->body);
  18319. }
  18320. #endif // CPPHTTPLIB_SSL_ENABLED
  18321. //==============================================================================
  18322. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18323. // results for various scenarios.
  18324. //==============================================================================
  18325. TEST(ParityTest, GetVsOpenStream) {
  18326. Server svr;
  18327. const std::string path = "/parity";
  18328. const std::string content = "Parity test content: hello world";
  18329. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18330. res.set_content(content, "text/plain");
  18331. });
  18332. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18333. auto se = detail::scope_exit([&] {
  18334. svr.stop();
  18335. t.join();
  18336. ASSERT_FALSE(svr.is_running());
  18337. });
  18338. svr.wait_until_ready();
  18339. Client cli(HOST, PORT);
  18340. // Non-stream path
  18341. auto r1 = cli.Get(path);
  18342. ASSERT_TRUE(r1);
  18343. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18344. // Stream path
  18345. auto h = cli.open_stream("GET", path);
  18346. ASSERT_TRUE(h.is_valid());
  18347. EXPECT_EQ(r1->body, read_all(h));
  18348. }
  18349. // Helper to compress data with provided compressor type T
  18350. template <typename Compressor>
  18351. static std::string compress_payload_for_parity(const std::string &in) {
  18352. std::string out;
  18353. Compressor compressor;
  18354. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18355. [&](const char *data, size_t n) {
  18356. out.append(data, n);
  18357. return true;
  18358. });
  18359. EXPECT_TRUE(ok);
  18360. return out;
  18361. }
  18362. // Helper function for compression parity tests
  18363. template <typename Compressor>
  18364. static void test_compression_parity(const std::string &original,
  18365. const std::string &path,
  18366. const std::string &encoding) {
  18367. const std::string compressed =
  18368. compress_payload_for_parity<Compressor>(original);
  18369. Server svr;
  18370. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18371. res.set_content(compressed, "application/octet-stream");
  18372. res.set_header("Content-Encoding", encoding);
  18373. });
  18374. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18375. auto se = detail::scope_exit([&] {
  18376. svr.stop();
  18377. t.join();
  18378. ASSERT_FALSE(svr.is_running());
  18379. });
  18380. svr.wait_until_ready();
  18381. Client cli(HOST, PORT);
  18382. // Non-streaming
  18383. {
  18384. auto res = cli.Get(path);
  18385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18386. EXPECT_EQ(StatusCode::OK_200, res->status);
  18387. EXPECT_EQ(original, res->body);
  18388. }
  18389. // Streaming
  18390. {
  18391. auto h = cli.open_stream("GET", path);
  18392. ASSERT_TRUE(h.is_valid());
  18393. EXPECT_EQ(original, read_all(h));
  18394. }
  18395. }
  18396. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18397. TEST(ParityTest, Gzip) {
  18398. test_compression_parity<detail::gzip_compressor>(
  18399. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18400. }
  18401. #endif
  18402. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18403. TEST(ParityTest, Brotli) {
  18404. test_compression_parity<detail::brotli_compressor>(
  18405. "Hello, brotli parity test payload", "/parity-br", "br");
  18406. }
  18407. #endif
  18408. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18409. TEST(ParityTest, Zstd) {
  18410. test_compression_parity<detail::zstd_compressor>(
  18411. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18412. }
  18413. #endif
  18414. //==============================================================================
  18415. // New Stream API Tests
  18416. //==============================================================================
  18417. inline std::string read_body(httplib::stream::Result &result) {
  18418. std::string body;
  18419. while (result.next()) {
  18420. body.append(result.data(), result.size());
  18421. }
  18422. return body;
  18423. }
  18424. TEST(ClientConnectionTest, Basic) {
  18425. httplib::ClientConnection conn;
  18426. EXPECT_FALSE(conn.is_open());
  18427. conn.sock = 1;
  18428. EXPECT_TRUE(conn.is_open());
  18429. httplib::ClientConnection conn2(std::move(conn));
  18430. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18431. conn2.sock = INVALID_SOCKET;
  18432. }
  18433. // Unified test server for all stream::* tests
  18434. class StreamApiTest : public ::testing::Test {
  18435. protected:
  18436. void SetUp() override {
  18437. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18438. res.set_content("Hello World!", "text/plain");
  18439. });
  18440. svr_.Get("/echo-params",
  18441. [](const httplib::Request &req, httplib::Response &res) {
  18442. std::string r;
  18443. for (const auto &p : req.params) {
  18444. if (!r.empty()) r += "&";
  18445. r += p.first + "=" + p.second;
  18446. }
  18447. res.set_content(r, "text/plain");
  18448. });
  18449. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18450. res.set_content(req.body, req.get_header_value("Content-Type"));
  18451. });
  18452. svr_.Post("/echo-headers",
  18453. [](const httplib::Request &req, httplib::Response &res) {
  18454. std::string r;
  18455. for (const auto &h : req.headers)
  18456. r += h.first + ": " + h.second + "\n";
  18457. res.set_content(r, "text/plain");
  18458. });
  18459. svr_.Post("/echo-params",
  18460. [](const httplib::Request &req, httplib::Response &res) {
  18461. std::string r = "params:";
  18462. for (const auto &p : req.params)
  18463. r += p.first + "=" + p.second + ";";
  18464. res.set_content(r + " body:" + req.body, "text/plain");
  18465. });
  18466. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18467. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18468. });
  18469. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18470. res.set_content("PUT:" + req.body, "text/plain");
  18471. });
  18472. svr_.Patch("/echo",
  18473. [](const httplib::Request &req, httplib::Response &res) {
  18474. res.set_content("PATCH:" + req.body, "text/plain");
  18475. });
  18476. svr_.Delete(
  18477. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18478. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18479. "text/plain");
  18480. });
  18481. svr_.Get("/head-test",
  18482. [](const httplib::Request &, httplib::Response &res) {
  18483. res.set_content("body for HEAD", "text/plain");
  18484. });
  18485. svr_.Options("/options",
  18486. [](const httplib::Request &, httplib::Response &res) {
  18487. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18488. });
  18489. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18490. svr_.wait_until_ready();
  18491. }
  18492. void TearDown() override {
  18493. svr_.stop();
  18494. if (thread_.joinable()) thread_.join();
  18495. }
  18496. httplib::Server svr_;
  18497. std::thread thread_;
  18498. };
  18499. // stream::Get tests
  18500. TEST_F(StreamApiTest, GetBasic) {
  18501. httplib::Client cli(HOST, PORT);
  18502. auto result = httplib::stream::Get(cli, "/hello");
  18503. ASSERT_TRUE(result.is_valid());
  18504. EXPECT_EQ(200, result.status());
  18505. EXPECT_EQ("Hello World!", read_body(result));
  18506. }
  18507. TEST_F(StreamApiTest, GetWithParams) {
  18508. httplib::Client cli(HOST, PORT);
  18509. httplib::Params params{{"foo", "bar"}};
  18510. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18511. ASSERT_TRUE(result.is_valid());
  18512. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18513. }
  18514. TEST_F(StreamApiTest, GetConnectionError) {
  18515. httplib::Client cli(HOST, 9999);
  18516. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18517. }
  18518. TEST_F(StreamApiTest, Get404) {
  18519. httplib::Client cli(HOST, PORT);
  18520. auto result = httplib::stream::Get(cli, "/nonexistent");
  18521. EXPECT_TRUE(result.is_valid());
  18522. EXPECT_EQ(404, result.status());
  18523. }
  18524. // stream::Post tests
  18525. TEST_F(StreamApiTest, PostBasic) {
  18526. httplib::Client cli(HOST, PORT);
  18527. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18528. "application/json");
  18529. ASSERT_TRUE(result.is_valid());
  18530. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18531. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18532. }
  18533. TEST_F(StreamApiTest, PostWithHeaders) {
  18534. httplib::Client cli(HOST, PORT);
  18535. httplib::Headers headers{{"X-Custom", "value"}};
  18536. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18537. "text/plain");
  18538. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18539. }
  18540. TEST_F(StreamApiTest, PostWithParams) {
  18541. httplib::Client cli(HOST, PORT);
  18542. httplib::Params params{{"k", "v"}};
  18543. auto result =
  18544. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18545. auto body = read_body(result);
  18546. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18547. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18548. }
  18549. TEST_F(StreamApiTest, PostLarge) {
  18550. httplib::Client cli(HOST, PORT);
  18551. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18552. size_t total = 0;
  18553. while (result.next()) {
  18554. total += result.size();
  18555. }
  18556. EXPECT_EQ(100u * 1024u, total);
  18557. }
  18558. // stream::Put/Patch tests
  18559. TEST_F(StreamApiTest, PutAndPatch) {
  18560. httplib::Client cli(HOST, PORT);
  18561. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18562. EXPECT_EQ("PUT:test", read_body(put));
  18563. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18564. EXPECT_EQ("PATCH:test", read_body(patch));
  18565. }
  18566. // stream::Delete tests
  18567. TEST_F(StreamApiTest, Delete) {
  18568. httplib::Client cli(HOST, PORT);
  18569. auto del1 = httplib::stream::Delete(cli, "/resource");
  18570. EXPECT_EQ("Deleted", read_body(del1));
  18571. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18572. EXPECT_EQ("Deleted:data", read_body(del2));
  18573. }
  18574. // stream::Head/Options tests
  18575. TEST_F(StreamApiTest, HeadAndOptions) {
  18576. httplib::Client cli(HOST, PORT);
  18577. auto head = httplib::stream::Head(cli, "/head-test");
  18578. EXPECT_TRUE(head.is_valid());
  18579. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18580. auto opts = httplib::stream::Options(cli, "/options");
  18581. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18582. }
  18583. // SSL stream::* tests
  18584. #ifdef CPPHTTPLIB_SSL_ENABLED
  18585. class SSLStreamApiTest : public ::testing::Test {
  18586. protected:
  18587. void SetUp() override {
  18588. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18589. res.set_content("Hello SSL!", "text/plain");
  18590. });
  18591. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18592. res.set_content(req.body, "text/plain");
  18593. });
  18594. port_ = svr_.bind_to_any_port("127.0.0.1");
  18595. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18596. svr_.wait_until_ready();
  18597. }
  18598. void TearDown() override {
  18599. svr_.stop();
  18600. if (thread_.joinable()) thread_.join();
  18601. }
  18602. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18603. std::thread thread_;
  18604. int port_ = 0;
  18605. };
  18606. TEST_F(SSLStreamApiTest, GetAndPost) {
  18607. httplib::SSLClient cli("127.0.0.1", port_);
  18608. cli.enable_server_certificate_verification(false);
  18609. auto get = httplib::stream::Get(cli, "/hello");
  18610. EXPECT_EQ("Hello SSL!", read_body(get));
  18611. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18612. EXPECT_EQ("test", read_body(post));
  18613. }
  18614. #endif
  18615. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18616. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18617. // BodyReader
  18618. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18619. // Test that read timeout during streaming is detected
  18620. // Use a large content-length response where server delays mid-stream
  18621. Server svr;
  18622. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18623. // Send a large response with delay in the middle
  18624. res.set_content_provider(
  18625. 1000, // content_length
  18626. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18627. if (offset < 100) {
  18628. // Send first 100 bytes immediately
  18629. std::string data(100, 'A');
  18630. sink.write(data.c_str(), data.size());
  18631. return true;
  18632. }
  18633. // Then delay longer than client timeout
  18634. std::this_thread::sleep_for(std::chrono::seconds(3));
  18635. std::string data(900, 'B');
  18636. sink.write(data.c_str(), data.size());
  18637. return true;
  18638. });
  18639. });
  18640. auto port = 8091;
  18641. std::thread t([&]() { svr.listen("localhost", port); });
  18642. svr.wait_until_ready();
  18643. Client cli("localhost", port);
  18644. cli.set_read_timeout(1, 0); // 1 second timeout
  18645. auto handle = cli.open_stream("GET", "/slow-stream");
  18646. ASSERT_TRUE(handle.is_valid());
  18647. char buf[256];
  18648. ssize_t total = 0;
  18649. ssize_t n;
  18650. bool got_error = false;
  18651. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18652. total += n;
  18653. }
  18654. if (n < 0) {
  18655. got_error = true;
  18656. // Should be timeout or read error
  18657. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18658. handle.get_read_error() == Error::Read)
  18659. << "Actual error: " << to_string(handle.get_read_error());
  18660. }
  18661. // Either we got an error, or we got less data than expected
  18662. EXPECT_TRUE(got_error || total < 1000)
  18663. << "Expected timeout but got all " << total << " bytes";
  18664. svr.stop();
  18665. t.join();
  18666. }
  18667. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18668. // Test connection closed detection via BodyReader
  18669. Server svr;
  18670. std::atomic<bool> close_now{false};
  18671. svr.Get("/will-close", [&](const Request &, Response &res) {
  18672. res.set_content_provider(
  18673. 10000, // Large content_length that we won't fully send
  18674. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18675. if (offset < 100) {
  18676. std::string data(100, 'X');
  18677. sink.write(data.c_str(), data.size());
  18678. return true;
  18679. }
  18680. // Wait for signal then abort
  18681. while (!close_now) {
  18682. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18683. }
  18684. return false; // Abort - server will close connection
  18685. });
  18686. });
  18687. auto port = 8092;
  18688. std::thread t([&]() { svr.listen("localhost", port); });
  18689. svr.wait_until_ready();
  18690. Client cli("localhost", port);
  18691. auto handle = cli.open_stream("GET", "/will-close");
  18692. ASSERT_TRUE(handle.is_valid());
  18693. char buf[256];
  18694. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18695. EXPECT_GT(n, 0) << "First read should succeed";
  18696. // Signal server to close
  18697. close_now = true;
  18698. // Keep reading until error or EOF
  18699. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18700. // Keep reading
  18701. }
  18702. // Should get an error since content_length wasn't satisfied
  18703. if (n < 0) {
  18704. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18705. handle.get_read_error() == Error::Read)
  18706. << "Actual error: " << to_string(handle.get_read_error());
  18707. }
  18708. svr.stop();
  18709. t.join();
  18710. }
  18711. #ifdef CPPHTTPLIB_SSL_ENABLED
  18712. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18713. // Test that read timeout during SSL streaming is detected
  18714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18715. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18716. res.set_content_provider(
  18717. 1000, "text/plain",
  18718. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18719. if (offset < 100) {
  18720. std::string data(100, 'A');
  18721. sink.write(data.c_str(), data.size());
  18722. return true;
  18723. }
  18724. std::this_thread::sleep_for(std::chrono::seconds(3));
  18725. std::string data(900, 'B');
  18726. sink.write(data.c_str(), data.size());
  18727. return true;
  18728. });
  18729. });
  18730. auto port = 8093;
  18731. std::thread t([&]() { svr.listen("localhost", port); });
  18732. svr.wait_until_ready();
  18733. SSLClient cli("localhost", port);
  18734. cli.enable_server_certificate_verification(false);
  18735. cli.set_read_timeout(1, 0); // 1 second timeout
  18736. auto handle = cli.open_stream("GET", "/slow-stream");
  18737. ASSERT_TRUE(handle.is_valid());
  18738. char buf[256];
  18739. ssize_t total = 0;
  18740. ssize_t n;
  18741. bool got_error = false;
  18742. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18743. total += n;
  18744. }
  18745. if (n < 0) {
  18746. got_error = true;
  18747. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18748. handle.get_read_error() == Error::Read)
  18749. << "Actual error: " << to_string(handle.get_read_error());
  18750. }
  18751. EXPECT_TRUE(got_error || total < 1000)
  18752. << "Expected timeout but got all " << total << " bytes";
  18753. svr.stop();
  18754. t.join();
  18755. }
  18756. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18757. // Test SSL connection closed detection
  18758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18759. std::atomic<bool> close_now{false};
  18760. svr.Get("/will-close", [&](const Request &, Response &res) {
  18761. res.set_content_provider(
  18762. 10000, "text/plain",
  18763. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18764. if (offset < 100) {
  18765. std::string data(100, 'X');
  18766. sink.write(data.c_str(), data.size());
  18767. return true;
  18768. }
  18769. while (!close_now) {
  18770. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18771. }
  18772. return false;
  18773. });
  18774. });
  18775. auto port = 8094;
  18776. std::thread t([&]() { svr.listen("localhost", port); });
  18777. svr.wait_until_ready();
  18778. SSLClient cli("localhost", port);
  18779. cli.enable_server_certificate_verification(false);
  18780. auto handle = cli.open_stream("GET", "/will-close");
  18781. ASSERT_TRUE(handle.is_valid());
  18782. char buf[256];
  18783. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18784. EXPECT_GT(n, 0);
  18785. // Signal server to close
  18786. close_now = true;
  18787. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18788. // Keep reading
  18789. }
  18790. if (n < 0) {
  18791. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18792. handle.get_read_error() == Error::Read)
  18793. << "Actual error: " << to_string(handle.get_read_error());
  18794. }
  18795. svr.stop();
  18796. t.join();
  18797. }
  18798. #endif
  18799. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18800. using namespace httplib;
  18801. // Create a test file
  18802. const char *fname = "etag_testfile.txt";
  18803. const char *content = "etag-content";
  18804. {
  18805. std::ofstream ofs(fname);
  18806. ofs << content;
  18807. ASSERT_TRUE(ofs.good());
  18808. }
  18809. Server svr;
  18810. svr.set_mount_point("/static", ".");
  18811. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18812. svr.wait_until_ready();
  18813. Client cli(HOST, PORT);
  18814. // First request: should get 200 with ETag header
  18815. auto res1 = cli.Get("/static/etag_testfile.txt");
  18816. ASSERT_TRUE(res1);
  18817. ASSERT_EQ(200, res1->status);
  18818. ASSERT_TRUE(res1->has_header("ETag"));
  18819. std::string etag = res1->get_header_value("ETag");
  18820. EXPECT_FALSE(etag.empty());
  18821. // Verify ETag format: W/"hex-hex"
  18822. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18823. EXPECT_EQ('W', etag[0]);
  18824. EXPECT_EQ('/', etag[1]);
  18825. EXPECT_EQ('"', etag[2]);
  18826. EXPECT_EQ('"', etag.back());
  18827. // Exact match: expect 304 Not Modified
  18828. Headers h2 = {{"If-None-Match", etag}};
  18829. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18830. ASSERT_TRUE(res2);
  18831. EXPECT_EQ(304, res2->status);
  18832. // Wildcard match: expect 304 Not Modified
  18833. Headers h3 = {{"If-None-Match", "*"}};
  18834. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18835. ASSERT_TRUE(res3);
  18836. EXPECT_EQ(304, res3->status);
  18837. // Non-matching ETag: expect 200
  18838. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18839. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18840. ASSERT_TRUE(res4);
  18841. EXPECT_EQ(200, res4->status);
  18842. // Multiple ETags with one matching: expect 304
  18843. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18844. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18845. ASSERT_TRUE(res5);
  18846. EXPECT_EQ(304, res5->status);
  18847. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18848. // that equivalent to the single comma-separated list above, so the match on
  18849. // the second line must still be found.
  18850. Headers h6;
  18851. h6.emplace("If-None-Match", "W/\"other\"");
  18852. h6.emplace("If-None-Match", etag);
  18853. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18854. ASSERT_TRUE(res6);
  18855. EXPECT_EQ(304, res6->status);
  18856. svr.stop();
  18857. t.join();
  18858. std::remove(fname);
  18859. }
  18860. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18861. using namespace httplib;
  18862. Server svr;
  18863. svr.set_mount_point("/static", ".");
  18864. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18865. svr.wait_until_ready();
  18866. Client cli(HOST, PORT);
  18867. // Send If-None-Match: * to a non-existent file
  18868. Headers h = {{"If-None-Match", "*"}};
  18869. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18871. EXPECT_EQ(404, res->status);
  18872. svr.stop();
  18873. t.join();
  18874. }
  18875. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18876. using namespace httplib;
  18877. // Create a test file
  18878. const char *fname = "etag_boundary_testfile.txt";
  18879. const char *content = "boundary-test";
  18880. {
  18881. std::ofstream ofs(fname);
  18882. ofs << content;
  18883. ASSERT_TRUE(ofs.good());
  18884. }
  18885. Server svr;
  18886. svr.set_mount_point("/static", ".");
  18887. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18888. svr.wait_until_ready();
  18889. Client cli(HOST, PORT);
  18890. // Get the actual ETag
  18891. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18892. ASSERT_TRUE(res1);
  18893. ASSERT_EQ(200, res1->status);
  18894. ASSERT_TRUE(res1->has_header("ETag"));
  18895. std::string etag = res1->get_header_value("ETag");
  18896. // Test 1: Very long ETag value (longer than actual ETag)
  18897. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18898. Headers h1 = {{"If-None-Match", "W/"
  18899. "\"very-long-etag-value-that-is-much-longer-"
  18900. "than-the-actual-etag-value\""}};
  18901. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18902. ASSERT_TRUE(res2);
  18903. EXPECT_EQ(200, res2->status); // Should not match
  18904. // Test 2: Long string followed by wildcard
  18905. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18906. // string)
  18907. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18908. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18909. ASSERT_TRUE(res3);
  18910. EXPECT_EQ(304, res3->status); // Should match on "*"
  18911. // Test 3: Wildcard followed by long string
  18912. // Should match on "*" immediately and return 304
  18913. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18914. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18915. ASSERT_TRUE(res4);
  18916. EXPECT_EQ(304, res4->status); // Should match on "*"
  18917. // Test 4: Multiple long non-matching values
  18918. // Should NOT match and return 200 (test that all comparisons are safe)
  18919. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18920. "W/\"second-long-non-matching-value\", "
  18921. "W/\"third-long-non-matching-value\""}};
  18922. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18923. ASSERT_TRUE(res5);
  18924. EXPECT_EQ(200, res5->status); // Should not match
  18925. // Test 5: Single character that is not "*" (edge case)
  18926. Headers h5 = {{"If-None-Match", "X"}};
  18927. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18928. ASSERT_TRUE(res6);
  18929. EXPECT_EQ(200, res6->status); // Should not match
  18930. svr.stop();
  18931. t.join();
  18932. std::remove(fname);
  18933. }
  18934. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18935. using namespace httplib;
  18936. // Create a test file
  18937. const char *fname = "ims_testfile.txt";
  18938. const char *content = "if-modified-since-test";
  18939. {
  18940. std::ofstream ofs(fname);
  18941. ofs << content;
  18942. ASSERT_TRUE(ofs.good());
  18943. }
  18944. Server svr;
  18945. svr.set_mount_point("/static", ".");
  18946. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18947. svr.wait_until_ready();
  18948. Client cli(HOST, PORT);
  18949. // First request: should get 200 with Last-Modified header
  18950. auto res1 = cli.Get("/static/ims_testfile.txt");
  18951. ASSERT_TRUE(res1);
  18952. ASSERT_EQ(200, res1->status);
  18953. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18954. std::string last_modified = res1->get_header_value("Last-Modified");
  18955. EXPECT_FALSE(last_modified.empty());
  18956. // If-Modified-Since with same time: expect 304
  18957. Headers h2 = {{"If-Modified-Since", last_modified}};
  18958. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18959. ASSERT_TRUE(res2);
  18960. EXPECT_EQ(304, res2->status);
  18961. // If-Modified-Since with future time: expect 304
  18962. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18963. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18964. ASSERT_TRUE(res3);
  18965. EXPECT_EQ(304, res3->status);
  18966. // If-Modified-Since with past time: expect 200
  18967. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18968. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18969. ASSERT_TRUE(res4);
  18970. EXPECT_EQ(200, res4->status);
  18971. // If-None-Match takes precedence over If-Modified-Since
  18972. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18973. ASSERT_TRUE(res1->has_header("ETag"));
  18974. std::string etag = res1->get_header_value("ETag");
  18975. Headers h5 = {{"If-None-Match", etag},
  18976. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18977. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18978. ASSERT_TRUE(res5);
  18979. EXPECT_EQ(304, res5->status);
  18980. svr.stop();
  18981. t.join();
  18982. std::remove(fname);
  18983. }
  18984. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18985. using namespace httplib;
  18986. Server svr;
  18987. // Endpoint that returns compressible content
  18988. svr.Get("/compressible", [](const Request &, Response &res) {
  18989. // Return a large enough body to trigger compression
  18990. std::string body(1000, 'a');
  18991. res.set_content(body, "text/plain");
  18992. });
  18993. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18994. svr.wait_until_ready();
  18995. Client cli(HOST, PORT);
  18996. // Request with gzip support: should get Vary header when compressed
  18997. cli.set_compress(true);
  18998. auto res1 = cli.Get("/compressible");
  18999. ASSERT_TRUE(res1);
  19000. EXPECT_EQ(200, res1->status);
  19001. // If Content-Encoding is set, Vary should also be set
  19002. if (res1->has_header("Content-Encoding")) {
  19003. EXPECT_TRUE(res1->has_header("Vary"));
  19004. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19005. }
  19006. // Request without Accept-Encoding header: should not have compression
  19007. Headers h_no_compress;
  19008. auto res2 = cli.Get("/compressible", h_no_compress);
  19009. ASSERT_TRUE(res2);
  19010. EXPECT_EQ(200, res2->status);
  19011. // Verify Vary header is present when compression is applied
  19012. // (the exact behavior depends on server configuration)
  19013. svr.stop();
  19014. t.join();
  19015. }
  19016. TEST(ETagTest, IfRangeWithETag) {
  19017. using namespace httplib;
  19018. // Create a test file with known content
  19019. const char *fname = "if_range_testfile.txt";
  19020. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19021. {
  19022. std::ofstream ofs(fname);
  19023. ofs << content;
  19024. ASSERT_TRUE(ofs.good());
  19025. }
  19026. Server svr;
  19027. svr.set_mount_point("/static", ".");
  19028. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19029. svr.wait_until_ready();
  19030. Client cli(HOST, PORT);
  19031. // First request: get ETag
  19032. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19033. ASSERT_TRUE(res1);
  19034. ASSERT_EQ(200, res1->status);
  19035. ASSERT_TRUE(res1->has_header("ETag"));
  19036. std::string etag = res1->get_header_value("ETag");
  19037. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19038. // Since our server generates weak ETags (W/"..."), If-Range with our
  19039. // ETag should NOT result in partial content - it should return full content.
  19040. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19041. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19042. ASSERT_TRUE(res2);
  19043. // Weak ETag in If-Range -> full content (200), not partial (206)
  19044. EXPECT_EQ(200, res2->status);
  19045. EXPECT_EQ(content, res2->body);
  19046. EXPECT_FALSE(res2->has_header("Content-Range"));
  19047. // Range request with non-matching If-Range (ETag): should get 200 (full
  19048. // content)
  19049. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19050. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19051. ASSERT_TRUE(res3);
  19052. EXPECT_EQ(200, res3->status);
  19053. EXPECT_EQ(content, res3->body);
  19054. EXPECT_FALSE(res3->has_header("Content-Range"));
  19055. // Range request with strong ETag (hypothetical - our server doesn't generate
  19056. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19057. // should return full content)
  19058. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19059. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19060. ASSERT_TRUE(res4);
  19061. EXPECT_EQ(200, res4->status);
  19062. EXPECT_EQ(content, res4->body);
  19063. EXPECT_FALSE(res4->has_header("Content-Range"));
  19064. svr.stop();
  19065. t.join();
  19066. std::remove(fname);
  19067. }
  19068. TEST(ETagTest, IfRangeWithDate) {
  19069. using namespace httplib;
  19070. // Create a test file
  19071. const char *fname = "if_range_date_testfile.txt";
  19072. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19073. {
  19074. std::ofstream ofs(fname);
  19075. ofs << content;
  19076. ASSERT_TRUE(ofs.good());
  19077. }
  19078. Server svr;
  19079. svr.set_mount_point("/static", ".");
  19080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19081. svr.wait_until_ready();
  19082. Client cli(HOST, PORT);
  19083. // First request: get Last-Modified
  19084. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19085. ASSERT_TRUE(res1);
  19086. ASSERT_EQ(200, res1->status);
  19087. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19088. std::string last_modified = res1->get_header_value("Last-Modified");
  19089. // Range request with matching If-Range (date): should get 206
  19090. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19091. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19092. ASSERT_TRUE(res2);
  19093. EXPECT_EQ(206, res2->status);
  19094. EXPECT_EQ("FGHIJ", res2->body);
  19095. // Range request with old If-Range date: should get 200 (full content)
  19096. Headers h3 = {{"Range", "bytes=5-9"},
  19097. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19098. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19099. ASSERT_TRUE(res3);
  19100. EXPECT_EQ(200, res3->status);
  19101. EXPECT_EQ(content, res3->body);
  19102. // Range request with future If-Range date: should get 206
  19103. Headers h4 = {{"Range", "bytes=0-4"},
  19104. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19105. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19106. ASSERT_TRUE(res4);
  19107. EXPECT_EQ(206, res4->status);
  19108. EXPECT_EQ("ABCDE", res4->body);
  19109. svr.stop();
  19110. t.join();
  19111. std::remove(fname);
  19112. }
  19113. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19114. using namespace httplib;
  19115. const char *fname = "etag_malformed.txt";
  19116. const char *content = "malformed-etag";
  19117. {
  19118. std::ofstream ofs(fname);
  19119. ofs << content;
  19120. ASSERT_TRUE(ofs.good());
  19121. }
  19122. Server svr;
  19123. svr.set_mount_point("/static", ".");
  19124. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19125. svr.wait_until_ready();
  19126. Client cli(HOST, PORT);
  19127. // baseline: should get 200 and an ETag
  19128. auto res1 = cli.Get("/static/etag_malformed.txt");
  19129. ASSERT_TRUE(res1);
  19130. ASSERT_EQ(200, res1->status);
  19131. ASSERT_TRUE(res1->has_header("ETag"));
  19132. // Malformed ETag value (missing quotes) should be treated as non-matching
  19133. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19134. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19135. ASSERT_TRUE(res_bad);
  19136. EXPECT_EQ(200, res_bad->status);
  19137. // Whitespace-only header value should be considered invalid / non-matching
  19138. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19139. "Host: localhost\r\n"
  19140. "If-None-Match: \r\n"
  19141. "Connection: close\r\n"
  19142. "\r\n";
  19143. std::string out;
  19144. ASSERT_TRUE(send_request(5, raw_req, &out));
  19145. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19146. svr.stop();
  19147. t.join();
  19148. std::remove(fname);
  19149. }
  19150. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19151. using namespace httplib;
  19152. const char *fname = "ims_invalid_format.txt";
  19153. const char *content = "ims-bad-format";
  19154. {
  19155. std::ofstream ofs(fname);
  19156. ofs << content;
  19157. ASSERT_TRUE(ofs.good());
  19158. }
  19159. Server svr;
  19160. svr.set_mount_point("/static", ".");
  19161. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19162. svr.wait_until_ready();
  19163. Client cli(HOST, PORT);
  19164. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19165. ASSERT_TRUE(res1);
  19166. ASSERT_EQ(200, res1->status);
  19167. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19168. // If-Modified-Since with invalid format should not result in 304
  19169. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19170. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19171. ASSERT_TRUE(res_bad);
  19172. EXPECT_EQ(200, res_bad->status);
  19173. // If-Range with invalid date format should be treated as mismatch -> full
  19174. // content (200)
  19175. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19176. {"If-Range", "invalid-date"}};
  19177. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19178. ASSERT_TRUE(res_ifrange);
  19179. EXPECT_EQ(200, res_ifrange->status);
  19180. svr.stop();
  19181. t.join();
  19182. std::remove(fname);
  19183. }
  19184. TEST(ETagTest, IfRangeWithMalformedETag) {
  19185. using namespace httplib;
  19186. const char *fname = "ifrange_malformed.txt";
  19187. const std::string content = "0123456789";
  19188. {
  19189. std::ofstream ofs(fname);
  19190. ofs << content;
  19191. ASSERT_TRUE(ofs.good());
  19192. }
  19193. Server svr;
  19194. svr.set_mount_point("/static", ".");
  19195. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19196. svr.wait_until_ready();
  19197. Client cli(HOST, PORT);
  19198. // First request: get ETag
  19199. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19200. ASSERT_TRUE(res1);
  19201. ASSERT_EQ(200, res1->status);
  19202. ASSERT_TRUE(res1->has_header("ETag"));
  19203. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19204. // full content (200)
  19205. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19206. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19207. ASSERT_TRUE(res2);
  19208. EXPECT_EQ(200, res2->status);
  19209. EXPECT_EQ(content, res2->body);
  19210. svr.stop();
  19211. t.join();
  19212. std::remove(fname);
  19213. }
  19214. TEST(ETagTest, ExtremeLargeDateValues) {
  19215. using namespace httplib;
  19216. const char *fname = "ims_extreme_date.txt";
  19217. const char *content = "ims-extreme-date";
  19218. {
  19219. std::ofstream ofs(fname);
  19220. ofs << content;
  19221. ASSERT_TRUE(ofs.good());
  19222. }
  19223. Server svr;
  19224. svr.set_mount_point("/static", ".");
  19225. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19226. svr.wait_until_ready();
  19227. Client cli(HOST, PORT);
  19228. auto res1 = cli.Get(std::string("/static/") + fname);
  19229. ASSERT_TRUE(res1);
  19230. ASSERT_EQ(200, res1->status);
  19231. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19232. // Extremely large year that may overflow date parsing routines.
  19233. Headers h_large_date = {
  19234. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19235. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19236. ASSERT_TRUE(res_bad);
  19237. // Expect server to treat this as invalid/mismatch and return full content
  19238. EXPECT_EQ(200, res_bad->status);
  19239. // If-Range with extremely large date should be treated as mismatch -> full
  19240. // content (200)
  19241. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19242. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19243. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19244. ASSERT_TRUE(res_ifrange);
  19245. EXPECT_EQ(200, res_ifrange->status);
  19246. svr.stop();
  19247. t.join();
  19248. std::remove(fname);
  19249. }
  19250. TEST(ETagTest, NegativeFileModificationTime) {
  19251. using namespace httplib;
  19252. const char *fname = "ims_negative_mtime.txt";
  19253. const std::string content = "negative-mtime";
  19254. {
  19255. std::ofstream ofs(fname);
  19256. ofs << content;
  19257. ASSERT_TRUE(ofs.good());
  19258. }
  19259. // Try to set file mtime to a negative value. This may fail on some
  19260. // platforms/filesystems; if it fails, the test will still verify server
  19261. // behaves safely by performing a regular conditional request.
  19262. #if defined(__APPLE__) || defined(__linux__)
  19263. bool set_negative = false;
  19264. do {
  19265. struct timeval times[2];
  19266. // access time: now
  19267. times[0].tv_sec = time(nullptr);
  19268. times[0].tv_usec = 0;
  19269. // modification time: negative (e.g., -1)
  19270. times[1].tv_sec = -1;
  19271. times[1].tv_usec = 0;
  19272. if (utimes(fname, times) == 0) { set_negative = true; }
  19273. } while (0);
  19274. #else
  19275. bool set_negative = false;
  19276. #endif
  19277. Server svr;
  19278. svr.set_mount_point("/static", ".");
  19279. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19280. svr.wait_until_ready();
  19281. Client cli(HOST, PORT);
  19282. auto res1 = cli.Get(std::string("/static/") + fname);
  19283. ASSERT_TRUE(res1);
  19284. ASSERT_EQ(200, res1->status);
  19285. bool has_last_modified = res1->has_header("Last-Modified");
  19286. std::string last_modified;
  19287. if (has_last_modified) {
  19288. last_modified = res1->get_header_value("Last-Modified");
  19289. }
  19290. if (set_negative) {
  19291. // If we successfully set a negative mtime, ensure server returns a
  19292. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19293. // with an old date and ensure server handles it without crash.
  19294. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19295. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19296. ASSERT_TRUE(res2);
  19297. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19298. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19299. } else {
  19300. // Could not set negative mtime on this platform; fall back to verifying
  19301. // that normal invalid/malformed dates are treated safely (non-304).
  19302. Headers h_bad_date = {
  19303. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19304. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19305. ASSERT_TRUE(res_bad);
  19306. EXPECT_EQ(200, res_bad->status);
  19307. }
  19308. svr.stop();
  19309. t.join();
  19310. std::remove(fname);
  19311. }
  19312. //==============================================================================
  19313. // Integration Tests with Server
  19314. //==============================================================================
  19315. class SSEIntegrationTest : public ::testing::Test {
  19316. protected:
  19317. void SetUp() override {
  19318. stop_server_.store(false);
  19319. events_.clear();
  19320. server_ = httplib::detail::make_unique<Server>();
  19321. setup_server();
  19322. start_server();
  19323. }
  19324. void TearDown() override {
  19325. stop_server_.store(true);
  19326. event_cv_.notify_all();
  19327. server_->stop();
  19328. if (server_thread_.joinable()) { server_thread_.join(); }
  19329. }
  19330. void setup_server() {
  19331. // Simple SSE endpoint
  19332. server_->Get("/events", [this](const Request &req, Response &res) {
  19333. auto last_id = req.get_header_value("Last-Event-ID");
  19334. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19335. res.set_chunked_content_provider(
  19336. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19337. std::unique_lock<std::mutex> lock(event_mutex_);
  19338. if (event_cv_.wait_for(
  19339. lock, std::chrono::milliseconds(200), [this] {
  19340. return !events_.empty() || stop_server_.load();
  19341. })) {
  19342. if (stop_server_.load()) { return false; }
  19343. if (!events_.empty()) {
  19344. std::string event = events_.front();
  19345. events_.erase(events_.begin());
  19346. sink.write(event.data(), event.size());
  19347. return true;
  19348. }
  19349. }
  19350. return !stop_server_.load();
  19351. });
  19352. });
  19353. // Endpoint that returns error
  19354. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19355. res.status = 500;
  19356. res.set_content("Internal Server Error", "text/plain");
  19357. });
  19358. // Endpoint for custom event types
  19359. server_->Get("/custom-events", [](const Request &, Response &res) {
  19360. res.set_chunked_content_provider(
  19361. "text/event-stream", [](size_t offset, DataSink &sink) {
  19362. if (offset == 0) {
  19363. std::string event = "event: update\ndata: updated\n\n"
  19364. "event: delete\ndata: deleted\n\n";
  19365. sink.write(event.data(), event.size());
  19366. }
  19367. return false; // End stream after sending
  19368. });
  19369. });
  19370. }
  19371. void start_server() {
  19372. port_ = server_->bind_to_any_port(HOST);
  19373. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19374. // Wait for server to start
  19375. while (!server_->is_running()) {
  19376. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19377. }
  19378. }
  19379. int get_port() const { return port_; }
  19380. void send_event(const std::string &event) {
  19381. std::lock_guard<std::mutex> lock(event_mutex_);
  19382. events_.push_back(event);
  19383. event_cv_.notify_all();
  19384. }
  19385. std::unique_ptr<Server> server_;
  19386. std::thread server_thread_;
  19387. std::mutex event_mutex_;
  19388. std::condition_variable event_cv_;
  19389. std::vector<std::string> events_;
  19390. std::atomic<bool> stop_server_{false};
  19391. std::string last_received_event_id_;
  19392. int port_ = 0;
  19393. };
  19394. //==============================================================================
  19395. // SSE Parsing Tests
  19396. //==============================================================================
  19397. class SSEParsingTest : public SSEIntegrationTest {
  19398. protected:
  19399. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19400. // A trailing sentinel event tells when the whole stream has been parsed.
  19401. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19402. auto body = stream + "event: end\ndata: end\n\n";
  19403. server_->Get("/parse", [body](const Request &, Response &res) {
  19404. res.set_content(body, "text/event-stream");
  19405. });
  19406. return collect("/parse");
  19407. }
  19408. // Runs SSEClient against path until an "end" event arrives and returns the
  19409. // messages dispatched before it
  19410. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19411. Client client(HOST, get_port());
  19412. sse::SSEClient sse(client, path);
  19413. std::mutex mutex;
  19414. std::condition_variable cv;
  19415. std::vector<sse::SSEMessage> messages;
  19416. auto done = false;
  19417. sse.on_message([&](const sse::SSEMessage &msg) {
  19418. std::lock_guard<std::mutex> lock(mutex);
  19419. // Ignore a replay from a reconnect that races with stop()
  19420. if (!done) { messages.push_back(msg); }
  19421. });
  19422. sse.on_event("end", [&](const sse::SSEMessage &) {
  19423. std::lock_guard<std::mutex> lock(mutex);
  19424. done = true;
  19425. cv.notify_all();
  19426. });
  19427. sse.set_reconnect_interval(100);
  19428. sse.start_async();
  19429. {
  19430. std::unique_lock<std::mutex> lock(mutex);
  19431. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19432. }
  19433. sse.stop();
  19434. EXPECT_TRUE(done);
  19435. return messages;
  19436. }
  19437. };
  19438. TEST_F(SSEParsingTest, SingleLineData) {
  19439. auto msgs = parse("data: hello\n\n");
  19440. ASSERT_EQ(msgs.size(), 1u);
  19441. EXPECT_EQ(msgs[0].data, "hello");
  19442. EXPECT_EQ(msgs[0].event, "message");
  19443. }
  19444. TEST_F(SSEParsingTest, MultiLineData) {
  19445. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19446. ASSERT_EQ(msgs.size(), 1u);
  19447. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19448. }
  19449. TEST_F(SSEParsingTest, CustomEventType) {
  19450. auto msgs = parse("event: update\ndata: payload\n\n");
  19451. ASSERT_EQ(msgs.size(), 1u);
  19452. EXPECT_EQ(msgs[0].event, "update");
  19453. EXPECT_EQ(msgs[0].data, "payload");
  19454. }
  19455. TEST_F(SSEParsingTest, EventIdHandling) {
  19456. auto msgs = parse("id: 12345\ndata: test\n\n");
  19457. ASSERT_EQ(msgs.size(), 1u);
  19458. EXPECT_EQ(msgs[0].id, "12345");
  19459. }
  19460. TEST_F(SSEParsingTest, EmptyEventId) {
  19461. auto msgs = parse("id:\ndata: test\n\n");
  19462. ASSERT_EQ(msgs.size(), 1u);
  19463. EXPECT_EQ(msgs[0].id, "");
  19464. }
  19465. TEST_F(SSEParsingTest, CommentsIgnored) {
  19466. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19467. ASSERT_EQ(msgs.size(), 1u);
  19468. EXPECT_EQ(msgs[0].data, "hello");
  19469. EXPECT_EQ(msgs[0].event, "message");
  19470. }
  19471. TEST_F(SSEParsingTest, ColonInValue) {
  19472. auto msgs = parse("data: hello:world:test\n\n");
  19473. ASSERT_EQ(msgs.size(), 1u);
  19474. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19475. }
  19476. TEST_F(SSEParsingTest, FieldNameOnly) {
  19477. // A line without a colon is a field name with an empty value
  19478. auto msgs = parse("data\n\n");
  19479. ASSERT_EQ(msgs.size(), 1u);
  19480. EXPECT_EQ(msgs[0].data, "");
  19481. }
  19482. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19483. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19484. ASSERT_EQ(msgs.size(), 1u);
  19485. EXPECT_EQ(msgs[0].event, "update");
  19486. EXPECT_EQ(msgs[0].data, "hello");
  19487. }
  19488. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19489. auto msgs = parse("data\r\n\r\n");
  19490. ASSERT_EQ(msgs.size(), 1u);
  19491. EXPECT_EQ(msgs[0].data, "");
  19492. }
  19493. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19494. auto msgs = parse("event: update\rdata: hello\r\r");
  19495. ASSERT_EQ(msgs.size(), 1u);
  19496. EXPECT_EQ(msgs[0].event, "update");
  19497. EXPECT_EQ(msgs[0].data, "hello");
  19498. }
  19499. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19500. // Chunk boundaries fall inside every \r\n and right before the first one
  19501. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19502. "\n\r", "\nevent: end\ndata: end\n\n"};
  19503. server_->Get("/split", [chunks](const Request &, Response &res) {
  19504. auto i = std::make_shared<size_t>(0);
  19505. res.set_chunked_content_provider(
  19506. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19507. if (*i == chunks.size()) {
  19508. sink.done();
  19509. } else {
  19510. sink.write(chunks[*i].data(), chunks[*i].size());
  19511. (*i)++;
  19512. }
  19513. return true;
  19514. });
  19515. });
  19516. auto msgs = collect("/split");
  19517. ASSERT_EQ(msgs.size(), 1u);
  19518. EXPECT_EQ(msgs[0].event, "update");
  19519. EXPECT_EQ(msgs[0].data, "hello");
  19520. }
  19521. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19522. // Only a BOM at the start of the stream is ignored
  19523. auto msgs = parse("\xEF\xBB\xBF"
  19524. "data: first\n\n"
  19525. "\xEF\xBB\xBF"
  19526. "data: second\n\n");
  19527. ASSERT_EQ(msgs.size(), 1u);
  19528. EXPECT_EQ(msgs[0].data, "first");
  19529. }
  19530. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19531. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19532. ASSERT_EQ(msgs.size(), 1u);
  19533. EXPECT_EQ(msgs[0].data, "hello");
  19534. EXPECT_EQ(msgs[0].event, "message");
  19535. }
  19536. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19537. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19538. ASSERT_EQ(msgs.size(), 2u);
  19539. EXPECT_EQ(msgs[0].data, "hello");
  19540. EXPECT_EQ(msgs[1].data, "hello");
  19541. }
  19542. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19543. // An event without data is not dispatched, and its type must not leak
  19544. // into the next event
  19545. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19546. ASSERT_EQ(msgs.size(), 1u);
  19547. EXPECT_EQ(msgs[0].event, "message");
  19548. EXPECT_EQ(msgs[0].data, "hello");
  19549. }
  19550. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19551. // The first connection sends only an id; the second echoes back the
  19552. // Last-Event-ID it was reconnected with
  19553. std::atomic<int> connection_count{0};
  19554. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19555. if (connection_count++ == 0) {
  19556. res.set_content("id: 42\n\n", "text/event-stream");
  19557. } else {
  19558. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19559. "\n\nevent: end\ndata: end\n\n",
  19560. "text/event-stream");
  19561. }
  19562. });
  19563. auto msgs = collect("/id-only");
  19564. ASSERT_EQ(msgs.size(), 1u);
  19565. EXPECT_EQ(msgs[0].data, "42");
  19566. }
  19567. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19568. // The first connection sets an id and then clears it with an empty one; the
  19569. // second reports whether it was reconnected with a Last-Event-ID
  19570. std::atomic<int> connection_count{0};
  19571. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19572. if (connection_count++ == 0) {
  19573. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19574. "text/event-stream");
  19575. } else {
  19576. res.set_content(
  19577. std::string("data: ") +
  19578. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19579. "\n\nevent: end\ndata: end\n\n",
  19580. "text/event-stream");
  19581. }
  19582. });
  19583. auto msgs = collect("/id-clear");
  19584. ASSERT_EQ(msgs.size(), 3u);
  19585. EXPECT_EQ(msgs[0].id, "1");
  19586. EXPECT_EQ(msgs[1].id, "");
  19587. EXPECT_EQ(msgs[2].data, "not sent");
  19588. }
  19589. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19590. // The first connection sets an id and then sends ids that cannot be carried
  19591. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19592. // with
  19593. std::atomic<int> connection_count{0};
  19594. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19595. if (connection_count++ == 0) {
  19596. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19597. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19598. "text/event-stream");
  19599. } else {
  19600. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19601. "\n\nevent: end\ndata: end\n\n",
  19602. "text/event-stream");
  19603. }
  19604. });
  19605. auto msgs = collect("/id-unsendable");
  19606. ASSERT_EQ(msgs.size(), 1u);
  19607. EXPECT_EQ(msgs[0].data, "42");
  19608. }
  19609. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19610. auto msgs = parse("event: notification\nid: evt-42\n"
  19611. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19612. ASSERT_EQ(msgs.size(), 1u);
  19613. EXPECT_EQ(msgs[0].event, "notification");
  19614. EXPECT_EQ(msgs[0].id, "evt-42");
  19615. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19616. }
  19617. TEST(SSEMessageTest, Clear) {
  19618. sse::SSEMessage msg;
  19619. msg.event = "custom";
  19620. msg.data = "some data";
  19621. msg.id = "123";
  19622. msg.clear();
  19623. EXPECT_EQ(msg.event, "message");
  19624. EXPECT_EQ(msg.data, "");
  19625. EXPECT_EQ(msg.id, "");
  19626. }
  19627. //==============================================================================
  19628. // SSE Integration Tests
  19629. //==============================================================================
  19630. // Test: Successful connection and on_open callback
  19631. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19632. // Add a simple endpoint that sends one event and closes
  19633. server_->Get("/simple-event", [](const Request &, Response &res) {
  19634. res.set_chunked_content_provider(
  19635. "text/event-stream", [](size_t offset, DataSink &sink) {
  19636. if (offset == 0) {
  19637. std::string event = "data: hello\n\n";
  19638. sink.write(event.data(), event.size());
  19639. }
  19640. return false; // Close stream after sending
  19641. });
  19642. });
  19643. Client client("localhost", get_port());
  19644. sse::SSEClient sse(client, "/simple-event");
  19645. std::atomic<bool> open_called{false};
  19646. std::atomic<bool> message_received{false};
  19647. sse.on_open([&open_called]() { open_called.store(true); });
  19648. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19649. if (msg.data == "hello") { message_received.store(true); }
  19650. });
  19651. sse.set_reconnect_interval(100);
  19652. sse.set_max_reconnect_attempts(1);
  19653. // Start async
  19654. sse.start_async();
  19655. // Wait for message to be processed
  19656. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19657. sse.stop();
  19658. EXPECT_TRUE(open_called.load());
  19659. EXPECT_TRUE(message_received.load());
  19660. }
  19661. // Test: on_message callback
  19662. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19663. // Endpoint that sends multiple events then closes
  19664. server_->Get("/multi-event", [](const Request &, Response &res) {
  19665. res.set_chunked_content_provider(
  19666. "text/event-stream", [](size_t offset, DataSink &sink) {
  19667. if (offset == 0) {
  19668. std::string events = "data: message1\n\ndata: message2\n\n";
  19669. sink.write(events.data(), events.size());
  19670. }
  19671. return false;
  19672. });
  19673. });
  19674. Client client("localhost", get_port());
  19675. sse::SSEClient sse(client, "/multi-event");
  19676. std::vector<std::string> received_messages;
  19677. std::mutex messages_mutex;
  19678. sse.on_message([&](const sse::SSEMessage &msg) {
  19679. std::lock_guard<std::mutex> lock(messages_mutex);
  19680. received_messages.push_back(msg.data);
  19681. });
  19682. sse.set_reconnect_interval(100);
  19683. sse.set_max_reconnect_attempts(1);
  19684. sse.start_async();
  19685. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19686. sse.stop();
  19687. std::lock_guard<std::mutex> lock(messages_mutex);
  19688. EXPECT_GE(received_messages.size(), 2u);
  19689. if (received_messages.size() >= 2) {
  19690. EXPECT_EQ(received_messages[0], "message1");
  19691. EXPECT_EQ(received_messages[1], "message2");
  19692. }
  19693. }
  19694. // Test: on_event for specific types
  19695. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19696. Client client("localhost", get_port());
  19697. sse::SSEClient sse(client, "/custom-events");
  19698. std::atomic<bool> update_received{false};
  19699. std::atomic<bool> delete_received{false};
  19700. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19701. if (msg.data == "updated") { update_received.store(true); }
  19702. });
  19703. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19704. if (msg.data == "deleted") { delete_received.store(true); }
  19705. });
  19706. sse.set_max_reconnect_attempts(1);
  19707. sse.start_async();
  19708. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19709. sse.stop();
  19710. EXPECT_TRUE(update_received.load());
  19711. EXPECT_TRUE(delete_received.load());
  19712. }
  19713. // Test: on_error callback on connection failure
  19714. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19715. // Connect to a non-existent port
  19716. Client client("localhost", 59999);
  19717. sse::SSEClient sse(client, "/events");
  19718. std::atomic<bool> error_called{false};
  19719. Error received_error = Error::Success;
  19720. sse.on_error([&](Error err) {
  19721. error_called.store(true);
  19722. received_error = err;
  19723. });
  19724. sse.set_reconnect_interval(50);
  19725. sse.set_max_reconnect_attempts(1);
  19726. sse.start_async();
  19727. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19728. sse.stop();
  19729. EXPECT_TRUE(error_called.load());
  19730. EXPECT_NE(received_error, Error::Success);
  19731. }
  19732. // Test: Last-Event-ID header sent on reconnect
  19733. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19734. // Endpoint that sends event with ID
  19735. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19736. res.set_chunked_content_provider(
  19737. "text/event-stream", [](size_t offset, DataSink &sink) {
  19738. if (offset == 0) {
  19739. std::string event = "id: evt-123\ndata: test\n\n";
  19740. sink.write(event.data(), event.size());
  19741. }
  19742. return false;
  19743. });
  19744. });
  19745. Client client("localhost", get_port());
  19746. sse::SSEClient sse(client, "/event-with-id");
  19747. std::atomic<bool> id_received{false};
  19748. sse.on_message([&](const sse::SSEMessage &msg) {
  19749. if (!msg.id.empty()) { id_received.store(true); }
  19750. });
  19751. sse.set_reconnect_interval(100);
  19752. sse.set_max_reconnect_attempts(1);
  19753. sse.start_async();
  19754. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19755. sse.stop();
  19756. EXPECT_TRUE(id_received.load());
  19757. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19758. }
  19759. // Test: Manual stop
  19760. TEST_F(SSEIntegrationTest, ManualStop) {
  19761. // Endpoint that sends one event and stays open briefly
  19762. std::atomic<bool> handler_running{true};
  19763. server_->Get("/stay-open", [&handler_running](const Request &,
  19764. Response &res) {
  19765. res.set_chunked_content_provider(
  19766. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19767. if (offset == 0) {
  19768. std::string event = "data: connected\n\n";
  19769. sink.write(event.data(), event.size());
  19770. }
  19771. // Keep connection open while handler_running is true
  19772. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19773. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19774. }
  19775. return false;
  19776. });
  19777. });
  19778. Client client("localhost", get_port());
  19779. sse::SSEClient sse(client, "/stay-open");
  19780. std::atomic<bool> connected{false};
  19781. sse.on_open([&connected]() { connected.store(true); });
  19782. sse.set_reconnect_interval(100);
  19783. sse.set_max_reconnect_attempts(1);
  19784. sse.start_async();
  19785. // Wait for connection to establish
  19786. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19787. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19788. }
  19789. EXPECT_TRUE(connected.load());
  19790. EXPECT_TRUE(sse.is_connected());
  19791. // Signal handler to stop
  19792. handler_running.store(false);
  19793. // Stop SSE client
  19794. sse.stop();
  19795. EXPECT_FALSE(sse.is_connected());
  19796. }
  19797. // Test: SSEClient with custom headers
  19798. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19799. // Setup a server endpoint that checks for custom header
  19800. std::atomic<bool> header_received{false};
  19801. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19802. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19803. header_received.store(true);
  19804. }
  19805. res.set_chunked_content_provider("text/event-stream",
  19806. [](size_t, DataSink &) { return false; });
  19807. });
  19808. Client client("localhost", get_port());
  19809. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19810. sse::SSEClient sse(client, "/header-check", headers);
  19811. sse.set_max_reconnect_attempts(1);
  19812. sse.start_async();
  19813. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19814. sse.stop();
  19815. EXPECT_TRUE(header_received.load());
  19816. }
  19817. // Test: Reconnect interval configuration
  19818. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19819. Client client("localhost", get_port());
  19820. sse::SSEClient sse(client, "/events");
  19821. auto &result = sse.set_reconnect_interval(500);
  19822. // Builder pattern should return reference to self
  19823. EXPECT_EQ(&result, &sse);
  19824. }
  19825. // Test: Max reconnect attempts
  19826. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19827. // Connect to non-existent port to force reconnects
  19828. Client client("localhost", 59998);
  19829. sse::SSEClient sse(client, "/events");
  19830. std::atomic<int> error_count{0};
  19831. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19832. sse.set_reconnect_interval(50);
  19833. sse.set_max_reconnect_attempts(2);
  19834. auto start = std::chrono::steady_clock::now();
  19835. sse.start(); // Blocking call
  19836. auto end = std::chrono::steady_clock::now();
  19837. // Should have stopped after 2 failed attempts
  19838. EXPECT_GE(error_count.load(), 2);
  19839. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19840. auto duration =
  19841. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19842. #ifdef _WIN32
  19843. // Windows is much slower for socket connection failures
  19844. EXPECT_LT(duration.count(), 7000);
  19845. #else
  19846. EXPECT_LT(duration.count(), 1000);
  19847. #endif
  19848. }
  19849. // Test: Multi-line data in integration
  19850. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19851. // Endpoint with multi-line data
  19852. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19853. res.set_chunked_content_provider(
  19854. "text/event-stream", [](size_t offset, DataSink &sink) {
  19855. if (offset == 0) {
  19856. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19857. sink.write(event.data(), event.size());
  19858. }
  19859. return false;
  19860. });
  19861. });
  19862. Client client("localhost", get_port());
  19863. sse::SSEClient sse(client, "/multiline-data");
  19864. std::string received_data;
  19865. std::mutex data_mutex;
  19866. sse.on_message([&](const sse::SSEMessage &msg) {
  19867. std::lock_guard<std::mutex> lock(data_mutex);
  19868. received_data = msg.data;
  19869. });
  19870. sse.set_reconnect_interval(100);
  19871. sse.set_max_reconnect_attempts(1);
  19872. sse.start_async();
  19873. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19874. sse.stop();
  19875. std::lock_guard<std::mutex> lock(data_mutex);
  19876. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19877. }
  19878. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19879. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19880. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19881. DataSink &sink) {
  19882. if (offset == 0) {
  19883. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19884. sink.write(events.data(), events.size());
  19885. }
  19886. return false;
  19887. });
  19888. });
  19889. Client client("localhost", get_port());
  19890. sse::SSEClient sse(client, "/empty-data-lines");
  19891. std::mutex mutex;
  19892. std::condition_variable cv;
  19893. std::vector<std::string> received;
  19894. sse.on_message([&](const sse::SSEMessage &msg) {
  19895. std::lock_guard<std::mutex> lock(mutex);
  19896. received.push_back(msg.data);
  19897. cv.notify_all();
  19898. });
  19899. sse.set_max_reconnect_attempts(1);
  19900. sse.start_async();
  19901. {
  19902. std::unique_lock<std::mutex> lock(mutex);
  19903. cv.wait_for(lock, std::chrono::seconds(2),
  19904. [&] { return received.size() >= 3; });
  19905. }
  19906. sse.stop();
  19907. ASSERT_GE(received.size(), 3u);
  19908. EXPECT_EQ(received[0], "");
  19909. EXPECT_EQ(received[1], "\nhello");
  19910. EXPECT_EQ(received[2], "");
  19911. }
  19912. // Test: Auto-reconnect after server disconnection
  19913. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19914. std::atomic<int> connection_count{0};
  19915. std::atomic<int> message_count{0};
  19916. // Endpoint that sends one event and closes, forcing reconnect
  19917. server_->Get("/reconnect-test",
  19918. [&connection_count](const Request &, Response &res) {
  19919. connection_count.fetch_add(1);
  19920. res.set_chunked_content_provider(
  19921. "text/event-stream", [](size_t offset, DataSink &sink) {
  19922. if (offset == 0) {
  19923. std::string event = "data: hello\n\n";
  19924. sink.write(event.data(), event.size());
  19925. }
  19926. return false; // Close connection after sending
  19927. });
  19928. });
  19929. Client client("localhost", get_port());
  19930. sse::SSEClient sse(client, "/reconnect-test");
  19931. sse.on_message([&message_count](const sse::SSEMessage &) {
  19932. message_count.fetch_add(1);
  19933. });
  19934. sse.set_reconnect_interval(100);
  19935. sse.set_max_reconnect_attempts(3);
  19936. sse.start_async();
  19937. // Wait long enough for multiple reconnects
  19938. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19939. sse.stop();
  19940. // Should have connected multiple times (initial + reconnects)
  19941. EXPECT_GE(connection_count.load(), 2);
  19942. // Should have received messages from multiple connections
  19943. EXPECT_GE(message_count.load(), 2);
  19944. }
  19945. // Test: A retry field that is not all ASCII digits is ignored
  19946. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19947. std::atomic<int> connection_count{0};
  19948. server_->Get("/bad-retry",
  19949. [&connection_count](const Request &, Response &res) {
  19950. connection_count.fetch_add(1);
  19951. res.set_chunked_content_provider(
  19952. "text/event-stream", [](size_t offset, DataSink &sink) {
  19953. if (offset == 0) {
  19954. std::string event = "retry: -1\ndata: hello\n\n";
  19955. sink.write(event.data(), event.size());
  19956. }
  19957. return false;
  19958. });
  19959. });
  19960. Client client("localhost", get_port());
  19961. sse::SSEClient sse(client, "/bad-retry");
  19962. sse.set_reconnect_interval(10000);
  19963. sse.start_async();
  19964. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19965. sse.stop();
  19966. EXPECT_EQ(connection_count.load(), 1);
  19967. }
  19968. // Test: A retry field of all ASCII digits sets the reconnection time
  19969. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19970. std::mutex mutex;
  19971. std::condition_variable cv;
  19972. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19973. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19974. {
  19975. std::lock_guard<std::mutex> lock(mutex);
  19976. connected_at.push_back(std::chrono::steady_clock::now());
  19977. cv.notify_all();
  19978. }
  19979. res.set_chunked_content_provider(
  19980. "text/event-stream", [](size_t offset, DataSink &sink) {
  19981. if (offset == 0) {
  19982. std::string event = "retry: 0\ndata: hello\n\n";
  19983. sink.write(event.data(), event.size());
  19984. }
  19985. return false;
  19986. });
  19987. });
  19988. Client client("localhost", get_port());
  19989. sse::SSEClient sse(client, "/zero-retry");
  19990. sse.set_reconnect_interval(10000);
  19991. sse.start_async();
  19992. {
  19993. std::unique_lock<std::mutex> lock(mutex);
  19994. cv.wait_for(lock, std::chrono::seconds(5),
  19995. [&] { return connected_at.size() >= 2; });
  19996. }
  19997. sse.stop();
  19998. // The server-supplied interval is applied, but never below 100ms, so
  19999. // "retry: 0" does not cause a busy reconnect loop
  20000. std::lock_guard<std::mutex> lock(mutex);
  20001. ASSERT_GE(connected_at.size(), 2u);
  20002. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20003. connected_at[1] - connected_at[0])
  20004. .count();
  20005. EXPECT_GE(interval_ms, 100);
  20006. }
  20007. // Test: Last-Event-ID sent on reconnect
  20008. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20009. std::atomic<int> connection_count{0};
  20010. std::vector<std::string> received_last_event_ids;
  20011. std::mutex id_mutex;
  20012. // Endpoint that checks Last-Event-ID header and sends event with ID
  20013. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20014. int conn = connection_count.fetch_add(1);
  20015. // Capture the Last-Event-ID header from each connection
  20016. {
  20017. std::lock_guard<std::mutex> lock(id_mutex);
  20018. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20019. }
  20020. res.set_chunked_content_provider(
  20021. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20022. if (offset == 0) {
  20023. std::string event =
  20024. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20025. sink.write(event.data(), event.size());
  20026. }
  20027. return false;
  20028. });
  20029. });
  20030. Client client("localhost", get_port());
  20031. sse::SSEClient sse(client, "/reconnect-with-id");
  20032. sse.set_reconnect_interval(100);
  20033. sse.set_max_reconnect_attempts(3);
  20034. sse.start_async();
  20035. // Wait for at least 2 connections
  20036. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20037. sse.stop();
  20038. // Verify behavior
  20039. std::lock_guard<std::mutex> lock(id_mutex);
  20040. EXPECT_GE(received_last_event_ids.size(), 2u);
  20041. // First connection should have no Last-Event-ID
  20042. if (!received_last_event_ids.empty()) {
  20043. EXPECT_EQ(received_last_event_ids[0], "");
  20044. }
  20045. // Second connection should have Last-Event-ID from first connection
  20046. if (received_last_event_ids.size() >= 2) {
  20047. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20048. }
  20049. }
  20050. // Test: set_headers updates headers used on reconnect
  20051. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20052. std::vector<std::string> received_tokens;
  20053. std::mutex token_mutex;
  20054. // Endpoint that captures Authorization header
  20055. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20056. {
  20057. std::lock_guard<std::mutex> lock(token_mutex);
  20058. received_tokens.push_back(req.get_header_value("Authorization"));
  20059. }
  20060. res.set_chunked_content_provider(
  20061. "text/event-stream", [](size_t offset, DataSink &sink) {
  20062. if (offset == 0) {
  20063. std::string event = "data: hello\n\n";
  20064. sink.write(event.data(), event.size());
  20065. }
  20066. return false; // Close connection to trigger reconnect
  20067. });
  20068. });
  20069. Client client("localhost", get_port());
  20070. Headers headers = {{"Authorization", "Bearer old-token"}};
  20071. sse::SSEClient sse(client, "/auth-check", headers);
  20072. // Update headers on each successful connection
  20073. sse.on_open(
  20074. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20075. sse.set_reconnect_interval(100);
  20076. sse.set_max_reconnect_attempts(3);
  20077. sse.start_async();
  20078. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20079. sse.stop();
  20080. std::lock_guard<std::mutex> lock(token_mutex);
  20081. ASSERT_GE(received_tokens.size(), 2u);
  20082. // First connection uses original header
  20083. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20084. // Second connection uses updated header from set_headers
  20085. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20086. }
  20087. // Test: 401 allows reconnection (so on_error can refresh headers)
  20088. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20089. std::atomic<int> connection_count{0};
  20090. // Endpoint: returns 401 on first attempt, 200 on second
  20091. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20092. int conn = connection_count.fetch_add(1);
  20093. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20094. res.status = StatusCode::Unauthorized_401;
  20095. res.set_content("Unauthorized", "text/plain");
  20096. return;
  20097. }
  20098. res.set_chunked_content_provider(
  20099. "text/event-stream", [](size_t offset, DataSink &sink) {
  20100. if (offset == 0) {
  20101. std::string event = "data: authenticated\n\n";
  20102. sink.write(event.data(), event.size());
  20103. }
  20104. return false;
  20105. });
  20106. });
  20107. Client client("localhost", get_port());
  20108. Headers headers = {{"Authorization", "Bearer expired"}};
  20109. sse::SSEClient sse(client, "/auth-retry", headers);
  20110. std::atomic<bool> message_received{false};
  20111. // Refresh token on error
  20112. sse.on_error(
  20113. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20114. sse.on_message([&](const sse::SSEMessage &msg) {
  20115. if (msg.data == "authenticated") { message_received.store(true); }
  20116. });
  20117. sse.set_reconnect_interval(100);
  20118. sse.set_max_reconnect_attempts(3);
  20119. sse.start_async();
  20120. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20121. sse.stop();
  20122. // Should have reconnected after 401 and succeeded with new token
  20123. EXPECT_GE(connection_count.load(), 2);
  20124. EXPECT_TRUE(message_received.load());
  20125. }
  20126. TEST(Issue2318Test, EmptyHostString) {
  20127. {
  20128. httplib::Client cli_empty("", PORT);
  20129. auto res = cli_empty.Get("/");
  20130. ASSERT_FALSE(res);
  20131. EXPECT_EQ(httplib::Error::Connection, res.error());
  20132. }
  20133. {
  20134. httplib::Client cli(" ", PORT);
  20135. auto res = cli.Get("/");
  20136. ASSERT_FALSE(res);
  20137. EXPECT_EQ(httplib::Error::Connection, res.error());
  20138. }
  20139. }
  20140. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20141. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20142. Server svr;
  20143. // Set a small payload limit (1KB)
  20144. svr.set_payload_max_length(1024);
  20145. svr.Post("/test", [&](const Request &req, Response &res) {
  20146. res.set_content("Body size: " + std::to_string(req.body.size()),
  20147. "text/plain");
  20148. });
  20149. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20150. auto se = detail::scope_exit([&] {
  20151. svr.stop();
  20152. listen_thread.join();
  20153. });
  20154. svr.wait_until_ready();
  20155. // Create data that compresses well but exceeds limit when decompressed
  20156. // 8KB of repeated null bytes compresses to a very small size
  20157. std::string original_data(8 * 1024, '\0');
  20158. // Compress the data using gzip
  20159. std::string compressed_data;
  20160. detail::gzip_compressor compressor;
  20161. compressor.compress(original_data.data(), original_data.size(), true,
  20162. [&](const char *data, size_t size) {
  20163. compressed_data.append(data, size);
  20164. return true;
  20165. });
  20166. // Verify compression worked (compressed should be much smaller)
  20167. ASSERT_LT(compressed_data.size(), original_data.size());
  20168. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20169. // Send compressed data with Content-Encoding: gzip
  20170. Client cli(HOST, PORT);
  20171. Headers headers = {{"Content-Encoding", "gzip"}};
  20172. auto res =
  20173. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20174. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20176. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20177. }
  20178. #endif
  20179. // ============================================================================
  20180. // OpenSSL-Specific Tests
  20181. // ============================================================================
  20182. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20183. X509 *readCertificate(const std::string &strFileName) {
  20184. std::ifstream inStream(strFileName);
  20185. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20186. std::istreambuf_iterator<char>());
  20187. if (strCertPEM.empty()) return (nullptr);
  20188. BIO *pbCert = BIO_new(BIO_s_mem());
  20189. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20190. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20191. BIO_free(pbCert);
  20192. return (pCert);
  20193. }
  20194. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20195. std::ifstream inStream(strFileName);
  20196. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20197. std::istreambuf_iterator<char>());
  20198. if (strPrivateKeyPEM.empty()) return (nullptr);
  20199. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20200. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20201. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20202. BIO_free(pbPrivKey);
  20203. return (pPrivateKey);
  20204. }
  20205. TEST(BindServerTest, UpdateCerts) {
  20206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20207. int port = svr.bind_to_any_port("0.0.0.0");
  20208. ASSERT_TRUE(svr.is_valid());
  20209. ASSERT_TRUE(port > 0);
  20210. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20211. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20212. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20213. ASSERT_TRUE(cert != nullptr);
  20214. ASSERT_TRUE(ca_cert != nullptr);
  20215. ASSERT_TRUE(key != nullptr);
  20216. X509_STORE *cert_store = X509_STORE_new();
  20217. X509_STORE_add_cert(cert_store, ca_cert);
  20218. // svr.update_certs(cert, key, cert_store); // deprecated
  20219. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20220. CLIENT_CA_CERT_FILE);
  20221. ASSERT_TRUE(svr.is_valid());
  20222. svr.stop();
  20223. X509_STORE_free(cert_store);
  20224. X509_free(cert);
  20225. X509_free(ca_cert);
  20226. EVP_PKEY_free(key);
  20227. }
  20228. // Test that update_certs() updates client CA list correctly
  20229. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20230. // Start with file-based constructor
  20231. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20232. ASSERT_TRUE(svr.is_valid());
  20233. // Initially no client CA list should be set
  20234. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20235. ASSERT_TRUE(ssl_ctx != nullptr);
  20236. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20237. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20238. EXPECT_EQ(0, count_before);
  20239. // Now update with client CA (PEM string)
  20240. std::string cert_pem, key_pem, ca_pem;
  20241. read_file(SERVER_CERT_FILE, cert_pem);
  20242. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20243. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20244. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20245. ASSERT_TRUE(svr.is_valid());
  20246. // Now client CA list should be set
  20247. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20248. ASSERT_TRUE(ca_list_after != nullptr);
  20249. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20250. }
  20251. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20252. // Test that the file-path SSLServer constructor properly sets the client CA
  20253. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20254. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20255. ASSERT_TRUE(svr.is_valid());
  20256. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20257. ASSERT_TRUE(ssl_ctx != nullptr);
  20258. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20259. ASSERT_TRUE(ca_list != nullptr);
  20260. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20261. }
  20262. #endif
  20263. // ============================================================================
  20264. // MbedTLS-Specific Tests
  20265. // ============================================================================
  20266. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20267. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20268. using namespace httplib::tls;
  20269. // Track if callback was invoked
  20270. bool callback_invoked = false;
  20271. // The callback receives void* ctx which is actually MbedTlsContext*
  20272. // We can access the mbedtls_ssl_config via the context
  20273. auto setup_callback = [&callback_invoked](void *ctx) {
  20274. callback_invoked = true;
  20275. // Cast to MbedTlsContext* to access the ssl config
  20276. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20277. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20278. // Use static variables to hold certificate data (simplified for test)
  20279. static mbedtls_x509_crt own_cert;
  20280. static mbedtls_pk_context own_key;
  20281. static mbedtls_x509_crt ca_chain;
  20282. static bool initialized = false;
  20283. if (!initialized) {
  20284. mbedtls_x509_crt_init(&own_cert);
  20285. mbedtls_pk_init(&own_key);
  20286. mbedtls_x509_crt_init(&ca_chain);
  20287. // Load server certificate
  20288. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20289. return false;
  20290. }
  20291. // Load server private key.
  20292. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20293. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20294. #if MBEDTLS_VERSION_MAJOR == 3
  20295. ,
  20296. mbedtls_ctr_drbg_random, nullptr
  20297. #endif
  20298. ) != 0) {
  20299. return false;
  20300. }
  20301. // Load CA chain for client verification
  20302. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20303. return false;
  20304. }
  20305. initialized = true;
  20306. }
  20307. // Configure the SSL config
  20308. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20309. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20310. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20311. // Set minimum TLS version using mbedTLS native API
  20312. #if MBEDTLS_VERSION_MAJOR >= 3
  20313. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20314. #else
  20315. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20316. MBEDTLS_SSL_MINOR_VERSION_3);
  20317. #endif
  20318. return true;
  20319. };
  20320. SSLServer svr(setup_callback);
  20321. ASSERT_TRUE(svr.is_valid());
  20322. ASSERT_TRUE(callback_invoked);
  20323. svr.Get("/test", [&](const Request &req, Response &res) {
  20324. res.set_content("test", "text/plain");
  20325. auto cert = req.peer_cert();
  20326. ASSERT_TRUE(static_cast<bool>(cert));
  20327. auto common_name = cert.subject_cn();
  20328. EXPECT_EQ("Common Name", common_name);
  20329. });
  20330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20331. auto se = detail::scope_exit([&] {
  20332. svr.stop();
  20333. t.join();
  20334. ASSERT_FALSE(svr.is_running());
  20335. });
  20336. svr.wait_until_ready();
  20337. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20338. cli.enable_server_certificate_verification(false);
  20339. cli.set_connection_timeout(30);
  20340. auto res = cli.Get("/test");
  20341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20342. ASSERT_EQ(StatusCode::OK_200, res->status);
  20343. }
  20344. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20345. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20346. // keep-alive SSL session, which reads through that config in
  20347. // mbedtls_ssl_close_notify.
  20348. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20350. ASSERT_TRUE(svr.is_valid());
  20351. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20352. res.set_content("test", "text/plain");
  20353. });
  20354. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20355. auto se = detail::scope_exit([&] {
  20356. svr.stop();
  20357. t.join();
  20358. ASSERT_FALSE(svr.is_running());
  20359. });
  20360. svr.wait_until_ready();
  20361. {
  20362. SSLClient cli(HOST, PORT);
  20363. cli.enable_server_certificate_verification(false);
  20364. cli.set_keep_alive(true);
  20365. auto res = cli.Get("/test");
  20366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20367. ASSERT_EQ(StatusCode::OK_200, res->status);
  20368. // cli is destructed here with the keep-alive SSL session still open.
  20369. }
  20370. }
  20371. #endif
  20372. // WebSocket Tests
  20373. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20374. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20375. // defining the meaning of these bits has been negotiated.
  20376. auto make_frame = [](uint8_t first_byte) {
  20377. std::string frame;
  20378. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20379. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20380. frame += "Hello";
  20381. return frame;
  20382. };
  20383. // RSV1 set (0x40)
  20384. {
  20385. detail::BufferStream strm;
  20386. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20387. ws::Opcode opcode;
  20388. std::string payload;
  20389. bool fin;
  20390. EXPECT_EQ(
  20391. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20392. ws::impl::FrameRead::Fail);
  20393. }
  20394. // RSV2 set (0x20)
  20395. {
  20396. detail::BufferStream strm;
  20397. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20398. ws::Opcode opcode;
  20399. std::string payload;
  20400. bool fin;
  20401. EXPECT_EQ(
  20402. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20403. ws::impl::FrameRead::Fail);
  20404. }
  20405. // RSV3 set (0x10)
  20406. {
  20407. detail::BufferStream strm;
  20408. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20409. ws::Opcode opcode;
  20410. std::string payload;
  20411. bool fin;
  20412. EXPECT_EQ(
  20413. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20414. ws::impl::FrameRead::Fail);
  20415. }
  20416. // No RSV bits set - should succeed
  20417. {
  20418. detail::BufferStream strm;
  20419. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20420. ws::Opcode opcode;
  20421. std::string payload;
  20422. bool fin;
  20423. EXPECT_EQ(
  20424. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20425. ws::impl::FrameRead::Ok);
  20426. EXPECT_EQ(ws::Opcode::Text, opcode);
  20427. EXPECT_EQ("Hello", payload);
  20428. EXPECT_TRUE(fin);
  20429. }
  20430. }
  20431. TEST(WebSocketTest, ControlFrameValidation) {
  20432. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20433. // payload length <= 125.
  20434. // Ping with FIN=0 - must be rejected
  20435. {
  20436. detail::BufferStream strm;
  20437. std::string frame;
  20438. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20439. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20440. strm.write(frame.data(), frame.size());
  20441. ws::Opcode opcode;
  20442. std::string payload;
  20443. bool fin;
  20444. EXPECT_EQ(
  20445. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20446. ws::impl::FrameRead::Fail);
  20447. }
  20448. // Close with FIN=0 - must be rejected
  20449. {
  20450. detail::BufferStream strm;
  20451. std::string frame;
  20452. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20453. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20454. strm.write(frame.data(), frame.size());
  20455. ws::Opcode opcode;
  20456. std::string payload;
  20457. bool fin;
  20458. EXPECT_EQ(
  20459. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20460. ws::impl::FrameRead::Fail);
  20461. }
  20462. // Ping with payload_len=126 (extended length) - must be rejected
  20463. {
  20464. detail::BufferStream strm;
  20465. std::string frame;
  20466. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20467. frame += static_cast<char>(126); // payload_len=126 (>125)
  20468. frame += static_cast<char>(0x00); // extended length high byte
  20469. frame += static_cast<char>(126); // extended length low byte
  20470. frame += std::string(126, 'x');
  20471. strm.write(frame.data(), frame.size());
  20472. ws::Opcode opcode;
  20473. std::string payload;
  20474. bool fin;
  20475. EXPECT_EQ(
  20476. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20477. ws::impl::FrameRead::Fail);
  20478. }
  20479. // Ping with FIN=1 and payload_len=125 - should succeed
  20480. {
  20481. detail::BufferStream strm;
  20482. std::string frame;
  20483. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20484. frame += static_cast<char>(125); // payload_len=125
  20485. frame += std::string(125, 'x');
  20486. strm.write(frame.data(), frame.size());
  20487. ws::Opcode opcode;
  20488. std::string payload;
  20489. bool fin;
  20490. EXPECT_EQ(
  20491. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20492. ws::impl::FrameRead::Ok);
  20493. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20494. EXPECT_EQ(125u, payload.size());
  20495. EXPECT_TRUE(fin);
  20496. }
  20497. }
  20498. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20499. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20500. // length MUST be 0.
  20501. // MSB set - must be rejected
  20502. {
  20503. detail::BufferStream strm;
  20504. std::string frame;
  20505. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20506. frame += static_cast<char>(127); // 64-bit extended length
  20507. frame += static_cast<char>(0x80); // MSB set (invalid)
  20508. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20509. strm.write(frame.data(), frame.size());
  20510. ws::Opcode opcode;
  20511. std::string payload;
  20512. bool fin;
  20513. EXPECT_EQ(
  20514. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20515. ws::impl::FrameRead::Fail);
  20516. }
  20517. // MSB clear - should pass length parsing (will be rejected by max_len,
  20518. // but that's a different check; use a small length to verify)
  20519. {
  20520. detail::BufferStream strm;
  20521. std::string frame;
  20522. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20523. frame += static_cast<char>(127); // 64-bit extended length
  20524. frame += std::string(7, '\0'); // high bytes = 0
  20525. frame += static_cast<char>(0x03); // length = 3
  20526. frame += "abc";
  20527. strm.write(frame.data(), frame.size());
  20528. ws::Opcode opcode;
  20529. std::string payload;
  20530. bool fin;
  20531. EXPECT_EQ(
  20532. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20533. ws::impl::FrameRead::Ok);
  20534. EXPECT_EQ(ws::Opcode::Text, opcode);
  20535. EXPECT_EQ("abc", payload);
  20536. }
  20537. }
  20538. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20539. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20540. // Valid UTF-8
  20541. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20542. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20543. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20544. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20545. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20546. // Invalid UTF-8
  20547. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20548. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20549. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20550. EXPECT_FALSE(
  20551. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20552. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20553. }
  20554. TEST(WebSocketTest, ConnectAndDisconnect) {
  20555. Server svr;
  20556. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20557. std::string msg;
  20558. while (ws.read(msg)) {}
  20559. });
  20560. auto port = svr.bind_to_any_port(HOST);
  20561. std::thread t([&]() { svr.listen_after_bind(); });
  20562. svr.wait_until_ready();
  20563. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20564. auto res = client.connect();
  20565. ASSERT_TRUE(res);
  20566. EXPECT_EQ(Error::Success, res.error());
  20567. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20568. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20569. EXPECT_TRUE(client.is_open());
  20570. client.close();
  20571. EXPECT_FALSE(client.is_open());
  20572. svr.stop();
  20573. t.join();
  20574. }
  20575. TEST(WebSocketTest, ValidURL) {
  20576. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20577. EXPECT_TRUE(ws1.is_valid());
  20578. ws::WebSocketClient ws2("ws://example.com/path");
  20579. EXPECT_TRUE(ws2.is_valid());
  20580. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20581. EXPECT_TRUE(ws3.is_valid());
  20582. #ifdef CPPHTTPLIB_SSL_ENABLED
  20583. ws::WebSocketClient wss1("wss://example.com/path");
  20584. EXPECT_TRUE(wss1.is_valid());
  20585. ws::WebSocketClient wss2("wss://example.com:443/path");
  20586. EXPECT_TRUE(wss2.is_valid());
  20587. #endif
  20588. }
  20589. TEST(WebSocketTest, InvalidURL) {
  20590. // No scheme
  20591. ws::WebSocketClient ws1("localhost:8080/path");
  20592. EXPECT_FALSE(ws1.is_valid());
  20593. // No path
  20594. ws::WebSocketClient ws2("ws://localhost:8080");
  20595. EXPECT_FALSE(ws2.is_valid());
  20596. // Empty string
  20597. ws::WebSocketClient ws3("");
  20598. EXPECT_FALSE(ws3.is_valid());
  20599. // Missing host
  20600. ws::WebSocketClient ws4("ws://:8080/path");
  20601. EXPECT_FALSE(ws4.is_valid());
  20602. // Port number overflow — should not crash
  20603. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20604. EXPECT_FALSE(ws5.is_valid());
  20605. // Port out of range
  20606. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20607. EXPECT_FALSE(ws6.is_valid());
  20608. }
  20609. TEST(WebSocketTest, UnsupportedScheme) {
  20610. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20611. ws::WebSocketClient ws1("http://localhost:8080/path");
  20612. EXPECT_FALSE(ws1.is_valid());
  20613. ws::WebSocketClient ws2("https://localhost:8080/path");
  20614. EXPECT_FALSE(ws2.is_valid());
  20615. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20616. EXPECT_FALSE(ws3.is_valid());
  20617. #else
  20618. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20619. std::invalid_argument);
  20620. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20621. std::invalid_argument);
  20622. #endif
  20623. }
  20624. TEST(WebSocketTest, ConnectWhenInvalid) {
  20625. ws::WebSocketClient ws("not a valid url");
  20626. EXPECT_FALSE(ws.is_valid());
  20627. auto res = ws.connect();
  20628. EXPECT_FALSE(res);
  20629. EXPECT_EQ(Error::Connection, res.error());
  20630. EXPECT_EQ(-1, res.status());
  20631. }
  20632. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20633. // Grab a port that is free, then close it again so nothing listens there
  20634. Server svr;
  20635. auto port = svr.bind_to_any_port(HOST);
  20636. svr.stop();
  20637. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20638. auto res = client.connect();
  20639. ASSERT_FALSE(res);
  20640. EXPECT_EQ(Error::Connection, res.error());
  20641. EXPECT_EQ(-1, res.status());
  20642. }
  20643. TEST(WebSocketTest, DefaultPort) {
  20644. ws::WebSocketClient ws1("ws://example.com/path");
  20645. EXPECT_TRUE(ws1.is_valid());
  20646. // ws:// defaults to port 80 (verified by successful parse)
  20647. #ifdef CPPHTTPLIB_SSL_ENABLED
  20648. ws::WebSocketClient ws2("wss://example.com/path");
  20649. EXPECT_TRUE(ws2.is_valid());
  20650. // wss:// defaults to port 443 (verified by successful parse)
  20651. #endif
  20652. }
  20653. TEST(WebSocketTest, IPv6LiteralAddress) {
  20654. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20655. EXPECT_TRUE(ws1.is_valid());
  20656. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20657. EXPECT_TRUE(ws2.is_valid());
  20658. }
  20659. TEST(WebSocketTest, ComplexPath) {
  20660. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20661. EXPECT_TRUE(ws1.is_valid());
  20662. ws::WebSocketClient ws2("ws://localhost:8080/");
  20663. EXPECT_TRUE(ws2.is_valid());
  20664. }
  20665. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20666. Server svr;
  20667. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20668. std::string msg;
  20669. while (ws.read(msg)) {}
  20670. });
  20671. auto port = svr.bind_to_any_port(HOST);
  20672. std::thread t([&]() { svr.listen_after_bind(); });
  20673. svr.wait_until_ready();
  20674. auto another_host = "example.com";
  20675. auto wrong_ip = "192.0.2.1";
  20676. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20677. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20678. ASSERT_TRUE(client.connect());
  20679. EXPECT_TRUE(client.is_open());
  20680. client.close();
  20681. svr.stop();
  20682. t.join();
  20683. }
  20684. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20685. Server svr;
  20686. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20687. std::string msg;
  20688. while (ws.read(msg)) {}
  20689. });
  20690. auto port = svr.bind_to_any_port(HOST);
  20691. std::thread t([&]() { svr.listen_after_bind(); });
  20692. svr.wait_until_ready();
  20693. auto wrong_ip = "192.0.2.1";
  20694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20695. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20696. client.set_connection_timeout(1);
  20697. client.set_read_timeout(1);
  20698. client.set_write_timeout(1);
  20699. EXPECT_FALSE(client.connect());
  20700. EXPECT_FALSE(client.is_open());
  20701. svr.stop();
  20702. t.join();
  20703. }
  20704. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20705. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20706. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20707. // (RFC 6761) is only a map key and the Host header value.
  20708. auto host = "target.invalid";
  20709. Server svr;
  20710. std::string received_host;
  20711. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20712. received_host = req.get_header_value("Host");
  20713. std::string msg;
  20714. while (ws.read(msg)) {}
  20715. });
  20716. auto port = svr.bind_to_any_port(HOST);
  20717. std::thread t([&]() { svr.listen_after_bind(); });
  20718. // ASSERT_* below returns from the test body, which would leave t joinable
  20719. // and make ~thread call std::terminate.
  20720. auto se = detail::scope_exit([&] {
  20721. svr.stop();
  20722. if (t.joinable()) { t.join(); }
  20723. });
  20724. svr.wait_until_ready();
  20725. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20726. std::to_string(port) + "/ws");
  20727. client.set_hostname_addr_map({{host, HOST}});
  20728. ASSERT_TRUE(client.connect());
  20729. EXPECT_TRUE(client.is_open());
  20730. client.close();
  20731. svr.stop();
  20732. t.join();
  20733. // The mapping only redirects the connection; the identity stays host_.
  20734. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20735. }
  20736. class WebSocketIntegrationTest : public ::testing::Test {
  20737. protected:
  20738. void SetUp() override {
  20739. server_ = httplib::detail::make_unique<Server>();
  20740. setup_server();
  20741. start_server();
  20742. }
  20743. void TearDown() override {
  20744. server_->stop();
  20745. if (server_thread_.joinable()) { server_thread_.join(); }
  20746. }
  20747. void setup_server() {
  20748. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20749. std::string msg;
  20750. ws::ReadResult ret;
  20751. while ((ret = ws.read(msg))) {
  20752. if (ret == ws::Binary) {
  20753. ws.send(msg.data(), msg.size());
  20754. } else {
  20755. ws.send(msg);
  20756. }
  20757. }
  20758. });
  20759. server_->WebSocket("/ws-echo-string",
  20760. [](const Request &, ws::WebSocket &ws) {
  20761. std::string msg;
  20762. while (ws.read(msg)) {
  20763. ws.send("echo: " + msg);
  20764. }
  20765. });
  20766. server_->WebSocket(
  20767. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20768. // Echo back request metadata
  20769. ws.send("path:" + req.path);
  20770. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20771. std::string msg;
  20772. while (ws.read(msg)) {}
  20773. });
  20774. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20775. std::string msg;
  20776. ws.read(msg); // wait for a message
  20777. ws.close();
  20778. });
  20779. server_->WebSocket("/ws-close-status",
  20780. [](const Request &, ws::WebSocket &ws) {
  20781. std::string msg;
  20782. ws.read(msg); // wait for a message
  20783. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20784. });
  20785. server_->WebSocket(
  20786. "/ws-subprotocol",
  20787. [](const Request &, ws::WebSocket &ws) {
  20788. std::string msg;
  20789. while (ws.read(msg)) {
  20790. ws.send(msg);
  20791. }
  20792. },
  20793. [](const std::vector<std::string> &protocols) -> std::string {
  20794. for (const auto &p : protocols) {
  20795. if (p == "graphql-ws") { return p; }
  20796. }
  20797. return "";
  20798. });
  20799. server_->WebSocket(
  20800. "/ws-subprotocol-unoffered",
  20801. [](const Request &, ws::WebSocket &ws) {
  20802. std::string msg;
  20803. while (ws.read(msg)) {
  20804. ws.send(msg);
  20805. }
  20806. },
  20807. [](const std::vector<std::string> &) -> std::string {
  20808. return "admin";
  20809. });
  20810. }
  20811. void start_server() {
  20812. port_ = server_->bind_to_any_port(HOST);
  20813. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20814. server_->wait_until_ready();
  20815. }
  20816. std::unique_ptr<Server> server_;
  20817. std::thread server_thread_;
  20818. int port_ = 0;
  20819. };
  20820. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20821. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20822. "/ws-echo");
  20823. ASSERT_TRUE(client.connect());
  20824. ASSERT_TRUE(client.is_open());
  20825. ASSERT_TRUE(client.send("Hello WebSocket"));
  20826. std::string msg;
  20827. EXPECT_EQ(ws::Text, client.read(msg));
  20828. EXPECT_EQ("Hello WebSocket", msg);
  20829. client.close();
  20830. }
  20831. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20833. "/ws-echo");
  20834. ASSERT_TRUE(client.connect());
  20835. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20836. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20837. std::string msg;
  20838. EXPECT_EQ(ws::Binary, client.read(msg));
  20839. EXPECT_EQ(binary_data, msg);
  20840. client.close();
  20841. }
  20842. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20843. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20844. "/ws-echo");
  20845. ASSERT_TRUE(client.connect());
  20846. for (int i = 0; i < 10; i++) {
  20847. auto text = "message " + std::to_string(i);
  20848. ASSERT_TRUE(client.send(text));
  20849. std::string msg;
  20850. ASSERT_TRUE(client.read(msg));
  20851. EXPECT_EQ(text, msg);
  20852. }
  20853. client.close();
  20854. }
  20855. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20857. "/ws-close");
  20858. ASSERT_TRUE(client.connect());
  20859. // Send a message to trigger the server to close
  20860. ASSERT_TRUE(client.send("trigger close"));
  20861. // The server will close, so read should return false
  20862. std::string msg;
  20863. EXPECT_FALSE(client.read(msg));
  20864. EXPECT_FALSE(client.is_open());
  20865. }
  20866. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20868. "/ws-echo");
  20869. ASSERT_TRUE(client.connect());
  20870. // 128KB message
  20871. std::string large_data(128 * 1024, 'X');
  20872. ASSERT_TRUE(client.send(large_data));
  20873. std::string msg;
  20874. ASSERT_TRUE(client.read(msg));
  20875. EXPECT_EQ(large_data, msg);
  20876. client.close();
  20877. }
  20878. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20879. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20880. "/ws-echo");
  20881. ASSERT_TRUE(client.connect());
  20882. const int num_threads = 4;
  20883. std::vector<std::thread> threads;
  20884. std::atomic<int> send_count{0};
  20885. for (int t = 0; t < num_threads; t++) {
  20886. threads.emplace_back([&client, &send_count, t]() {
  20887. for (int i = 0; i < 5; i++) {
  20888. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20889. if (client.send(text)) { send_count++; }
  20890. }
  20891. });
  20892. }
  20893. for (auto &th : threads) {
  20894. th.join();
  20895. }
  20896. int received = 0;
  20897. std::string msg;
  20898. while (received < send_count.load()) {
  20899. if (!client.read(msg)) { break; }
  20900. received++;
  20901. }
  20902. EXPECT_EQ(send_count.load(), received);
  20903. client.close();
  20904. }
  20905. TEST_F(WebSocketIntegrationTest, ReadString) {
  20906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20907. "/ws-echo-string");
  20908. ASSERT_TRUE(client.connect());
  20909. ASSERT_TRUE(client.send("hello"));
  20910. std::string msg;
  20911. ASSERT_TRUE(client.read(msg));
  20912. EXPECT_EQ("echo: hello", msg);
  20913. ASSERT_TRUE(client.send("world"));
  20914. ASSERT_TRUE(client.read(msg));
  20915. EXPECT_EQ("echo: world", msg);
  20916. client.close();
  20917. }
  20918. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20919. Headers headers = {{"X-Test-Header", "test-value"}};
  20920. ws::WebSocketClient client(
  20921. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20922. ASSERT_TRUE(client.connect());
  20923. std::string msg;
  20924. ASSERT_TRUE(client.read(msg));
  20925. EXPECT_EQ("path:/ws-request-info", msg);
  20926. ASSERT_TRUE(client.read(msg));
  20927. EXPECT_EQ("header:test-value", msg);
  20928. client.close();
  20929. }
  20930. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20931. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20932. "/ws-echo");
  20933. client.set_read_timeout(1, 0); // 1 second
  20934. ASSERT_TRUE(client.connect());
  20935. // Don't send anything — server echo handler waits for a message, so read()
  20936. // should time out. The connection survives it: nothing was consumed.
  20937. std::string msg;
  20938. EXPECT_EQ(client.read(msg), ws::Timeout);
  20939. EXPECT_TRUE(client.is_open());
  20940. // And it is still usable afterwards.
  20941. EXPECT_TRUE(client.send("after timeout"));
  20942. EXPECT_EQ(client.read(msg), ws::Text);
  20943. EXPECT_EQ(msg, "after timeout");
  20944. }
  20945. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20946. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20947. "/ws-echo");
  20948. client.set_read_timeout(1, 0);
  20949. ASSERT_TRUE(client.connect());
  20950. ASSERT_TRUE(client.send("first"));
  20951. std::string msg;
  20952. ASSERT_EQ(client.read(msg), ws::Text);
  20953. ASSERT_EQ(msg, "first");
  20954. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20955. // not be used with a read timeout: it would reprocess the previous message.
  20956. EXPECT_EQ(client.read(msg), ws::Timeout);
  20957. EXPECT_EQ(msg, "first");
  20958. }
  20959. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20960. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20961. "/ws-echo");
  20962. ASSERT_TRUE(client.connect());
  20963. // Setting it once the connection is open reaches the live stream, not just
  20964. // the seed for the next connect().
  20965. client.set_read_timeout(1, 0);
  20966. std::string msg;
  20967. EXPECT_EQ(client.read(msg), ws::Timeout);
  20968. EXPECT_TRUE(client.is_open());
  20969. }
  20970. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20972. "/ws-echo");
  20973. client.set_read_timeout(5, 0);
  20974. ASSERT_TRUE(client.connect());
  20975. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20976. // The server should reject it and close the connection.
  20977. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20978. client.send(oversized);
  20979. // The server's read() should have failed due to payload limit,
  20980. // so our read() should return false (connection closed).
  20981. std::string msg;
  20982. EXPECT_FALSE(client.read(msg));
  20983. }
  20984. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20985. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20986. "/ws-echo");
  20987. client.set_read_timeout(10, 0);
  20988. ASSERT_TRUE(client.connect());
  20989. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20990. // This should succeed.
  20991. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20992. ASSERT_TRUE(client.send(at_limit));
  20993. std::string msg;
  20994. ASSERT_TRUE(client.read(msg));
  20995. EXPECT_EQ(at_limit.size(), msg.size());
  20996. client.close();
  20997. }
  20998. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20999. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21000. "/nonexistent");
  21001. auto res = client.connect();
  21002. EXPECT_FALSE(res);
  21003. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21004. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21005. EXPECT_FALSE(client.is_open());
  21006. }
  21007. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21008. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21009. "/ws-echo");
  21010. ASSERT_TRUE(client.connect());
  21011. ASSERT_TRUE(client.send(""));
  21012. std::string msg;
  21013. EXPECT_EQ(ws::Text, client.read(msg));
  21014. EXPECT_EQ("", msg);
  21015. client.close();
  21016. }
  21017. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21019. "/ws-echo");
  21020. // First connection
  21021. ASSERT_TRUE(client.connect());
  21022. ASSERT_TRUE(client.send("first"));
  21023. std::string msg;
  21024. ASSERT_TRUE(client.read(msg));
  21025. EXPECT_EQ("first", msg);
  21026. client.close();
  21027. EXPECT_FALSE(client.is_open());
  21028. // Reconnect using the same client object
  21029. ASSERT_TRUE(client.connect());
  21030. ASSERT_TRUE(client.is_open());
  21031. ASSERT_TRUE(client.send("second"));
  21032. ASSERT_TRUE(client.read(msg));
  21033. EXPECT_EQ("second", msg);
  21034. client.close();
  21035. }
  21036. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21038. "/ws-close-status");
  21039. ASSERT_TRUE(client.connect());
  21040. // Trigger the server to close with GoingAway status
  21041. ASSERT_TRUE(client.send("trigger"));
  21042. // read() should return false after receiving the close frame
  21043. std::string msg;
  21044. EXPECT_FALSE(client.read(msg));
  21045. EXPECT_FALSE(client.is_open());
  21046. }
  21047. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21048. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21049. "/ws-echo");
  21050. ASSERT_TRUE(client.connect());
  21051. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21052. EXPECT_FALSE(client.is_open());
  21053. }
  21054. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21055. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21056. ws::WebSocketClient client(
  21057. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21058. ASSERT_TRUE(client.connect());
  21059. // Server should have selected graphql-ws
  21060. EXPECT_EQ("graphql-ws", client.subprotocol());
  21061. client.close();
  21062. }
  21063. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21064. Headers headers;
  21065. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21066. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21067. ws::WebSocketClient client(
  21068. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21069. ASSERT_TRUE(client.connect());
  21070. // The offer on the second field line counts too, so graphql-ws is selected
  21071. EXPECT_EQ("graphql-ws", client.subprotocol());
  21072. client.close();
  21073. }
  21074. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21075. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21076. ws::WebSocketClient client(
  21077. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21078. ASSERT_TRUE(client.connect());
  21079. // Server should not have selected any subprotocol
  21080. EXPECT_TRUE(client.subprotocol().empty());
  21081. client.close();
  21082. }
  21083. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21084. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21086. "/ws-subprotocol-unoffered",
  21087. headers);
  21088. ASSERT_TRUE(client.connect());
  21089. EXPECT_TRUE(client.subprotocol().empty());
  21090. client.close();
  21091. }
  21092. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21093. // Connect without requesting any subprotocol
  21094. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21095. "/ws-subprotocol");
  21096. ASSERT_TRUE(client.connect());
  21097. EXPECT_TRUE(client.subprotocol().empty());
  21098. client.close();
  21099. }
  21100. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21101. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21102. "/ws-echo");
  21103. client.set_tcp_nodelay(true);
  21104. client.set_connection_timeout(3, 0);
  21105. bool socket_options_called = false;
  21106. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21107. ASSERT_TRUE(client.connect());
  21108. ASSERT_TRUE(client.is_open());
  21109. EXPECT_TRUE(socket_options_called);
  21110. ASSERT_TRUE(client.send("hello"));
  21111. std::string msg;
  21112. auto result = client.read(msg);
  21113. EXPECT_EQ(result, ws::ReadResult::Text);
  21114. EXPECT_EQ(msg, "hello");
  21115. client.close();
  21116. }
  21117. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21118. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21119. "/ws-echo");
  21120. client.set_connection_timeout(std::chrono::seconds(3));
  21121. client.set_write_timeout(std::chrono::seconds(3));
  21122. // A sub-second remainder exercises the seconds/microseconds split.
  21123. client.set_read_timeout(std::chrono::milliseconds(1500));
  21124. ASSERT_TRUE(client.connect());
  21125. auto start = std::chrono::steady_clock::now();
  21126. std::string msg;
  21127. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21128. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21129. std::chrono::steady_clock::now() - start)
  21130. .count();
  21131. // Above 1s so that dropping the microseconds half of the split fails here.
  21132. // Ignoring the setter altogether would not reach this line at all: a client
  21133. // waits forever by default.
  21134. EXPECT_GE(elapsed, 1400);
  21135. EXPECT_LT(elapsed, 30000);
  21136. }
  21137. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21138. Server svr;
  21139. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21140. if (!req.has_header("Authorization")) {
  21141. res.status = StatusCode::Unauthorized_401;
  21142. res.set_content("Unauthorized", "text/plain");
  21143. return Server::HandlerResponse::Handled;
  21144. }
  21145. return Server::HandlerResponse::Unhandled;
  21146. });
  21147. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21148. std::string msg;
  21149. while (ws.read(msg)) {
  21150. ws.send(msg);
  21151. }
  21152. });
  21153. auto port = svr.bind_to_any_port("localhost");
  21154. std::thread t([&]() { svr.listen_after_bind(); });
  21155. svr.wait_until_ready();
  21156. // Without Authorization header - should be rejected before upgrade
  21157. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21158. EXPECT_FALSE(client1.connect());
  21159. // The rejection is framed like any other HTTP response
  21160. {
  21161. Client cli("localhost", port);
  21162. Headers headers = {{"Upgrade", "websocket"},
  21163. {"Connection", "Upgrade"},
  21164. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21165. {"Sec-WebSocket-Version", "13"}};
  21166. auto res = cli.Get("/ws", headers);
  21167. ASSERT_TRUE(res);
  21168. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21169. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21170. EXPECT_EQ("Unauthorized", res->body);
  21171. }
  21172. // With Authorization header - should succeed
  21173. Headers headers = {{"Authorization", "Bearer token123"}};
  21174. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21175. headers);
  21176. ASSERT_TRUE(client2.connect());
  21177. ASSERT_TRUE(client2.send("hello"));
  21178. std::string msg;
  21179. ASSERT_TRUE(client2.read(msg));
  21180. EXPECT_EQ("hello", msg);
  21181. client2.close();
  21182. svr.stop();
  21183. t.join();
  21184. }
  21185. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21186. Server svr;
  21187. std::atomic<int> pre_request_calls{0};
  21188. std::atomic<bool> route_matched{false};
  21189. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21190. pre_request_calls++;
  21191. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21192. if (req.get_header_value("Authorization") != "Bearer token123") {
  21193. res.status = StatusCode::Unauthorized_401;
  21194. res.set_content("Unauthorized", "text/plain");
  21195. return Server::HandlerResponse::Handled;
  21196. }
  21197. return Server::HandlerResponse::Unhandled;
  21198. });
  21199. std::atomic<bool> handler_called{false};
  21200. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21201. handler_called = true;
  21202. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21203. });
  21204. auto port = svr.bind_to_any_port("localhost");
  21205. std::thread t([&]() { svr.listen_after_bind(); });
  21206. svr.wait_until_ready();
  21207. // Without Authorization header - should be rejected before upgrade
  21208. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21209. "/ws/1");
  21210. EXPECT_FALSE(client1.connect());
  21211. EXPECT_FALSE(handler_called);
  21212. EXPECT_EQ(1, pre_request_calls);
  21213. EXPECT_TRUE(route_matched);
  21214. // The rejection is an ordinary HTTP response, not a protocol switch
  21215. {
  21216. Client cli("localhost", port);
  21217. Headers headers = {{"Upgrade", "websocket"},
  21218. {"Connection", "Upgrade"},
  21219. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21220. {"Sec-WebSocket-Version", "13"}};
  21221. auto res = cli.Get("/ws/1", headers);
  21222. ASSERT_TRUE(res);
  21223. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21224. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21225. EXPECT_EQ("Unauthorized", res->body);
  21226. }
  21227. EXPECT_FALSE(handler_called);
  21228. // With Authorization header - should succeed
  21229. Headers headers = {{"Authorization", "Bearer token123"}};
  21230. ws::WebSocketClient client2(
  21231. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21232. ASSERT_TRUE(client2.connect());
  21233. std::string msg;
  21234. ASSERT_TRUE(client2.read(msg));
  21235. EXPECT_EQ("/ws/:id 2", msg);
  21236. EXPECT_TRUE(handler_called);
  21237. client2.close();
  21238. svr.stop();
  21239. t.join();
  21240. }
  21241. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21242. Server svr;
  21243. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21244. // A read timeout is how a handler gets control back. Without it, a handler
  21245. // parked in read() can never write on the connection it is reading.
  21246. ws.set_read_timeout(std::chrono::milliseconds(100));
  21247. std::string msg;
  21248. while (ws.is_open()) {
  21249. auto r = ws.read(msg);
  21250. if (r == httplib::ws::Timeout) {
  21251. ws.send("tick");
  21252. continue;
  21253. }
  21254. if (r == httplib::ws::Fail) { break; }
  21255. ws.send(msg);
  21256. }
  21257. });
  21258. auto port = svr.bind_to_any_port("localhost");
  21259. std::thread t([&]() { svr.listen_after_bind(); });
  21260. svr.wait_until_ready();
  21261. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21262. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21263. ASSERT_TRUE(client.connect());
  21264. // The client sends nothing, so anything it receives came out of the
  21265. // handler's timeout path.
  21266. std::string msg;
  21267. ASSERT_EQ(client.read(msg), ws::Text);
  21268. EXPECT_EQ("tick", msg);
  21269. client.close();
  21270. svr.stop();
  21271. t.join();
  21272. }
  21273. // Stream::read may return fewer bytes than asked for. This is that contract at
  21274. // its worst -- one byte per call -- which is what a frame header straddling a
  21275. // read buffer's boundary looks like to the frame parser.
  21276. class WsByteAtATimeStream : public Stream {
  21277. public:
  21278. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21279. bool is_readable() const override { return true; }
  21280. bool wait_readable() const override { return true; }
  21281. bool wait_writable() const override { return true; }
  21282. ssize_t read(char *ptr, size_t size) override {
  21283. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21284. *ptr = data_[pos_++];
  21285. return 1;
  21286. }
  21287. ssize_t write(const char *, size_t size) override {
  21288. return static_cast<ssize_t>(size);
  21289. }
  21290. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21291. ip = "127.0.0.1";
  21292. port = 0;
  21293. }
  21294. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21295. ip = "127.0.0.1";
  21296. port = 0;
  21297. }
  21298. socket_t socket() const override { return INVALID_SOCKET; }
  21299. time_t duration() const override { return 0; }
  21300. private:
  21301. std::string data_;
  21302. size_t pos_ = 0;
  21303. };
  21304. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21305. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21306. // length and the mask key are all multi-byte fields here. Each used to be
  21307. // read with a single read() call, which fails as soon as one is split.
  21308. std::string body(200, 'x');
  21309. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21310. std::string frame;
  21311. frame += static_cast<char>(0x81); // FIN + Text
  21312. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21313. frame += static_cast<char>(body.size() >> 8);
  21314. frame += static_cast<char>(body.size() & 0xff);
  21315. for (size_t i = 0; i < 4; i++) {
  21316. frame += static_cast<char>(mask[i]);
  21317. }
  21318. for (size_t i = 0; i < body.size(); i++) {
  21319. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21320. }
  21321. WsByteAtATimeStream strm(frame);
  21322. ws::Opcode opcode;
  21323. std::string payload;
  21324. bool fin = false;
  21325. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21326. /*expect_masked=*/true, 1024),
  21327. ws::impl::FrameRead::Ok);
  21328. EXPECT_TRUE(fin);
  21329. EXPECT_EQ(opcode, ws::Opcode::Text);
  21330. EXPECT_EQ(payload, body);
  21331. }
  21332. TEST(WebSocketTest, QueryStringInHandshake) {
  21333. Server svr;
  21334. std::mutex mtx;
  21335. std::string received_target;
  21336. std::string received_token;
  21337. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21338. {
  21339. std::lock_guard<std::mutex> lock(mtx);
  21340. received_target = req.target;
  21341. if (req.has_param("token")) {
  21342. received_token = req.get_param_value("token");
  21343. }
  21344. }
  21345. std::string msg;
  21346. while (ws.read(msg)) {
  21347. ws.send(msg);
  21348. }
  21349. });
  21350. auto port = svr.bind_to_any_port("localhost");
  21351. std::thread t([&]() { svr.listen_after_bind(); });
  21352. svr.wait_until_ready();
  21353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21354. "/ws?token=ABC&session=123");
  21355. ASSERT_TRUE(client.connect());
  21356. // Round-trip ensures the handler has run and captured the request.
  21357. ASSERT_TRUE(client.send("hello"));
  21358. std::string msg;
  21359. ASSERT_TRUE(client.read(msg));
  21360. EXPECT_EQ("hello", msg);
  21361. client.close();
  21362. {
  21363. std::lock_guard<std::mutex> lock(mtx);
  21364. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21365. EXPECT_EQ("ABC", received_token);
  21366. }
  21367. svr.stop();
  21368. t.join();
  21369. }
  21370. // Run a handshake against a throwaway server and hand the request the server
  21371. // received back to the caller, so tests can assert on the headers the client
  21372. // actually put on the wire.
  21373. static void capture_websocket_handshake_request(
  21374. const Headers &client_headers,
  21375. std::function<void(const Request &, int port)> verify) {
  21376. Server svr;
  21377. std::mutex mtx;
  21378. Request received;
  21379. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21380. {
  21381. std::lock_guard<std::mutex> lock(mtx);
  21382. received = req;
  21383. }
  21384. std::string msg;
  21385. while (ws.read(msg)) {
  21386. ws.send(msg);
  21387. }
  21388. });
  21389. auto port = svr.bind_to_any_port("localhost");
  21390. std::thread t([&]() { svr.listen_after_bind(); });
  21391. auto se = detail::scope_exit([&] {
  21392. svr.stop();
  21393. t.join();
  21394. });
  21395. svr.wait_until_ready();
  21396. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21397. client_headers);
  21398. ASSERT_TRUE(client.connect());
  21399. ASSERT_TRUE(client.send("hello"));
  21400. std::string msg;
  21401. ASSERT_TRUE(client.read(msg));
  21402. client.close();
  21403. {
  21404. std::lock_guard<std::mutex> lock(mtx);
  21405. verify(received, port);
  21406. }
  21407. }
  21408. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21409. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21410. // Non-default port must be present in the Host header. Default ports
  21411. // (80/443) are omitted; that logic is covered by
  21412. // MakeHostAndPortStringTest.
  21413. EXPECT_EQ("localhost:" + std::to_string(port),
  21414. req.get_header_value("Host"));
  21415. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21416. req.get_header_value("User-Agent"));
  21417. EXPECT_FALSE(req.has_header("Accept"));
  21418. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21419. EXPECT_FALSE(req.has_header("Content-Length"));
  21420. });
  21421. }
  21422. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21423. capture_websocket_handshake_request(
  21424. {{"Host", "example.com"},
  21425. {"User-Agent", "custom-agent"},
  21426. {"X-Custom", "value"}},
  21427. [](const Request &req, int) {
  21428. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21429. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21430. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21431. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21432. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21433. });
  21434. }
  21435. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21436. capture_websocket_handshake_request(
  21437. {{"Upgrade", "bogus"},
  21438. {"Connection", "close"},
  21439. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21440. {"Sec-WebSocket-Version", "8"}},
  21441. [](const Request &req, int) {
  21442. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21443. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21444. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21445. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21446. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21447. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21448. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21449. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21450. req.get_header_value("Sec-WebSocket-Key"));
  21451. });
  21452. }
  21453. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21454. // A header the client refuses to send must abort the handshake before any
  21455. // part of it reaches the wire; a lone request line would otherwise sit in
  21456. // the peer's buffer as a truncated request.
  21457. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21458. ASSERT_NE(INVALID_SOCKET, srv);
  21459. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21460. sockaddr_in addr{};
  21461. addr.sin_family = AF_INET;
  21462. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21463. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21464. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21465. ASSERT_EQ(0, ::listen(srv, 1));
  21466. sockaddr_in bound{};
  21467. socklen_t bound_len = sizeof(bound);
  21468. ASSERT_EQ(
  21469. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21470. auto port = ntohs(bound.sin_port);
  21471. ssize_t received = -1;
  21472. std::thread t([&] {
  21473. // Bound every blocking call so a regression fails the test with a bad
  21474. // value instead of hanging the suite.
  21475. fd_set rfds;
  21476. FD_ZERO(&rfds);
  21477. FD_SET(srv, &rfds);
  21478. timeval tv{5, 0};
  21479. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21480. 0) {
  21481. return;
  21482. }
  21483. sockaddr_in cli_addr{};
  21484. socklen_t cli_len = sizeof(cli_addr);
  21485. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21486. if (cli == INVALID_SOCKET) { return; }
  21487. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21489. char buf[4096];
  21490. received = ::recv(cli, buf, sizeof(buf), 0);
  21491. });
  21492. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21493. // connect() has already shut the socket down by the time it returns false,
  21494. // so the peer sees EOF without waiting for the client to be destroyed.
  21495. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21496. {{"X-Bad", "a\r\nInjected: 1"}});
  21497. EXPECT_FALSE(client.connect());
  21498. t.join();
  21499. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21500. EXPECT_EQ(0, received);
  21501. }
  21502. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21503. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21504. // contains "upgrade" as a substring is a different token and must not
  21505. // start a WebSocket handshake.
  21506. auto make_request = [](const std::vector<std::string> &connection_values) {
  21507. Request req;
  21508. req.method = "GET";
  21509. req.headers.emplace("Upgrade", "websocket");
  21510. for (const auto &value : connection_values) {
  21511. req.headers.emplace("Connection", value);
  21512. }
  21513. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21514. req.headers.emplace("Sec-WebSocket-Version", "13");
  21515. return req;
  21516. };
  21517. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21518. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21519. EXPECT_TRUE(
  21520. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21521. EXPECT_TRUE(
  21522. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21523. EXPECT_TRUE(
  21524. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21525. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21526. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21527. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21528. EXPECT_FALSE(
  21529. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21530. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21531. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21532. }
  21533. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21534. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21535. // asks recipients to match each protocol-name case-insensitively, and RFC
  21536. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21537. // client naming websocket alongside another protocol, or on a second field
  21538. // line, is offering websocket; a value that merely contains "websocket" as a
  21539. // substring is a different protocol name and is not.
  21540. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21541. Request req;
  21542. req.method = "GET";
  21543. for (const auto &value : upgrade_values) {
  21544. req.headers.emplace("Upgrade", value);
  21545. }
  21546. req.headers.emplace("Connection", "Upgrade");
  21547. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21548. req.headers.emplace("Sec-WebSocket-Version", "13");
  21549. return req;
  21550. };
  21551. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21552. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21553. EXPECT_TRUE(
  21554. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21555. EXPECT_TRUE(
  21556. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21557. EXPECT_TRUE(
  21558. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21559. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21560. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21561. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21562. EXPECT_FALSE(
  21563. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21564. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21565. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21566. }
  21567. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21568. Server svr;
  21569. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21570. auto port = svr.bind_to_any_port("localhost");
  21571. std::thread t([&]() { svr.listen_after_bind(); });
  21572. auto se = detail::scope_exit([&] {
  21573. svr.stop();
  21574. t.join();
  21575. });
  21576. svr.wait_until_ready();
  21577. Headers headers = {{"Upgrade", "websocket"},
  21578. {"Connection", "notupgrade"},
  21579. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21580. {"Sec-WebSocket-Version", "13"}};
  21581. Client cli("localhost", port);
  21582. auto res = cli.Get("/ws", headers);
  21583. // The route exists only as a WebSocket route, so a request that fails the
  21584. // handshake check falls through to ordinary routing.
  21585. ASSERT_TRUE(res);
  21586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21587. }
  21588. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21589. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21590. // Connection value is the only thing left for the client to reject.
  21591. Server svr;
  21592. svr.Get("/ws", [](const Request &req, Response &res) {
  21593. res.status = StatusCode::SwitchingProtocol_101;
  21594. res.set_header("Upgrade", "websocket");
  21595. res.set_header("Connection", "notupgrade");
  21596. res.set_header("Sec-WebSocket-Accept",
  21597. detail::websocket_accept_key(
  21598. req.get_header_value("Sec-WebSocket-Key")));
  21599. });
  21600. auto port = svr.bind_to_any_port("localhost");
  21601. std::thread t([&]() { svr.listen_after_bind(); });
  21602. auto se = detail::scope_exit([&] {
  21603. svr.stop();
  21604. t.join();
  21605. });
  21606. svr.wait_until_ready();
  21607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21608. auto res = client.connect();
  21609. EXPECT_FALSE(res);
  21610. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21611. EXPECT_FALSE(client.is_open());
  21612. }
  21613. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21614. Server svr;
  21615. svr.Get("/ws", [](const Request &req, Response &res) {
  21616. res.status = StatusCode::SwitchingProtocol_101;
  21617. res.set_header("Upgrade", "websocket");
  21618. res.set_header("Connection", "Upgrade");
  21619. res.set_header("Sec-WebSocket-Accept",
  21620. detail::websocket_accept_key(
  21621. req.get_header_value("Sec-WebSocket-Key")));
  21622. res.set_header("Sec-WebSocket-Protocol", "admin");
  21623. });
  21624. auto port = svr.bind_to_any_port("localhost");
  21625. std::thread t([&]() { svr.listen_after_bind(); });
  21626. auto se = detail::scope_exit([&] {
  21627. svr.stop();
  21628. t.join();
  21629. });
  21630. svr.wait_until_ready();
  21631. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21632. // Server selects a subprotocol the client never offered
  21633. {
  21634. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21635. ws::WebSocketClient client(url, headers);
  21636. auto res = client.connect();
  21637. EXPECT_FALSE(res);
  21638. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21639. EXPECT_FALSE(client.is_open());
  21640. EXPECT_TRUE(client.subprotocol().empty());
  21641. }
  21642. // Client offered none but the server named one anyway
  21643. {
  21644. ws::WebSocketClient client(url);
  21645. auto res = client.connect();
  21646. EXPECT_FALSE(res);
  21647. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21648. EXPECT_FALSE(client.is_open());
  21649. EXPECT_TRUE(client.subprotocol().empty());
  21650. }
  21651. }
  21652. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21653. // The socket path doubles as the URL host, so it must not contain '/'.
  21654. const char *shard = getenv("GTEST_SHARD_INDEX");
  21655. const std::string sock_path =
  21656. shard ? std::string("httplib-ws-") + shard + ".sock"
  21657. : std::string("httplib-ws.sock");
  21658. std::remove(sock_path.c_str());
  21659. Server svr;
  21660. std::mutex mtx;
  21661. std::string received_host;
  21662. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21663. {
  21664. std::lock_guard<std::mutex> lock(mtx);
  21665. received_host = req.get_header_value("Host");
  21666. }
  21667. std::string msg;
  21668. while (ws.read(msg)) {
  21669. ws.send(msg);
  21670. }
  21671. });
  21672. svr.set_address_family(AF_UNIX);
  21673. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21674. auto se = detail::scope_exit([&] {
  21675. svr.stop();
  21676. t.join();
  21677. std::remove(sock_path.c_str());
  21678. });
  21679. svr.wait_until_ready();
  21680. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21681. client.set_address_family(AF_UNIX);
  21682. ASSERT_TRUE(client.connect());
  21683. ASSERT_TRUE(client.send("hello"));
  21684. std::string msg;
  21685. ASSERT_TRUE(client.read(msg));
  21686. client.close();
  21687. {
  21688. std::lock_guard<std::mutex> lock(mtx);
  21689. // There is no host:port for a Unix socket, so the same "localhost"
  21690. // placeholder the HTTP client uses is expected.
  21691. EXPECT_EQ("localhost", received_host);
  21692. }
  21693. }
  21694. // Two threads must never parse WebSocket frames from the same stream.
  21695. // close() used to read the peer's Close reply with its own frame read, so it
  21696. // raced a reader thread that was in the middle of a payload: the payload loop
  21697. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21698. // so bytes taken by close() were replaced with bytes from further along the
  21699. // stream. The message kept its length and silently changed content.
  21700. //
  21701. // The raw peer below sends a frame header plus part of the payload, waits for
  21702. // the handler to call close(), and only then sends the rest. Whichever thread
  21703. // would win the race for those bytes, the message must arrive intact, because
  21704. // close() must not touch the stream while read() owns it.
  21705. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21706. #ifndef _WIN32
  21707. signal(SIGPIPE, SIG_IGN);
  21708. #endif
  21709. const size_t payload_len = 120; // fits the 7-bit length field
  21710. const size_t prefix_len = 8;
  21711. const int attempts = 8;
  21712. std::string expected(payload_len, '\0');
  21713. for (size_t i = 0; i < payload_len; i++) {
  21714. expected[i] = static_cast<char>('a' + i % 26);
  21715. }
  21716. std::atomic<bool> peer_stalled{false};
  21717. std::atomic<bool> handler_done{false};
  21718. std::mutex received_mutex;
  21719. std::vector<std::string> received;
  21720. // Bound every wait, so a regression fails the test instead of hanging the
  21721. // suite.
  21722. auto wait_for = [](const std::atomic<bool> &flag) {
  21723. for (int i = 0; i < 500 && !flag; i++) {
  21724. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21725. }
  21726. };
  21727. Server svr;
  21728. svr.set_websocket_ping_interval(0);
  21729. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21730. std::thread reader([&]() {
  21731. std::string msg;
  21732. while (ws.read(msg)) {
  21733. std::lock_guard<std::mutex> guard(received_mutex);
  21734. received.push_back(msg);
  21735. }
  21736. });
  21737. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21738. // inside read_websocket_frame() when close() runs.
  21739. wait_for(peer_stalled);
  21740. ws.close();
  21741. reader.join();
  21742. handler_done = true;
  21743. });
  21744. auto port = svr.bind_to_any_port("127.0.0.1");
  21745. std::thread t([&]() { svr.listen_after_bind(); });
  21746. auto se = detail::scope_exit([&] {
  21747. svr.stop();
  21748. t.join();
  21749. });
  21750. svr.wait_until_ready();
  21751. auto send_bytes = [](socket_t s, const std::string &data) {
  21752. #ifdef _WIN32
  21753. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21754. #else
  21755. auto n = ::send(s, data.data(), data.size(), 0);
  21756. #endif
  21757. return n == static_cast<decltype(n)>(data.size());
  21758. };
  21759. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21760. // Every length used here fits the 7-bit length field.
  21761. auto masked_header = [](uint8_t first_byte, size_t len) {
  21762. std::string h;
  21763. h += static_cast<char>(first_byte);
  21764. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21765. h.append(4, '\0'); // mask key
  21766. return h;
  21767. };
  21768. for (int attempt = 0; attempt < attempts; attempt++) {
  21769. peer_stalled = false;
  21770. handler_done = false;
  21771. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21772. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21773. auto se_sock = detail::scope_exit([&] {
  21774. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21775. });
  21776. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21777. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21778. sockaddr_in addr{};
  21779. addr.sin_family = AF_INET;
  21780. addr.sin_port = htons(static_cast<uint16_t>(port));
  21781. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21782. ASSERT_EQ(
  21783. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21784. << "attempt " << attempt;
  21785. ASSERT_TRUE(send_bytes(sock,
  21786. "GET /ws HTTP/1.1\r\n"
  21787. "Host: 127.0.0.1\r\n"
  21788. "Upgrade: websocket\r\n"
  21789. "Connection: Upgrade\r\n"
  21790. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21791. "Sec-WebSocket-Version: 13\r\n"
  21792. "\r\n"))
  21793. << "attempt " << attempt;
  21794. std::string response;
  21795. while (response.find("\r\n\r\n") == std::string::npos) {
  21796. char buf[512];
  21797. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21798. if (n <= 0) { break; }
  21799. response.append(buf, static_cast<size_t>(n));
  21800. }
  21801. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21802. << "attempt " << attempt;
  21803. // Send the header of a Binary message but only the first prefix_len bytes
  21804. // of its payload, leaving the reader thread stalled inside the payload.
  21805. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21806. expected.substr(0, prefix_len)))
  21807. << "attempt " << attempt;
  21808. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21809. peer_stalled = true;
  21810. // Let close() send its Close frame and park in its own read before the
  21811. // rest of the payload arrives, so both threads are waiting for it.
  21812. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21813. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21814. close_frame += static_cast<char>(0x03); // status 1000
  21815. close_frame += static_cast<char>(0xE8);
  21816. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21817. << "attempt " << attempt;
  21818. // Closing the peer releases the reader thread even on the buggy path,
  21819. // where it waits for bytes another thread already consumed.
  21820. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21821. detail::close_socket(sock);
  21822. sock = INVALID_SOCKET;
  21823. wait_for(handler_done);
  21824. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21825. }
  21826. std::lock_guard<std::mutex> guard(received_mutex);
  21827. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21828. << "a message in flight when close() ran was dropped";
  21829. for (size_t i = 0; i < received.size(); i++) {
  21830. EXPECT_EQ(expected, received[i]) << "message " << i;
  21831. }
  21832. }
  21833. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21834. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21835. protected:
  21836. void SetUp() override {
  21837. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21838. SERVER_PRIVATE_KEY_FILE);
  21839. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21840. std::string msg;
  21841. ws::ReadResult ret;
  21842. while ((ret = ws.read(msg))) {
  21843. if (ret == ws::Binary) {
  21844. ws.send(msg.data(), msg.size());
  21845. } else {
  21846. ws.send(msg);
  21847. }
  21848. }
  21849. });
  21850. port_ = server_->bind_to_any_port(HOST);
  21851. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21852. server_->wait_until_ready();
  21853. }
  21854. void TearDown() override {
  21855. server_->stop();
  21856. if (server_thread_.joinable()) { server_thread_.join(); }
  21857. }
  21858. std::unique_ptr<SSLServer> server_;
  21859. std::thread server_thread_;
  21860. int port_ = 0;
  21861. };
  21862. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21863. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21864. "/ws-echo");
  21865. client.enable_server_certificate_verification(false);
  21866. ASSERT_TRUE(client.connect());
  21867. ASSERT_TRUE(client.is_open());
  21868. ASSERT_TRUE(client.send("Hello WSS"));
  21869. std::string msg;
  21870. EXPECT_EQ(ws::Text, client.read(msg));
  21871. EXPECT_EQ("Hello WSS", msg);
  21872. client.close();
  21873. }
  21874. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21875. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21876. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21877. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21878. // client (without calling close() first) is the only path that runs
  21879. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21880. // bug exactly.
  21881. //
  21882. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21883. // when linked against an instrumented libssl; run under Valgrind to catch it
  21884. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21885. // suite (the freed session otherwise stalls on the close handshake) — this test
  21886. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21887. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21888. {
  21889. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21890. "/ws-echo");
  21891. client.enable_server_certificate_verification(false);
  21892. client.set_read_timeout(2, 0);
  21893. client.set_write_timeout(2, 0);
  21894. ASSERT_TRUE(client.connect());
  21895. ASSERT_TRUE(client.is_open());
  21896. ASSERT_TRUE(client.send("still open"));
  21897. // Intentionally do NOT call client.close(): leaving scope runs
  21898. // shutdown_and_close() with the WebSocket still open, which must send the
  21899. // close frame while the TLS session is still alive.
  21900. }
  21901. }
  21902. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21903. // shutdown_and_close() at the start of connect(), reproducing the same
  21904. // use-after-free within the test body rather than at scope exit. The second
  21905. // connect must succeed and echo, proving the close handshake ran over a live
  21906. // session. See the note above about memory-tool requirements.
  21907. TEST_F(WebSocketSSLIntegrationTest,
  21908. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21909. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21910. "/ws-echo");
  21911. client.enable_server_certificate_verification(false);
  21912. client.set_read_timeout(2, 0);
  21913. client.set_write_timeout(2, 0);
  21914. ASSERT_TRUE(client.connect());
  21915. ASSERT_TRUE(client.is_open());
  21916. ASSERT_TRUE(client.send("still open"));
  21917. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21918. // the still-open connection, which must not touch a freed TLS session.
  21919. ASSERT_TRUE(client.connect());
  21920. ASSERT_TRUE(client.is_open());
  21921. ASSERT_TRUE(client.send("after reconnect"));
  21922. std::string msg;
  21923. EXPECT_EQ(ws::Text, client.read(msg));
  21924. EXPECT_EQ("after reconnect", msg);
  21925. client.close();
  21926. }
  21927. #endif
  21928. #ifdef CPPHTTPLIB_SSL_ENABLED
  21929. class WebSocketSSLCATest : public ::testing::Test {
  21930. protected:
  21931. void SetUp() override {
  21932. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21933. SERVER_PRIVATE_KEY_FILE);
  21934. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21935. std::string msg;
  21936. while (ws.read(msg)) {
  21937. ws.send(msg);
  21938. }
  21939. });
  21940. port_ = server_->bind_to_any_port("127.0.0.1");
  21941. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21942. server_->wait_until_ready();
  21943. }
  21944. void TearDown() override {
  21945. server_->stop();
  21946. if (server_thread_.joinable()) { server_thread_.join(); }
  21947. }
  21948. std::string url() const {
  21949. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21950. }
  21951. std::unique_ptr<SSLServer> server_;
  21952. std::thread server_thread_;
  21953. int port_ = 0;
  21954. };
  21955. // A custom CA loaded as PEM verifies the server with full certificate
  21956. // verification enabled
  21957. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21958. ws::WebSocketClient client(url());
  21959. std::string cert;
  21960. read_file(SERVER_CERT2_FILE, cert);
  21961. client.load_ca_cert_store(cert.c_str(), cert.size());
  21962. ASSERT_TRUE(client.connect());
  21963. ASSERT_TRUE(client.send("hello"));
  21964. std::string msg;
  21965. EXPECT_EQ(ws::Text, client.read(msg));
  21966. EXPECT_EQ("hello", msg);
  21967. client.close();
  21968. }
  21969. // A custom CA that does not cover the server must fail verification (the
  21970. // custom CA is exclusive; system certs are not loaded alongside it)
  21971. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21972. ws::WebSocketClient client(url());
  21973. std::string cert;
  21974. read_file(CLIENT_CA_CERT_FILE, cert);
  21975. client.load_ca_cert_store(cert.c_str(), cert.size());
  21976. auto res = client.connect();
  21977. ASSERT_FALSE(res);
  21978. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21979. EXPECT_EQ(-1, res.status());
  21980. EXPECT_NE(0u, res.ssl_backend_error());
  21981. }
  21982. // The same CA as a file path rather than PEM in memory
  21983. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21984. ws::WebSocketClient client(url());
  21985. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21986. ASSERT_TRUE(client.connect());
  21987. ASSERT_TRUE(client.send("hello"));
  21988. std::string msg;
  21989. EXPECT_EQ(ws::Text, client.read(msg));
  21990. EXPECT_EQ("hello", msg);
  21991. client.close();
  21992. }
  21993. // ...and a CA file that does not cover the server still fails, so it is the
  21994. // path above that decides the outcome
  21995. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21996. ws::WebSocketClient client(url());
  21997. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21998. ASSERT_FALSE(client.connect());
  21999. }
  22000. // Regression test: reconnecting with a native custom CA store used to reuse
  22001. // a store handle the previous TLS context had already freed (use-after-free
  22002. // under the OpenSSL backend). The context now lives as long as the client.
  22003. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22004. ws::WebSocketClient client(url());
  22005. std::string cert;
  22006. read_file(SERVER_CERT2_FILE, cert);
  22007. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22008. ASSERT_TRUE(client.connect());
  22009. client.close();
  22010. ASSERT_TRUE(client.connect());
  22011. ASSERT_TRUE(client.send("again"));
  22012. std::string msg;
  22013. EXPECT_EQ(ws::Text, client.read(msg));
  22014. EXPECT_EQ("again", msg);
  22015. client.close();
  22016. }
  22017. // Regression test: a certificate with a trusted chain but no identity match
  22018. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22019. // verification entirely for IP hosts, so this connection succeeded there.
  22020. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22021. // chain verification while the identity check must still fail.
  22022. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22024. ASSERT_TRUE(svr.is_valid());
  22025. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22026. std::string msg;
  22027. while (ws.read(msg)) {
  22028. ws.send(msg);
  22029. }
  22030. });
  22031. auto port = svr.bind_to_any_port("127.0.0.1");
  22032. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22033. auto se = detail::scope_exit([&] {
  22034. svr.stop();
  22035. t.join();
  22036. });
  22037. svr.wait_until_ready();
  22038. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22039. "/echo");
  22040. std::string cert;
  22041. read_file(SERVER_CERT_FILE, cert);
  22042. client.load_ca_cert_store(cert.c_str(), cert.size());
  22043. ASSERT_FALSE(client.connect());
  22044. }
  22045. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22046. // SNI, so nothing binds the host name to the TLS session. These bind the
  22047. // server to "localhost" instead, the only shape that exercises the SNI and
  22048. // hostname-verification path with certificate verification left enabled.
  22049. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22050. protected:
  22051. void Start(const char *cert_file) {
  22052. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22053. SERVER_PRIVATE_KEY_FILE);
  22054. ASSERT_TRUE(server_->is_valid());
  22055. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22056. std::string msg;
  22057. while (ws.read(msg)) {
  22058. ws.send(msg);
  22059. }
  22060. });
  22061. port_ = server_->bind_to_any_port("localhost");
  22062. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22063. server_->wait_until_ready();
  22064. }
  22065. void TearDown() override {
  22066. if (server_) { server_->stop(); }
  22067. if (server_thread_.joinable()) { server_thread_.join(); }
  22068. }
  22069. std::string url() const {
  22070. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22071. }
  22072. std::unique_ptr<SSLServer> server_;
  22073. std::thread server_thread_;
  22074. int port_ = 0;
  22075. };
  22076. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22077. // out and the connection is usable
  22078. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22079. Start(SERVER_CERT2_FILE);
  22080. ws::WebSocketClient client(url());
  22081. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22082. ASSERT_TRUE(client.connect());
  22083. ASSERT_TRUE(client.send("hello"));
  22084. std::string msg;
  22085. EXPECT_EQ(ws::Text, client.read(msg));
  22086. EXPECT_EQ("hello", msg);
  22087. client.close();
  22088. }
  22089. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22090. // while the identity check must still reject "localhost"
  22091. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22092. Start(SERVER_CERT_FILE);
  22093. ws::WebSocketClient client(url());
  22094. client.set_ca_cert_path(SERVER_CERT_FILE);
  22095. auto res = client.connect();
  22096. ASSERT_FALSE(res);
  22097. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22098. EXPECT_EQ(-1, res.status());
  22099. }
  22100. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22101. // disabled: the chain is still checked, only the identity check is skipped
  22102. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22103. Start(SERVER_CERT_FILE);
  22104. ws::WebSocketClient client(url());
  22105. client.set_ca_cert_path(SERVER_CERT_FILE);
  22106. client.enable_server_hostname_verification(false);
  22107. ASSERT_TRUE(client.connect());
  22108. ASSERT_TRUE(client.send("hello"));
  22109. std::string msg;
  22110. EXPECT_EQ(ws::Text, client.read(msg));
  22111. EXPECT_EQ("hello", msg);
  22112. client.close();
  22113. }
  22114. // A CA that did not sign the server certificate fails the chain, even though
  22115. // the name would match
  22116. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22117. Start(SERVER_CERT2_FILE);
  22118. ws::WebSocketClient client(url());
  22119. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22120. ASSERT_FALSE(client.connect());
  22121. }
  22122. // With verification disabled, neither the chain nor the name is checked
  22123. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22124. Start(SERVER_CERT_FILE);
  22125. ws::WebSocketClient client(url());
  22126. client.enable_server_certificate_verification(false);
  22127. ASSERT_TRUE(client.connect());
  22128. ASSERT_TRUE(client.send("hello"));
  22129. std::string msg;
  22130. EXPECT_EQ(ws::Text, client.read(msg));
  22131. EXPECT_EQ("hello", msg);
  22132. client.close();
  22133. }
  22134. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22135. protected:
  22136. void SetUp() override {
  22137. server_ = httplib::detail::make_unique<SSLServer>(
  22138. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22139. ASSERT_TRUE(server_->is_valid());
  22140. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22141. std::string msg;
  22142. while (ws.read(msg)) {
  22143. ws.send(msg);
  22144. }
  22145. });
  22146. port_ = server_->bind_to_any_port("localhost");
  22147. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22148. server_->wait_until_ready();
  22149. }
  22150. void TearDown() override {
  22151. server_->stop();
  22152. if (server_thread_.joinable()) { server_thread_.join(); }
  22153. }
  22154. std::string url() const {
  22155. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22156. }
  22157. void ConnectWithClientCert(const std::string &client_cert_file,
  22158. const std::string &client_private_key_file,
  22159. const char *private_key_password) {
  22160. std::string cert_pem, key_pem;
  22161. read_file(client_cert_file, cert_pem);
  22162. read_file(client_private_key_file, key_pem);
  22163. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22164. key_pem.c_str(), key_pem.size(),
  22165. private_key_password};
  22166. ws::WebSocketClient client(url(), pem);
  22167. ASSERT_TRUE(client.is_valid());
  22168. client.enable_server_certificate_verification(false);
  22169. ASSERT_TRUE(client.connect());
  22170. ASSERT_TRUE(client.send("hello"));
  22171. std::string msg;
  22172. EXPECT_EQ(ws::Text, client.read(msg));
  22173. EXPECT_EQ("hello", msg);
  22174. client.close();
  22175. }
  22176. std::unique_ptr<SSLServer> server_;
  22177. std::thread server_thread_;
  22178. int port_ = 0;
  22179. };
  22180. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22181. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22182. }
  22183. // Control for the tests above: the fixture's server really does require a
  22184. // client certificate, so it is the PEM the constructor installed that decides
  22185. // the outcome.
  22186. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22187. ws::WebSocketClient client(url());
  22188. ASSERT_TRUE(client.is_valid());
  22189. client.enable_server_certificate_verification(false);
  22190. EXPECT_FALSE(client.connect());
  22191. }
  22192. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22193. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22194. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22195. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22196. }
  22197. #endif
  22198. #if !defined(_WIN32)
  22199. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22200. auto secret_dir = std::string("./symlink_test_secret");
  22201. auto served_dir = std::string("./symlink_test_served");
  22202. auto secret_file = secret_dir + "/secret.txt";
  22203. auto symlink_path = served_dir + "/escape";
  22204. // Setup: create directories and files
  22205. mkdir(secret_dir.c_str(), 0755);
  22206. mkdir(served_dir.c_str(), 0755);
  22207. {
  22208. std::ofstream ofs(secret_file);
  22209. ofs << "SECRET_DATA";
  22210. }
  22211. // Create symlink using absolute path so it resolves correctly
  22212. #ifdef PATH_MAX
  22213. char abs_secret[PATH_MAX];
  22214. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22215. #else
  22216. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22217. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22218. ASSERT_NE(nullptr, abs_secret);
  22219. #endif
  22220. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22221. auto se = detail::scope_exit([&] {
  22222. unlink(symlink_path.c_str());
  22223. unlink(secret_file.c_str());
  22224. rmdir(served_dir.c_str());
  22225. rmdir(secret_dir.c_str());
  22226. });
  22227. Server svr;
  22228. svr.set_mount_point("/", served_dir);
  22229. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22230. auto se2 = detail::scope_exit([&] {
  22231. svr.stop();
  22232. listen_thread.join();
  22233. });
  22234. svr.wait_until_ready();
  22235. Client cli("localhost", PORT);
  22236. // Symlink pointing outside base dir should be blocked
  22237. auto res = cli.Get("/escape/secret.txt");
  22238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22239. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22240. }
  22241. #endif
  22242. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22243. // "GET /smuggled" request), reads the first response, and only then sends the
  22244. // embedded request as the body. Returns how many times /smuggled ran.
  22245. //
  22246. // The body is sent AFTER receiving the first response (as in the original
  22247. // PoC) so that the stream_line_reader cannot buffer it together with the
  22248. // headers of the first request.
  22249. static int count_smuggled_requests(const std::string &outer_head,
  22250. std::string &first_response) {
  22251. Server svr;
  22252. svr.set_mount_point("/", "./www");
  22253. std::atomic<int> smuggled_count(0);
  22254. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22255. smuggled_count++;
  22256. res.set_content("oops", "text/plain");
  22257. });
  22258. svr.Post("/post", [&](const Request &req, Response &res) {
  22259. res.set_content(req.body, "text/plain");
  22260. });
  22261. auto port = svr.bind_to_any_port("localhost");
  22262. thread t = thread([&] { svr.listen_after_bind(); });
  22263. auto se = detail::scope_exit([&] {
  22264. svr.stop();
  22265. t.join();
  22266. });
  22267. svr.wait_until_ready();
  22268. auto error = Error::Success;
  22269. auto sock = detail::create_client_socket(
  22270. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22271. /*connection_timeout_sec=*/2, 0,
  22272. /*read_timeout_sec=*/2, 0,
  22273. /*write_timeout_sec=*/2, 0, std::string(), error);
  22274. EXPECT_NE(INVALID_SOCKET, sock);
  22275. if (sock == INVALID_SOCKET) { return -1; }
  22276. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22277. // The "smuggled" request will be sent as the body of the outer request
  22278. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22279. "Host: localhost\r\n"
  22280. "Connection: close\r\n"
  22281. "\r\n";
  22282. auto head = outer_head;
  22283. auto len = std::to_string(smuggled.size());
  22284. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22285. pos = head.find("{len}", pos + len.size())) {
  22286. head.replace(pos, 5, len);
  22287. }
  22288. // Step 1: Send only the outer request headers (no body yet)
  22289. auto sent = send(sock, head.data(), head.size(), 0);
  22290. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22291. // Step 2: Read the first response
  22292. char buf[4096];
  22293. for (;;) {
  22294. auto n = recv(sock, buf, sizeof(buf), 0);
  22295. if (n <= 0) break;
  22296. first_response.append(buf, static_cast<size_t>(n));
  22297. // Stop once we have a complete response (headers + body)
  22298. auto hdr_end = first_response.find("\r\n\r\n");
  22299. if (hdr_end != std::string::npos) {
  22300. // Check for Content-Length to know when the body is complete
  22301. auto cl_pos = first_response.find("Content-Length:");
  22302. if (cl_pos != std::string::npos) {
  22303. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22304. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22305. auto cl = std::stoul(
  22306. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22307. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22308. } else {
  22309. break; // No Content-Length, assume headers-only response
  22310. }
  22311. }
  22312. }
  22313. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22314. // vulnerable server the keep-alive loop reads this as a second request. The
  22315. // server may already have closed the connection, so the result is ignored.
  22316. send(sock, smuggled.data(), smuggled.size(), 0);
  22317. // Half-close so that a server which drained the body sees EOF and closes,
  22318. // instead of the read below waiting for the read timeout.
  22319. #ifdef _WIN32
  22320. ::shutdown(sock, SD_SEND);
  22321. #else
  22322. ::shutdown(sock, SHUT_WR);
  22323. #endif
  22324. // Step 4: Read until the server closes the connection
  22325. for (;;) {
  22326. auto n = recv(sock, buf, sizeof(buf), 0);
  22327. if (n <= 0) break;
  22328. }
  22329. return smuggled_count.load();
  22330. }
  22331. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22332. // A GET request with Content-Length to a static file handler must have its
  22333. // body drained before the keep-alive connection is reused. Otherwise the
  22334. // unread body bytes are interpreted as the next HTTP request.
  22335. std::string first_response;
  22336. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22337. "Host: localhost\r\n"
  22338. "Content-Length: {len}\r\n"
  22339. "\r\n",
  22340. first_response));
  22341. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22342. }
  22343. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22344. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22345. // be answered with 400 and the connection closed. Treating it as "no body"
  22346. // leaves the body to be parsed as the next request.
  22347. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22348. const char *targets[] = {
  22349. "GET /file", // handler that never reads the body
  22350. "GET /not-found", // no handler matches (404)
  22351. "POST /post", // handler that reads the body
  22352. };
  22353. for (auto target : targets) {
  22354. for (auto value : values) {
  22355. std::string first_response;
  22356. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22357. " HTTP/1.1\r\n"
  22358. "Host: localhost\r\n"
  22359. "Content-Length: " +
  22360. value + "\r\n\r\n",
  22361. first_response))
  22362. << target << " with Content-Length: " << value;
  22363. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22364. << target << " with Content-Length: " << value;
  22365. }
  22366. }
  22367. }
  22368. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22369. // A 400 for an unparseable request line leaves the rest of the message
  22370. // unread, so the connection must be closed rather than reused.
  22371. std::string first_response;
  22372. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22373. "Host: localhost\r\n"
  22374. "Content-Length: {len}\r\n"
  22375. "\r\n",
  22376. first_response));
  22377. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22378. }
  22379. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22380. // Same as above for a header block that fails to parse.
  22381. std::string first_response;
  22382. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22383. "Host: localhost\r\n"
  22384. "Bad Header\r\n"
  22385. "Content-Length: {len}\r\n"
  22386. "\r\n",
  22387. first_response));
  22388. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22389. }
  22390. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22391. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22392. // server must not read another request on that connection, even when the
  22393. // request had no body to drain.
  22394. std::string first_response;
  22395. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22396. "Host: localhost\r\n"
  22397. "\r\n",
  22398. first_response));
  22399. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22400. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22401. }
  22402. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22403. // A content reader that stops early leaves the stream inside the body.
  22404. // Draining the whole Content-Length from there, or reading the body again,
  22405. // reads into the next request, and whatever follows is parsed as a request
  22406. // of its own.
  22407. Server svr;
  22408. std::atomic<int> smuggled_count(0);
  22409. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22410. svr.Post("/upload", [](const Request &req, Response &res,
  22411. const ContentReader &content_reader) {
  22412. // Stop at the last chunk, so the whole body has been read however it
  22413. // arrives.
  22414. auto length = req.get_header_value_u64("Content-Length");
  22415. size_t total = 0;
  22416. auto consumed = content_reader([&](const char *, size_t n) {
  22417. total += n;
  22418. return total < length;
  22419. });
  22420. EXPECT_FALSE(consumed);
  22421. if (req.has_param("retry")) {
  22422. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22423. }
  22424. // Replace the 400 the aborted read set, which would close the connection.
  22425. res.set_redirect("/done");
  22426. });
  22427. auto port = svr.bind_to_any_port(HOST);
  22428. thread t = thread([&] { svr.listen_after_bind(); });
  22429. auto se = detail::scope_exit([&] {
  22430. svr.stop();
  22431. t.join();
  22432. });
  22433. svr.wait_until_ready();
  22434. // A front end sees the second request as a POST whose body is the GET. The
  22435. // first body is as long as the POST's headers, so draining it again reads
  22436. // exactly those and leaves the GET to be parsed next.
  22437. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22438. "Host: localhost\r\n"
  22439. "\r\n";
  22440. std::string second_head = "POST /post HTTP/1.1\r\n"
  22441. "Host: localhost\r\n"
  22442. "Content-Length: " +
  22443. std::to_string(inner.size()) +
  22444. "\r\n"
  22445. "\r\n";
  22446. for (auto target : {"/upload", "/upload?retry"}) {
  22447. smuggled_count = 0;
  22448. std::string request = "POST " + std::string(target) +
  22449. " HTTP/1.1\r\n"
  22450. "Host: localhost\r\n"
  22451. "Content-Length: " +
  22452. std::to_string(second_head.size()) +
  22453. "\r\n"
  22454. "\r\n" +
  22455. std::string(second_head.size(), 'A') + second_head +
  22456. inner;
  22457. std::string response;
  22458. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  22459. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  22460. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  22461. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  22462. EXPECT_EQ(0, smuggled_count.load()) << target;
  22463. }
  22464. }
  22465. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22466. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22467. // must be rejected with 400 Bad Request.
  22468. Server svr;
  22469. svr.Post("/test", [&](const Request &, Response &res) {
  22470. res.set_content("ok", "text/plain");
  22471. });
  22472. thread t = thread([&] { svr.listen(HOST, PORT); });
  22473. auto se = detail::scope_exit([&] {
  22474. svr.stop();
  22475. t.join();
  22476. ASSERT_FALSE(svr.is_running());
  22477. });
  22478. svr.wait_until_ready();
  22479. // Exact "chunked"
  22480. {
  22481. auto req = "POST /test HTTP/1.1\r\n"
  22482. "Host: localhost\r\n"
  22483. "Content-Length: 5\r\n"
  22484. "Transfer-Encoding: chunked\r\n"
  22485. "Connection: close\r\n"
  22486. "\r\n"
  22487. "hello";
  22488. std::string response;
  22489. ASSERT_TRUE(send_request(1, req, &response));
  22490. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22491. response.substr(0, response.find("\r\n")));
  22492. }
  22493. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22494. {
  22495. auto req = "POST /test HTTP/1.1\r\n"
  22496. "Host: localhost\r\n"
  22497. "Content-Length: 5\r\n"
  22498. "Transfer-Encoding: gzip, chunked\r\n"
  22499. "Connection: close\r\n"
  22500. "\r\n"
  22501. "hello";
  22502. std::string response;
  22503. ASSERT_TRUE(send_request(1, req, &response));
  22504. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22505. response.substr(0, response.find("\r\n")));
  22506. }
  22507. }
  22508. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22509. Server svr;
  22510. svr.Post("/test", [&](const Request &, Response &res) {
  22511. res.set_content("ok", "text/plain");
  22512. });
  22513. thread t = thread([&] { svr.listen(HOST, PORT); });
  22514. auto se = detail::scope_exit([&] {
  22515. svr.stop();
  22516. t.join();
  22517. ASSERT_FALSE(svr.is_running());
  22518. });
  22519. svr.wait_until_ready();
  22520. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22521. // length cannot be determined, so the server must answer 400 and close
  22522. // rather than treat the request as bodyless and leave the body in the
  22523. // socket for the next request to pick up.
  22524. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22525. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22526. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22527. std::string response;
  22528. ASSERT_TRUE(send_request(1, req, &response));
  22529. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22530. response.substr(0, response.find("\r\n")))
  22531. << transfer_encoding;
  22532. }
  22533. // RFC 9110 5.3: the codings may also be split across several
  22534. // Transfer-Encoding lines, which combine in the order they were received.
  22535. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22536. // just like the single-line "chunked, gzip" above.
  22537. {
  22538. auto req = "POST /test HTTP/1.1\r\n"
  22539. "Host: localhost\r\n"
  22540. "Transfer-Encoding: chunked\r\n"
  22541. "Transfer-Encoding: gzip\r\n"
  22542. "\r\n"
  22543. "0\r\n\r\n";
  22544. std::string response;
  22545. ASSERT_TRUE(send_request(1, req, &response));
  22546. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22547. response.substr(0, response.find("\r\n")));
  22548. }
  22549. // A sequence ending in chunked stays valid.
  22550. auto req = "POST /test HTTP/1.1\r\n"
  22551. "Host: localhost\r\n"
  22552. "Transfer-Encoding: gzip, chunked\r\n"
  22553. "Connection: close\r\n"
  22554. "\r\n"
  22555. "0\r\n\r\n";
  22556. std::string response;
  22557. ASSERT_TRUE(send_request(1, req, &response));
  22558. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22559. // ...including when it is spread over several lines.
  22560. auto split_req = "POST /test HTTP/1.1\r\n"
  22561. "Host: localhost\r\n"
  22562. "Transfer-Encoding: gzip\r\n"
  22563. "Transfer-Encoding: chunked\r\n"
  22564. "Connection: close\r\n"
  22565. "\r\n"
  22566. "0\r\n\r\n";
  22567. std::string split_response;
  22568. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22569. EXPECT_EQ("HTTP/1.1 200 OK",
  22570. split_response.substr(0, split_response.find("\r\n")));
  22571. }
  22572. // Regression for issue #2450: a DELETE without Content-Length on a
  22573. // keep-alive connection must not let the post-response drain consume the
  22574. // next request's bytes.
  22575. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22576. Server svr;
  22577. std::atomic<int> delete_count(0);
  22578. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22579. delete_count++;
  22580. res.status = StatusCode::NoContent_204;
  22581. });
  22582. auto port = svr.bind_to_any_port(HOST);
  22583. thread t = thread([&] { svr.listen_after_bind(); });
  22584. auto se = detail::scope_exit([&] {
  22585. svr.stop();
  22586. t.join();
  22587. });
  22588. svr.wait_until_ready();
  22589. auto error = Error::Success;
  22590. auto sock = detail::create_client_socket(
  22591. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22592. /*connection_timeout_sec=*/2, 0,
  22593. /*read_timeout_sec=*/2, 0,
  22594. /*write_timeout_sec=*/2, 0, std::string(), error);
  22595. ASSERT_NE(INVALID_SOCKET, sock);
  22596. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22597. auto send_request_and_read_response = [&](const std::string &req,
  22598. std::string &out) -> bool {
  22599. auto sent = send(sock, req.data(), req.size(), 0);
  22600. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22601. char buf[4096];
  22602. for (;;) {
  22603. auto n = recv(sock, buf, sizeof(buf), 0);
  22604. if (n <= 0) { return !out.empty(); }
  22605. out.append(buf, static_cast<size_t>(n));
  22606. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22607. }
  22608. };
  22609. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22610. "Host: localhost\r\n"
  22611. "\r\n";
  22612. std::string resp1;
  22613. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22614. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22615. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22616. "Host: localhost\r\n"
  22617. "Connection: close\r\n"
  22618. "\r\n";
  22619. std::string resp2;
  22620. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22621. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22622. EXPECT_EQ(2, delete_count.load());
  22623. }
  22624. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22625. Server svr;
  22626. svr.Post("/ingest", [&](const Request &, Response &res,
  22627. const ContentReader &content_reader) {
  22628. auto consumed = content_reader([](const char *, size_t) { return false; });
  22629. EXPECT_FALSE(consumed);
  22630. res.status = StatusCode::Conflict_409;
  22631. res.set_header("Connection", "close");
  22632. });
  22633. auto port = svr.bind_to_any_port(HOST);
  22634. thread t = thread([&] { svr.listen_after_bind(); });
  22635. auto se = detail::scope_exit([&] {
  22636. svr.stop();
  22637. t.join();
  22638. });
  22639. svr.wait_until_ready();
  22640. auto error = Error::Success;
  22641. auto sock = detail::create_client_socket(
  22642. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22643. /*connection_timeout_sec=*/2, 0,
  22644. /*read_timeout_sec=*/1, 0,
  22645. /*write_timeout_sec=*/2, 0, std::string(), error);
  22646. ASSERT_NE(INVALID_SOCKET, sock);
  22647. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22648. std::string request = "POST /ingest HTTP/1.1\r\n"
  22649. "Host: localhost\r\n"
  22650. "Transfer-Encoding: chunked\r\n"
  22651. "\r\n"
  22652. "4\r\n"
  22653. "data\r\n";
  22654. auto sent = send(sock, request.data(), request.size(), 0);
  22655. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22656. std::string response;
  22657. ssize_t received = 0;
  22658. do {
  22659. char buf[4096];
  22660. received = recv(sock, buf, sizeof(buf), 0);
  22661. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22662. } while (received > 0);
  22663. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22664. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22665. EXPECT_EQ(0, received);
  22666. }
  22667. namespace no_proxy_test {
  22668. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22669. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22670. // calling listen().
  22671. class ScopedServer {
  22672. public:
  22673. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22674. ~ScopedServer() {
  22675. svr_.stop();
  22676. if (th_.joinable()) { th_.join(); }
  22677. }
  22678. Server &svr() { return svr_; }
  22679. int port() const { return port_; }
  22680. void listen() {
  22681. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22682. svr_.wait_until_ready();
  22683. }
  22684. private:
  22685. Server svr_;
  22686. std::thread th_;
  22687. int port_ = 0;
  22688. };
  22689. class ProxyAndTargetServers {
  22690. public:
  22691. ProxyAndTargetServers() {
  22692. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22693. proxy_hits_++;
  22694. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22695. res.set_content("via-proxy", "text/plain");
  22696. });
  22697. target_.Get(".*", [this](const Request &req, Response &res) {
  22698. target_hits_++;
  22699. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22700. res.set_content("direct", "text/plain");
  22701. });
  22702. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22703. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22704. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22705. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22706. proxy_mock_.wait_until_ready();
  22707. target_.wait_until_ready();
  22708. }
  22709. ~ProxyAndTargetServers() {
  22710. proxy_mock_.stop();
  22711. target_.stop();
  22712. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22713. if (target_thread_.joinable()) { target_thread_.join(); }
  22714. }
  22715. Server &proxy_mock() { return proxy_mock_; }
  22716. Server &target() { return target_; }
  22717. int proxy_port() const { return proxy_port_; }
  22718. int target_port() const { return target_port_; }
  22719. int proxy_hits() const { return proxy_hits_.load(); }
  22720. int target_hits() const { return target_hits_.load(); }
  22721. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22722. void reset_counters() {
  22723. proxy_hits_ = 0;
  22724. target_hits_ = 0;
  22725. last_had_proxy_authz_ = false;
  22726. }
  22727. private:
  22728. Server proxy_mock_;
  22729. Server target_;
  22730. std::thread proxy_thread_;
  22731. std::thread target_thread_;
  22732. int proxy_port_ = 0;
  22733. int target_port_ = 0;
  22734. std::atomic<int> proxy_hits_{0};
  22735. std::atomic<int> target_hits_{0};
  22736. std::atomic<bool> last_had_proxy_authz_{false};
  22737. };
  22738. inline std::unique_ptr<Client> make_client(const std::string &host,
  22739. ProxyAndTargetServers &s) {
  22740. auto cli = detail::make_unique<Client>(host, s.target_port());
  22741. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22742. cli->set_proxy("127.0.0.1", s.proxy_port());
  22743. return cli;
  22744. }
  22745. } // namespace no_proxy_test
  22746. using no_proxy_test::make_client;
  22747. using no_proxy_test::ProxyAndTargetServers;
  22748. TEST(NoProxyTest, ExactHostnameBypasses) {
  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, SubdomainBypasses) {
  22758. ProxyAndTargetServers s;
  22759. auto cli = make_client("foo.example.com", s);
  22760. cli->set_no_proxy({"example.com"});
  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, EvilExampleDoesNotMatchExample) {
  22767. // Regression guard: "evilexample.com" must not be considered a subdomain
  22768. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22769. // check would let traffic bypass the proxy and leak credentials direct
  22770. // to the attacker host.
  22771. ProxyAndTargetServers s;
  22772. auto cli = make_client("evilexample.com", s);
  22773. cli->set_no_proxy({"example.com"});
  22774. auto res = cli->Get("/");
  22775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22776. EXPECT_GE(s.proxy_hits(), 1);
  22777. EXPECT_EQ(0, s.target_hits());
  22778. }
  22779. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22780. ProxyAndTargetServers s;
  22781. auto cli = make_client("example.com.evil.com", s);
  22782. cli->set_no_proxy({"example.com"});
  22783. auto res = cli->Get("/");
  22784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22785. EXPECT_GE(s.proxy_hits(), 1);
  22786. EXPECT_EQ(0, s.target_hits());
  22787. }
  22788. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22789. ProxyAndTargetServers s;
  22790. auto cli = make_client("example.com", s);
  22791. cli->set_no_proxy({".example.com"});
  22792. auto res = cli->Get("/");
  22793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22794. EXPECT_EQ(0, s.proxy_hits());
  22795. EXPECT_EQ(1, s.target_hits());
  22796. }
  22797. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22798. ProxyAndTargetServers s;
  22799. auto cli = make_client("Example.COM", s);
  22800. cli->set_no_proxy({"EXAMPLE.com"});
  22801. auto res = cli->Get("/");
  22802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22803. EXPECT_EQ(0, s.proxy_hits());
  22804. EXPECT_EQ(1, s.target_hits());
  22805. }
  22806. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22807. ProxyAndTargetServers s;
  22808. auto cli = make_client("example.com.", s);
  22809. cli->set_no_proxy({"example.com"});
  22810. auto res = cli->Get("/");
  22811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22812. EXPECT_EQ(0, s.proxy_hits());
  22813. EXPECT_EQ(1, s.target_hits());
  22814. }
  22815. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22816. // Trailing dots must be normalized on BOTH sides — host and entry.
  22817. // An implementation that only strips the host-side trailing dot would
  22818. // fail to match host "example.com" against entry "example.com." because
  22819. // a literal substring search would compare 11 chars against 12.
  22820. ProxyAndTargetServers s;
  22821. auto cli = make_client("example.com", s);
  22822. cli->set_no_proxy({"example.com."});
  22823. auto res = cli->Get("/");
  22824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22825. EXPECT_EQ(0, s.proxy_hits());
  22826. EXPECT_EQ(1, s.target_hits());
  22827. }
  22828. TEST(NoProxyTest, WildcardBypassesEverything) {
  22829. ProxyAndTargetServers s;
  22830. auto cli = make_client("anything.invalid.test", s);
  22831. cli->set_no_proxy({"*"});
  22832. auto res = cli->Get("/");
  22833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22834. EXPECT_EQ(0, s.proxy_hits());
  22835. EXPECT_EQ(1, s.target_hits());
  22836. }
  22837. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22838. ProxyAndTargetServers s;
  22839. Client cli("127.0.0.1", s.target_port());
  22840. cli.set_proxy("127.0.0.1", s.proxy_port());
  22841. cli.set_no_proxy({"127.0.0.1"});
  22842. auto res = cli.Get("/");
  22843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22844. EXPECT_EQ(0, s.proxy_hits());
  22845. EXPECT_EQ(1, s.target_hits());
  22846. }
  22847. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22848. ProxyAndTargetServers s;
  22849. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22850. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22851. cli.set_proxy("127.0.0.1", s.proxy_port());
  22852. cli.set_no_proxy({"::1"});
  22853. auto res = cli.Get("/");
  22854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22855. EXPECT_EQ(0, s.proxy_hits());
  22856. EXPECT_EQ(1, s.target_hits());
  22857. }
  22858. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22859. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22860. // must still be recognized as IPv6 for CIDR matching. Implementations
  22861. // that detect IPv6 only when the host begins with '[' would parse the
  22862. // host as a hostname and miss the match.
  22863. ProxyAndTargetServers s;
  22864. Client cli("fe80::1", s.target_port());
  22865. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22866. cli.set_proxy("127.0.0.1", s.proxy_port());
  22867. cli.set_no_proxy({"fe80::/10"});
  22868. auto res = cli.Get("/");
  22869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22870. EXPECT_EQ(0, s.proxy_hits());
  22871. EXPECT_EQ(1, s.target_hits());
  22872. }
  22873. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22874. ProxyAndTargetServers s;
  22875. Client cli("::1", s.target_port());
  22876. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22877. cli.set_proxy("127.0.0.1", s.proxy_port());
  22878. cli.set_no_proxy({"[::1]"});
  22879. auto res = cli.Get("/");
  22880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22881. EXPECT_EQ(0, s.proxy_hits());
  22882. EXPECT_EQ(1, s.target_hits());
  22883. }
  22884. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22885. ProxyAndTargetServers s;
  22886. Client cli("fe80::1", s.target_port());
  22887. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22888. cli.set_proxy("127.0.0.1", s.proxy_port());
  22889. cli.set_no_proxy({"[fe80::]/10"});
  22890. auto res = cli.Get("/");
  22891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22892. EXPECT_EQ(0, s.proxy_hits());
  22893. EXPECT_EQ(1, s.target_hits());
  22894. }
  22895. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22896. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22897. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22898. // tricks via address-family conversion.
  22899. ProxyAndTargetServers s;
  22900. Client cli("::ffff:127.0.0.1", s.target_port());
  22901. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22902. cli.set_proxy("127.0.0.1", s.proxy_port());
  22903. cli.set_no_proxy({"127.0.0.1"});
  22904. auto res = cli.Get("/");
  22905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22906. EXPECT_GE(s.proxy_hits(), 1);
  22907. EXPECT_EQ(0, s.target_hits());
  22908. }
  22909. TEST(NoProxyTest, IPv4CidrMatch) {
  22910. ProxyAndTargetServers s;
  22911. Client cli("127.0.0.1", s.target_port());
  22912. cli.set_proxy("127.0.0.1", s.proxy_port());
  22913. cli.set_no_proxy({"127.0.0.0/8"});
  22914. auto res = cli.Get("/");
  22915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22916. EXPECT_EQ(0, s.proxy_hits());
  22917. EXPECT_EQ(1, s.target_hits());
  22918. }
  22919. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22920. ProxyAndTargetServers s;
  22921. Client cli("127.0.0.1", s.target_port());
  22922. cli.set_proxy("127.0.0.1", s.proxy_port());
  22923. cli.set_no_proxy({"10.0.0.0/8"});
  22924. auto res = cli.Get("/");
  22925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22926. EXPECT_GE(s.proxy_hits(), 1);
  22927. EXPECT_EQ(0, s.target_hits());
  22928. }
  22929. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22930. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22931. // IPv4 target matches.
  22932. ProxyAndTargetServers s;
  22933. Client cli("127.0.0.1", s.target_port());
  22934. cli.set_proxy("127.0.0.1", s.proxy_port());
  22935. cli.set_no_proxy({"0.0.0.0/0"});
  22936. auto res = cli.Get("/");
  22937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22938. EXPECT_EQ(0, s.proxy_hits());
  22939. EXPECT_EQ(1, s.target_hits());
  22940. }
  22941. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22942. ProxyAndTargetServers s;
  22943. Client cli("127.0.0.1", s.target_port());
  22944. cli.set_proxy("127.0.0.1", s.proxy_port());
  22945. cli.set_no_proxy({"127.0.0.1"});
  22946. auto res = cli.Get("/");
  22947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22948. EXPECT_EQ(0, s.proxy_hits());
  22949. EXPECT_EQ(1, s.target_hits());
  22950. }
  22951. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22952. ProxyAndTargetServers s;
  22953. Client cli("127.0.0.1", s.target_port());
  22954. cli.set_proxy("127.0.0.1", s.proxy_port());
  22955. cli.set_no_proxy({"127.0.0.0/33"});
  22956. auto res = cli.Get("/");
  22957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22958. EXPECT_GE(s.proxy_hits(), 1);
  22959. EXPECT_EQ(0, s.target_hits());
  22960. }
  22961. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22962. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22963. ProxyAndTargetServers s;
  22964. Client cli("127.0.0.1", s.target_port());
  22965. cli.set_proxy("127.0.0.1", s.proxy_port());
  22966. cli.set_no_proxy({"127.0.0.1/"});
  22967. auto res = cli.Get("/");
  22968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22969. EXPECT_GE(s.proxy_hits(), 1);
  22970. EXPECT_EQ(0, s.target_hits());
  22971. }
  22972. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22973. ProxyAndTargetServers s;
  22974. auto cli = make_client("internal.corp", s);
  22975. cli->set_proxy_basic_auth("u", "p");
  22976. cli->set_no_proxy({"internal.corp"});
  22977. auto res = cli->Get("/");
  22978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22979. EXPECT_EQ(1, s.target_hits());
  22980. EXPECT_EQ(0, s.proxy_hits());
  22981. EXPECT_FALSE(s.last_had_proxy_authz())
  22982. << "Proxy-Authorization must not be sent direct to the target";
  22983. }
  22984. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22985. ProxyAndTargetServers s;
  22986. auto cli = make_client("public.example", s);
  22987. cli->set_proxy_basic_auth("u", "p");
  22988. cli->set_no_proxy({"internal.corp"}); // does not match
  22989. auto res = cli->Get("/");
  22990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22991. EXPECT_GE(s.proxy_hits(), 1);
  22992. EXPECT_TRUE(s.last_had_proxy_authz());
  22993. }
  22994. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22995. std::atomic<int> hits{0};
  22996. std::atomic<int> hits_with_authz{0};
  22997. no_proxy_test::ScopedServer proxy_mock;
  22998. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22999. hits++;
  23000. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23001. if (req.target.find("/redir") != std::string::npos) {
  23002. res.set_redirect("http://other.example/landed");
  23003. } else {
  23004. res.set_content("via-proxy", "text/plain");
  23005. }
  23006. });
  23007. proxy_mock.listen();
  23008. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23009. hits = 0;
  23010. hits_with_authz = 0;
  23011. Client cli("public.example", 80);
  23012. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23013. cli.set_proxy_basic_auth(c.first, c.second);
  23014. cli.set_follow_location(true);
  23015. // The redirect to another host goes through the proxy as well
  23016. auto res = cli.Get("/redir");
  23017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23018. EXPECT_EQ(2, hits.load());
  23019. EXPECT_EQ(2, hits_with_authz.load());
  23020. }
  23021. }
  23022. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23023. ProxyAndTargetServers s;
  23024. auto cli = make_client("anything.test", s);
  23025. auto res = cli->Get("/");
  23026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23027. EXPECT_GE(s.proxy_hits(), 1);
  23028. EXPECT_EQ(0, s.target_hits());
  23029. }
  23030. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23031. ProxyAndTargetServers s;
  23032. auto cli = make_client("example.com", s);
  23033. cli->set_no_proxy({"example.com:8080"});
  23034. auto res = cli->Get("/");
  23035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23036. EXPECT_GE(s.proxy_hits(), 1);
  23037. EXPECT_EQ(0, s.target_hits());
  23038. }
  23039. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23040. ProxyAndTargetServers s;
  23041. auto cli = make_client("anything.test", s);
  23042. cli->set_no_proxy({"", " ", "\t"});
  23043. auto res = cli->Get("/");
  23044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23045. EXPECT_GE(s.proxy_hits(), 1);
  23046. EXPECT_EQ(0, s.target_hits());
  23047. }
  23048. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23049. // An entry with leading/trailing whitespace must still match — env-style
  23050. // values are commonly pasted with stray spaces and an implementation
  23051. // that feeds the raw token directly to inet_pton would fail to match
  23052. // valid CIDRs because of the spaces.
  23053. ProxyAndTargetServers s;
  23054. Client cli("127.0.0.1", s.target_port());
  23055. cli.set_proxy("127.0.0.1", s.proxy_port());
  23056. cli.set_no_proxy({" 127.0.0.0/8 "});
  23057. auto res = cli.Get("/");
  23058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23059. EXPECT_EQ(0, s.proxy_hits());
  23060. EXPECT_EQ(1, s.target_hits());
  23061. }
  23062. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23063. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23064. // go direct and must NOT carry Proxy-Authorization.
  23065. std::atomic<int> proxy_hits{0};
  23066. std::atomic<int> target_hits{0};
  23067. std::atomic<bool> target_saw_authz{false};
  23068. no_proxy_test::ScopedServer proxy_mock, target;
  23069. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23070. proxy_hits++;
  23071. res.status = 302;
  23072. res.set_header("Location", "http://127.0.0.1:" +
  23073. std::to_string(target.port()) + "/landed");
  23074. });
  23075. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23076. target_hits++;
  23077. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23078. res.set_content("direct", "text/plain");
  23079. });
  23080. proxy_mock.listen();
  23081. target.listen();
  23082. Client cli("public.example", target.port());
  23083. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23084. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23085. cli.set_proxy_basic_auth("u", "p");
  23086. cli.set_no_proxy({"127.0.0.1"});
  23087. cli.set_follow_location(true);
  23088. auto res = cli.Get("/redir");
  23089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23090. EXPECT_GE(proxy_hits.load(), 1);
  23091. EXPECT_GE(target_hits.load(), 1);
  23092. EXPECT_FALSE(target_saw_authz.load());
  23093. }
  23094. #ifdef CPPHTTPLIB_SSL_ENABLED
  23095. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23096. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23097. // proxy creds would be sent to the (possibly hostile) origin.
  23098. std::atomic<int> target_hits{0};
  23099. std::atomic<bool> target_saw_proxy_authz{false};
  23100. no_proxy_test::ScopedServer target;
  23101. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23102. target_hits++;
  23103. if (req.has_header("Proxy-Authorization")) {
  23104. target_saw_proxy_authz = true;
  23105. }
  23106. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23107. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23108. "nonce=\"abc\", algorithm=MD5");
  23109. });
  23110. target.listen();
  23111. // The proxy address is set to the target's port: the bypass MUST kick in;
  23112. // if it doesn't, the test still routes "via proxy" to the same server and
  23113. // the Proxy-Authorization assertion below catches the leak.
  23114. Client cli("evil.example", target.port());
  23115. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23116. cli.set_proxy("127.0.0.1", target.port());
  23117. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23118. cli.set_no_proxy({"evil.example"});
  23119. auto res = cli.Get("/x");
  23120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23121. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23122. EXPECT_EQ(1, target_hits.load());
  23123. EXPECT_FALSE(target_saw_proxy_authz.load());
  23124. }
  23125. #endif
  23126. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23127. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23128. std::atomic<int> proxy_hits{0};
  23129. std::atomic<int> bypass_hits{0};
  23130. std::atomic<bool> proxy_saw_c_url{false};
  23131. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23132. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23133. proxy_hits++;
  23134. if (req.path.find("/start") != std::string::npos) {
  23135. res.status = 302;
  23136. res.set_header("Location", "http://127.0.0.1:" +
  23137. std::to_string(bypass_server.port()) +
  23138. "/middle");
  23139. return;
  23140. }
  23141. if (req.path.find("/end") != std::string::npos) {
  23142. proxy_saw_c_url = true;
  23143. res.set_content("c-via-proxy", "text/plain");
  23144. return;
  23145. }
  23146. res.set_content("unexpected", "text/plain");
  23147. });
  23148. // public.example's "advertised" port is arbitrary (the request never lands
  23149. // there — it goes through the proxy), but use a dynamic value to stay
  23150. // friendly with sharded parallel runs.
  23151. int public_port = bypass_server.port();
  23152. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23153. bypass_hits++;
  23154. res.status = 302;
  23155. res.set_header("Location", "http://public.example:" +
  23156. std::to_string(public_port) + "/end");
  23157. });
  23158. proxy_mock.listen();
  23159. bypass_server.listen();
  23160. Client cli("public.example", public_port);
  23161. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23162. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23163. cli.set_no_proxy({"127.0.0.1"});
  23164. cli.set_follow_location(true);
  23165. auto res = cli.Get("/start");
  23166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23167. EXPECT_EQ(StatusCode::OK_200, res->status);
  23168. EXPECT_EQ("c-via-proxy", res->body);
  23169. EXPECT_GE(proxy_hits.load(), 2);
  23170. EXPECT_GE(bypass_hits.load(), 1);
  23171. EXPECT_TRUE(proxy_saw_c_url.load());
  23172. }
  23173. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23174. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23175. // request reconnects to the correct endpoint.
  23176. std::atomic<int> proxy_hits{0};
  23177. std::atomic<int> target_hits{0};
  23178. no_proxy_test::ScopedServer proxy_mock, target;
  23179. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23180. proxy_hits++;
  23181. res.set_content("via-proxy", "text/plain");
  23182. });
  23183. target.svr().Get(".*", [&](const Request &, Response &res) {
  23184. target_hits++;
  23185. res.set_content("direct", "text/plain");
  23186. });
  23187. proxy_mock.listen();
  23188. target.listen();
  23189. Client cli("public.example", target.port());
  23190. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23191. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23192. cli.set_keep_alive(true);
  23193. auto res1 = cli.Get("/a");
  23194. ASSERT_TRUE(res1);
  23195. EXPECT_EQ("via-proxy", res1->body);
  23196. EXPECT_EQ(1, proxy_hits.load());
  23197. EXPECT_EQ(0, target_hits.load());
  23198. cli.set_no_proxy({"public.example"});
  23199. auto res2 = cli.Get("/b");
  23200. ASSERT_TRUE(res2);
  23201. EXPECT_EQ("direct", res2->body);
  23202. EXPECT_EQ(1, proxy_hits.load());
  23203. EXPECT_EQ(1, target_hits.load());
  23204. }
  23205. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23206. namespace proxy_tunnel_test {
  23207. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23208. class ScopedSSLServer {
  23209. public:
  23210. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23211. port_ = svr_.bind_to_any_port("127.0.0.1");
  23212. }
  23213. ~ScopedSSLServer() {
  23214. svr_.stop();
  23215. if (th_.joinable()) { th_.join(); }
  23216. }
  23217. SSLServer &svr() { return svr_; }
  23218. int port() const { return port_; }
  23219. void listen() {
  23220. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23221. svr_.wait_until_ready();
  23222. }
  23223. private:
  23224. SSLServer svr_;
  23225. std::thread th_;
  23226. int port_ = 0;
  23227. };
  23228. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23229. class ScopedConnectProxy {
  23230. public:
  23231. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23232. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23233. if (listen_fd_ < 0) { return; }
  23234. int yes = 1;
  23235. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23236. sockaddr_in a{};
  23237. a.sin_family = AF_INET;
  23238. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23239. a.sin_port = 0;
  23240. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23241. return;
  23242. }
  23243. socklen_t alen = sizeof(a);
  23244. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23245. 0) {
  23246. return;
  23247. }
  23248. port_ = ntohs(a.sin_port);
  23249. if (::listen(listen_fd_, 1) != 0) { return; }
  23250. th_ = std::thread([this] { run(); });
  23251. }
  23252. ~ScopedConnectProxy() {
  23253. stop_ = true;
  23254. if (listen_fd_ >= 0) {
  23255. ::shutdown(listen_fd_, SHUT_RDWR);
  23256. ::close(listen_fd_);
  23257. }
  23258. if (th_.joinable()) { th_.join(); }
  23259. }
  23260. int port() const { return port_; }
  23261. int connect_hits() const { return connect_hits_.load(); }
  23262. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23263. std::string connect_request() const {
  23264. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23265. return connect_request_;
  23266. }
  23267. private:
  23268. void run() {
  23269. while (!stop_.load()) {
  23270. fd_set rfds;
  23271. FD_ZERO(&rfds);
  23272. FD_SET(listen_fd_, &rfds);
  23273. timeval tv{0, 100 * 1000};
  23274. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23275. if (sel <= 0) { continue; }
  23276. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23277. if (client_fd < 0) { continue; }
  23278. std::string req;
  23279. char buf[2048];
  23280. while (req.find("\r\n\r\n") == std::string::npos) {
  23281. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23282. if (n <= 0) { break; }
  23283. req.append(buf, static_cast<size_t>(n));
  23284. }
  23285. if (req.compare(0, 7, "CONNECT") != 0) {
  23286. ::close(client_fd);
  23287. continue;
  23288. }
  23289. connect_hits_++;
  23290. {
  23291. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23292. connect_request_ = req;
  23293. }
  23294. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23295. ::send(client_fd, ok, std::strlen(ok), 0);
  23296. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23297. sockaddr_in o{};
  23298. o.sin_family = AF_INET;
  23299. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23300. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23301. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23302. 0) {
  23303. ::close(client_fd);
  23304. ::close(origin_fd);
  23305. continue;
  23306. }
  23307. auto forward = [](int from, int to) {
  23308. char b[8192];
  23309. for (;;) {
  23310. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23311. if (n <= 0) { break; }
  23312. ssize_t off = 0;
  23313. while (off < n) {
  23314. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23315. if (s <= 0) {
  23316. off = n;
  23317. break;
  23318. }
  23319. off += s;
  23320. }
  23321. }
  23322. ::shutdown(to, SHUT_WR);
  23323. };
  23324. std::thread t1([&] { forward(client_fd, origin_fd); });
  23325. std::thread t2([&] { forward(origin_fd, client_fd); });
  23326. t1.join();
  23327. t2.join();
  23328. ::close(client_fd);
  23329. ::close(origin_fd);
  23330. }
  23331. }
  23332. int forward_port_ = -1;
  23333. int listen_fd_ = -1;
  23334. int port_ = 0;
  23335. std::thread th_;
  23336. std::atomic<bool> stop_{false};
  23337. std::atomic<int> connect_hits_{0};
  23338. mutable std::mutex connect_request_mutex_;
  23339. std::string connect_request_;
  23340. };
  23341. // Sends one request through the CONNECT proxy to the TLS origin with a
  23342. // credential configured for each hop, and checks that each credential reaches
  23343. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23344. // origin's (every header in origin_headers) on the tunnelled request.
  23345. void CredentialsStayWithTheirHop(
  23346. const std::function<void(SSLClient &)> &set_credentials,
  23347. const std::string &scheme,
  23348. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23349. std::atomic<int> origin_hits{0};
  23350. std::atomic<bool> origin_saw_proxy_authz{false};
  23351. std::atomic<bool> origin_saw_headers{false};
  23352. ScopedSSLServer origin;
  23353. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23354. origin_hits++;
  23355. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23356. origin_saw_headers =
  23357. std::all_of(origin_headers.begin(), origin_headers.end(),
  23358. [&](const std::string &h) { return req.has_header(h); });
  23359. res.set_content("ok", "text/plain");
  23360. });
  23361. origin.listen();
  23362. ScopedConnectProxy proxy(origin.port());
  23363. ASSERT_NE(0, proxy.port());
  23364. // Pinned to 127.0.0.1 for the same reason as the test below.
  23365. SSLClient cli("127.0.0.1", origin.port());
  23366. cli.enable_server_certificate_verification(false);
  23367. cli.set_proxy("127.0.0.1", proxy.port());
  23368. set_credentials(cli);
  23369. auto res = cli.Get("/x");
  23370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23371. EXPECT_EQ(StatusCode::OK_200, res->status);
  23372. EXPECT_EQ(1, origin_hits.load());
  23373. EXPECT_EQ(1, proxy.connect_hits());
  23374. EXPECT_TRUE(origin_saw_headers.load());
  23375. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23376. << "Proxy-Authorization must not be sent inside the tunnel";
  23377. auto connect_req = proxy.connect_request();
  23378. EXPECT_NE(std::string::npos,
  23379. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23380. for (const auto &h : origin_headers) {
  23381. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23382. << h << " must not be sent to the proxy on CONNECT";
  23383. }
  23384. }
  23385. } // namespace proxy_tunnel_test
  23386. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23387. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23388. [](SSLClient &cli) {
  23389. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23390. cli.set_basic_auth("origin-user", "origin-pass");
  23391. },
  23392. "Basic");
  23393. }
  23394. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23395. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23396. [](SSLClient &cli) {
  23397. cli.set_proxy_bearer_token_auth("proxy-token");
  23398. cli.set_bearer_token_auth("origin-token");
  23399. },
  23400. "Bearer");
  23401. }
  23402. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23403. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23404. [](SSLClient &cli) {
  23405. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23406. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23407. {"Cookie", "sid=origin-session"},
  23408. {"X-Api-Key", "origin-key"}});
  23409. },
  23410. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23411. }
  23412. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23413. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23414. // retry; otherwise proxy creds would be sent to the origin.
  23415. std::atomic<int> origin_hits{0};
  23416. std::atomic<bool> origin_saw_proxy_authz{false};
  23417. proxy_tunnel_test::ScopedSSLServer origin;
  23418. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23419. origin_hits++;
  23420. if (req.has_header("Proxy-Authorization")) {
  23421. origin_saw_proxy_authz = true;
  23422. }
  23423. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23424. res.set_header("Proxy-Authenticate",
  23425. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23426. "algorithm=MD5");
  23427. });
  23428. origin.listen();
  23429. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23430. ASSERT_NE(0, proxy.port());
  23431. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23432. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23433. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23434. // and answer with its own status, making this test flaky.
  23435. SSLClient cli("127.0.0.1", origin.port());
  23436. cli.enable_server_certificate_verification(false);
  23437. cli.set_proxy("127.0.0.1", proxy.port());
  23438. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23439. auto res = cli.Get("/x");
  23440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23441. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23442. EXPECT_EQ(1, origin_hits.load());
  23443. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23444. EXPECT_EQ(1, proxy.connect_hits());
  23445. }
  23446. #endif