test.cc 899 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. } // namespace tls
  69. } // namespace httplib
  70. #endif
  71. using namespace std;
  72. using namespace httplib;
  73. const char *HOST = "localhost";
  74. static int get_base_port() {
  75. const char *shard = getenv("GTEST_SHARD_INDEX");
  76. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  77. }
  78. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  79. // New standalone tests MUST use svr.bind_to_any_port() instead.
  80. const int PORT = get_base_port();
  81. const string LONG_QUERY_VALUE = string(25000, '@');
  82. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  83. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  84. const string TOO_LONG_QUERY_URL =
  85. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  86. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  87. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  88. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  89. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  90. return file.name == key;
  91. });
  92. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  93. return *it;
  94. #else
  95. if (it != items.end()) { return *it; }
  96. throw std::runtime_error("invalid multipart form data name error");
  97. #endif
  98. }
  99. static void read_file(const std::string &path, std::string &out) {
  100. std::ifstream fs(path, std::ios_base::binary);
  101. if (!fs) {
  102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  103. return;
  104. #else
  105. throw std::runtime_error("File not found: " + path);
  106. #endif
  107. }
  108. fs.seekg(0, std::ios_base::end);
  109. auto size = fs.tellg();
  110. fs.seekg(0);
  111. out.resize(static_cast<size_t>(size));
  112. fs.read(&out[0], static_cast<std::streamsize>(size));
  113. }
  114. class UnixSocketTest : public ::testing::Test {
  115. protected:
  116. void TearDown() override { std::remove(pathname_.c_str()); }
  117. void client_GET(const std::string &addr) {
  118. httplib::Client cli{addr};
  119. cli.set_address_family(AF_UNIX);
  120. ASSERT_TRUE(cli.is_valid());
  121. const auto &result = cli.Get(pattern_);
  122. ASSERT_TRUE(result) << "error: " << result.error();
  123. const auto &resp = result.value();
  124. EXPECT_EQ(resp.status, StatusCode::OK_200);
  125. EXPECT_EQ(resp.body, content_);
  126. }
  127. static std::string make_sock_path() {
  128. const char *shard = getenv("GTEST_SHARD_INDEX");
  129. return shard ? std::string("./httplib-server-") + shard + ".sock"
  130. : "./httplib-server.sock";
  131. }
  132. const std::string pathname_{make_sock_path()};
  133. const std::string pattern_{"/hi"};
  134. const std::string content_{"Hello World!"};
  135. };
  136. TEST_F(UnixSocketTest, pathname) {
  137. httplib::Server svr;
  138. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  139. res.set_content(content_, "text/plain");
  140. });
  141. std::thread t{[&] {
  142. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  143. }};
  144. auto se = detail::scope_exit([&] {
  145. svr.stop();
  146. t.join();
  147. ASSERT_FALSE(svr.is_running());
  148. });
  149. svr.wait_until_ready();
  150. ASSERT_TRUE(svr.is_running());
  151. client_GET(pathname_);
  152. }
  153. #if defined(__linux__) || \
  154. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  155. TEST_F(UnixSocketTest, PeerPid) {
  156. httplib::Server svr;
  157. std::string remote_port_val;
  158. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  159. res.set_content(content_, "text/plain");
  160. remote_port_val = std::to_string(req.remote_port);
  161. });
  162. std::thread t{[&] {
  163. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  164. }};
  165. auto se = detail::scope_exit([&] {
  166. svr.stop();
  167. t.join();
  168. ASSERT_FALSE(svr.is_running());
  169. });
  170. svr.wait_until_ready();
  171. ASSERT_TRUE(svr.is_running());
  172. client_GET(pathname_);
  173. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  174. }
  175. #endif
  176. #ifdef __linux__
  177. TEST_F(UnixSocketTest, abstract) {
  178. constexpr char svr_path[]{"\x00httplib-server.sock"};
  179. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  180. httplib::Server svr;
  181. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  182. res.set_content(content_, "text/plain");
  183. });
  184. std::thread t{[&] {
  185. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  186. }};
  187. auto se = detail::scope_exit([&] {
  188. svr.stop();
  189. t.join();
  190. ASSERT_FALSE(svr.is_running());
  191. });
  192. svr.wait_until_ready();
  193. ASSERT_TRUE(svr.is_running());
  194. client_GET(abstract_addr);
  195. }
  196. #endif
  197. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  198. httplib::Server svr;
  199. std::string received_host_header;
  200. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  201. // Capture the Host header sent by the client
  202. auto host_iter = req.headers.find("Host");
  203. if (host_iter != req.headers.end()) {
  204. received_host_header = host_iter->second;
  205. }
  206. res.set_content(content_, "text/plain");
  207. });
  208. std::thread t{[&] {
  209. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  210. }};
  211. auto se = detail::scope_exit([&] {
  212. svr.stop();
  213. t.join();
  214. ASSERT_FALSE(svr.is_running());
  215. });
  216. svr.wait_until_ready();
  217. ASSERT_TRUE(svr.is_running());
  218. // Test that Host header is automatically set to "localhost" for Unix socket
  219. // connections
  220. httplib::Client cli{pathname_};
  221. cli.set_address_family(AF_UNIX);
  222. ASSERT_TRUE(cli.is_valid());
  223. const auto &result = cli.Get(pattern_);
  224. ASSERT_TRUE(result) << "error: " << result.error();
  225. const auto &resp = result.value();
  226. EXPECT_EQ(resp.status, StatusCode::OK_200);
  227. EXPECT_EQ(resp.body, content_);
  228. // Verify that Host header was automatically set to "localhost"
  229. EXPECT_EQ(received_host_header, "localhost");
  230. }
  231. #ifndef _WIN32
  232. TEST(SocketStream, wait_writable_UNIX) {
  233. int fds[2];
  234. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  235. const auto asSocketStream = [&](socket_t fd,
  236. std::function<bool(Stream &)> func) {
  237. return detail::process_client_socket(
  238. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  239. };
  240. asSocketStream(fds[0], [&](Stream &s0) {
  241. EXPECT_EQ(s0.socket(), fds[0]);
  242. EXPECT_TRUE(s0.wait_writable());
  243. EXPECT_TRUE(s0.is_peer_alive());
  244. EXPECT_EQ(0, close(fds[1]));
  245. EXPECT_FALSE(s0.is_peer_alive());
  246. return true;
  247. });
  248. EXPECT_EQ(0, close(fds[0]));
  249. }
  250. TEST(SocketStream, wait_writable_INET) {
  251. sockaddr_in addr;
  252. memset(&addr, 0, sizeof(addr));
  253. addr.sin_family = AF_INET;
  254. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  255. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  256. int disconnected_svr_sock = -1;
  257. std::thread svr{[&] {
  258. const int s = socket(AF_INET, SOCK_STREAM, 0);
  259. ASSERT_LE(0, s);
  260. // PORT + 1 is shared with the SSL redirect tests and with
  261. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  262. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  263. // because that happens on a worker thread the ASSERT does not stop the
  264. // test: it runs on and fails at the disconnected_svr_sock check instead.
  265. default_socket_options(s);
  266. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  267. ASSERT_EQ(0, listen(s, 1));
  268. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  269. ASSERT_EQ(0, close(s));
  270. }};
  271. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  272. std::thread cli{[&] {
  273. const int s = socket(AF_INET, SOCK_STREAM, 0);
  274. ASSERT_LE(0, s);
  275. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  276. ASSERT_EQ(0, close(s));
  277. }};
  278. cli.join();
  279. svr.join();
  280. ASSERT_NE(disconnected_svr_sock, -1);
  281. const auto asSocketStream = [&](socket_t fd,
  282. std::function<bool(Stream &)> func) {
  283. return detail::process_client_socket(
  284. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  285. };
  286. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  287. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  288. // wait_writable() returns true because select_write() only checks if the
  289. // send buffer has space. Peer disconnection is detected later by send().
  290. EXPECT_TRUE(ss.wait_writable());
  291. return true;
  292. });
  293. ASSERT_EQ(0, close(disconnected_svr_sock));
  294. }
  295. #endif // #ifndef _WIN32
  296. TEST(SetSocketOptTest, TcpNoDelay) {
  297. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  298. ASSERT_NE(sock, INVALID_SOCKET);
  299. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  300. int val = 0;
  301. socklen_t len = sizeof(val);
  302. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  303. reinterpret_cast<char *>(&val), &len));
  304. EXPECT_NE(val, 0);
  305. detail::close_socket(sock);
  306. }
  307. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  308. // accept() reports failures through WSAGetLastError() on Windows and through
  309. // errno everywhere else. Asking the wrong one is what made the accept loop
  310. // treat every recoverable failure as fatal on Windows.
  311. struct Classification {
  312. bool resource;
  313. bool transient;
  314. };
  315. auto classify = [](int err) {
  316. #ifdef _WIN32
  317. WSASetLastError(err);
  318. #else
  319. errno = err;
  320. #endif
  321. // Read both before asserting: an assertion may clobber the error slot.
  322. Classification c;
  323. c.resource = detail::is_accept_resource_error();
  324. c.transient = detail::is_accept_transient_error();
  325. return c;
  326. };
  327. #ifdef _WIN32
  328. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  329. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  330. WSAECONNRESET, WSAECONNABORTED};
  331. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  332. #else
  333. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  334. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  335. ECONNABORTED};
  336. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  337. #endif
  338. for (auto err : resource_errors) {
  339. const auto c = classify(err);
  340. EXPECT_TRUE(c.resource) << "error " << err;
  341. EXPECT_FALSE(c.transient) << "error " << err;
  342. }
  343. for (auto err : transient_errors) {
  344. const auto c = classify(err);
  345. EXPECT_TRUE(c.transient) << "error " << err;
  346. EXPECT_FALSE(c.resource) << "error " << err;
  347. }
  348. for (auto err : fatal_errors) {
  349. const auto c = classify(err);
  350. EXPECT_FALSE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. #ifdef _WIN32
  354. WSASetLastError(0);
  355. #else
  356. errno = 0;
  357. #endif
  358. }
  359. TEST(ClientTest, MoveConstructible) {
  360. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  361. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  362. }
  363. TEST(ClientTest, MoveAssignable) {
  364. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  365. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  366. }
  367. #ifdef _WIN32
  368. TEST(StartupTest, WSAStartup) {
  369. WSADATA wsaData;
  370. int ret = WSAStartup(0x0002, &wsaData);
  371. ASSERT_EQ(0, ret);
  372. }
  373. #endif
  374. TEST(DecodePathTest, PercentCharacter) {
  375. EXPECT_EQ(
  376. decode_path_component(
  377. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  378. U8("descrip=Gastos áéíóúñÑ 6"));
  379. }
  380. TEST(DecodePathTest, PercentCharacterNUL) {
  381. string expected;
  382. expected.push_back('x');
  383. expected.push_back('\0');
  384. expected.push_back('x');
  385. EXPECT_EQ(decode_path_component("x%00x"), expected);
  386. }
  387. TEST(DecodePathTest, UnicodeEncoding) {
  388. // %u0041 = 'A' (1-byte UTF-8)
  389. EXPECT_EQ("A", decode_path_component("%u0041"));
  390. // %u00E9 = 'é' (2-byte UTF-8)
  391. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  392. // %u3042 = 'あ' (3-byte UTF-8)
  393. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  394. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  395. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  396. // %uD800 = surrogate (invalid, silently dropped)
  397. EXPECT_EQ("", decode_path_component("%uD800"));
  398. }
  399. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  400. // A sign or whitespace inside the two-character escape window must not be
  401. // accepted as a valid percent-encoding; the sequence is passed through
  402. // literally, matching decode_uri_component / decode_path_component.
  403. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  404. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  405. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  406. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  407. // Well-formed escapes still decode.
  408. EXPECT_EQ("-", decode_query_component("%2D", false));
  409. EXPECT_EQ("A", decode_query_component("%41", false));
  410. }
  411. TEST(SanitizeFilenameTest, VariousPatterns) {
  412. // Path traversal
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  414. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  415. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  416. // Normal and edge cases
  417. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  418. EXPECT_EQ("filename.txt",
  419. httplib::sanitize_filename("/path/to/filename.txt"));
  420. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  421. EXPECT_EQ("", httplib::sanitize_filename(".."));
  422. EXPECT_EQ("", httplib::sanitize_filename(""));
  423. // Null bytes stripped
  424. EXPECT_EQ("safe.txt",
  425. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  426. // Whitespace-only rejected
  427. EXPECT_EQ("", httplib::sanitize_filename(" "));
  428. }
  429. // Forward declaration (see the base64_encode note below): split builds move the
  430. // definition into httplib.cc, so re-declaring it here lets the test link.
  431. namespace httplib {
  432. namespace detail {
  433. bool is_chunked_transfer_encoding(const Headers &headers);
  434. } // namespace detail
  435. } // namespace httplib
  436. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  437. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  438. auto make = [](std::initializer_list<const char *> lines) {
  439. Headers h;
  440. for (auto te : lines) {
  441. if (te) { h.emplace("Transfer-Encoding", te); }
  442. }
  443. return h;
  444. };
  445. // Sole coding, matched case-insensitively.
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  449. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  453. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  457. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  458. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  459. // were received, into one list. Headers preserves that order, so the answer
  460. // is decided by the last coding of the last line and the order the lines
  461. // arrived in is significant.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  464. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  465. // The split can fall anywhere in the list.
  466. EXPECT_TRUE(
  467. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  468. EXPECT_FALSE(
  469. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  470. // A trailing line naming no coding leaves the list ending in nothing, so it
  471. // must not inherit the chunked from the line before it.
  472. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  473. }
  474. // Forward declaration: in split builds split.py strips `inline` and moves the
  475. // definition into httplib.cc, so detail::base64_encode is not visible from the
  476. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  477. // in both header-only and split builds.
  478. namespace httplib {
  479. namespace detail {
  480. std::string base64_encode(const std::string &in);
  481. } // namespace detail
  482. } // namespace httplib
  483. TEST(Base64EncodeTest, KnownAnswers) {
  484. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  485. // where the accumulator's top bit is already set before the next shift.
  486. EXPECT_EQ("", detail::base64_encode(""));
  487. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  488. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  489. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  490. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  491. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  492. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  493. // High bytes keep the top bit set across several rounds.
  494. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  495. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  496. }
  497. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  498. string unescapedCharacters = "-_.!~*'()";
  499. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  500. }
  501. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  502. string reservedCharacters = ";,/?:@&=+$";
  503. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  504. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  505. }
  506. TEST(ClientQueryOrder, PreserveOrder) {
  507. // This test reproduces Issue #2259: client may reorder query parameters
  508. // when sending a GET request. The expected behavior is that the client
  509. // preserves the original query string order when the caller supplied it
  510. // as part of the path.
  511. Server svr;
  512. svr.Get("/", [&](const Request &req, Response &res) {
  513. // Echo back the raw target so the test can assert ordering
  514. res.set_content(req.target, "text/plain");
  515. });
  516. std::thread t{[&] { svr.listen(HOST, PORT); }};
  517. auto se = detail::scope_exit([&] {
  518. svr.stop();
  519. t.join();
  520. ASSERT_FALSE(svr.is_running());
  521. });
  522. svr.wait_until_ready();
  523. Client cli(HOST, PORT);
  524. ASSERT_TRUE(cli.is_valid());
  525. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  526. auto res = cli.Get(original);
  527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  528. // Expect the echoed target to exactly match the original path (order
  529. // preserved)
  530. EXPECT_EQ(res->body, original);
  531. }
  532. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  533. string chineseCharacters = U8("中国語");
  534. string russianCharacters = U8("дом");
  535. string brazilianCharacters = U8("óculos");
  536. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  537. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  538. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  539. "%D0%B4%D0%BE%D0%BC");
  540. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  541. }
  542. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  543. string unescapedCharacters = "-_.!~*'()";
  544. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  545. }
  546. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  547. string reservedCharacters = ";,/?:@&=+$";
  548. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  549. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  550. }
  551. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  552. string chineseCharacters = U8("中国語");
  553. string russianCharacters = U8("дом");
  554. string brazilianCharacters = U8("óculos");
  555. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  556. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  557. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  558. "%D0%B4%D0%BE%D0%BC");
  559. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  560. }
  561. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  562. // Issue #2082 use case: encoding path component with ampersand
  563. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  564. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  565. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  566. }
  567. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  568. string unescapedCharacters = "-_.!~*'()";
  569. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  570. }
  571. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  572. string reservedCharacters = ";,/?:@&=+$#";
  573. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  574. }
  575. TEST(EncodeUriTest, TestUTF8Characters) {
  576. string chineseCharacters = U8("中国語");
  577. string russianCharacters = U8("дом");
  578. string brazilianCharacters = U8("óculos");
  579. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  580. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  581. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  582. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  583. }
  584. TEST(EncodeUriTest, TestCompleteUri) {
  585. string uri =
  586. "https://example.com/path/to/resource?query=value&param=test#fragment";
  587. EXPECT_EQ(
  588. httplib::encode_uri(uri),
  589. "https://example.com/path/to/resource?query=value&param=test#fragment");
  590. }
  591. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  592. string uri =
  593. "https://example.com/path with spaces/file name.html?q=hello world";
  594. EXPECT_EQ(httplib::encode_uri(uri),
  595. "https://example.com/path%20with%20spaces/"
  596. "file%20name.html?q=hello%20world");
  597. }
  598. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  599. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  600. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  601. }
  602. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  603. string unescapedCharacters = "-_.!~*'()";
  604. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  605. }
  606. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  607. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  608. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  609. string encodedBrazilian = "%C3%B3culos";
  610. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  612. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  613. }
  614. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  615. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  616. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  617. "Piri Tommy Villiers - on & on");
  618. }
  619. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  620. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  621. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  622. }
  623. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  624. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  625. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  626. }
  627. TEST(DecodeUriTest, TestUTF8Characters) {
  628. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  629. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  630. string encodedBrazilian = "%C3%B3culos";
  631. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  632. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  633. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  634. }
  635. TEST(DecodeUriTest, TestCompleteUri) {
  636. string encodedUri = "https://example.com/path%20with%20spaces/"
  637. "file%20name.html?q=hello%20world";
  638. EXPECT_EQ(
  639. httplib::decode_uri(encodedUri),
  640. "https://example.com/path with spaces/file name.html?q=hello world");
  641. }
  642. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  643. string original =
  644. "https://example.com/path with spaces/file name.html?q=hello world";
  645. string encoded = httplib::encode_uri(original);
  646. string decoded = httplib::decode_uri(encoded);
  647. EXPECT_EQ(decoded, original);
  648. }
  649. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  650. // decode_uri is the inverse of encode_uri: an escaped reserved character
  651. // stays encoded so it is not promoted into a real delimiter, while
  652. // non-reserved escapes still decode (like JS decodeURI).
  653. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  654. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  655. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  656. "%3F%3A%40%26%3D%2B%24%2C%3B");
  657. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  658. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  659. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  660. "http://example.com/a%2Fb");
  661. // decode_uri_component still decodes the reserved character.
  662. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  663. }
  664. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  665. string original = "Piri Tommy Villiers - on & on";
  666. string encoded = httplib::encode_uri_component(original);
  667. string decoded = httplib::decode_uri_component(encoded);
  668. EXPECT_EQ(decoded, original);
  669. }
  670. TEST(TrimTests, TrimStringTests) {
  671. EXPECT_EQ("abc", detail::trim_copy("abc"));
  672. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  673. EXPECT_TRUE(detail::trim_copy("").empty());
  674. }
  675. TEST(AsciiTest, LocaleIndependentClassification) {
  676. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  677. // which consult the global C locale: std::isalnum(0xC5) can return true
  678. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  679. // helpers must classify every byte by the ASCII grammar alone.
  680. for (int i = 0; i < 256; i++) {
  681. auto c = static_cast<char>(i);
  682. auto is_digit = i >= '0' && i <= '9';
  683. auto is_upper = i >= 'A' && i <= 'Z';
  684. auto is_lower = i >= 'a' && i <= 'z';
  685. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  686. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  687. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  688. << "byte " << i;
  689. }
  690. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  691. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  692. // Non-ASCII bytes must be percent-encoded, never passed through as
  693. // alphanumeric.
  694. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  695. }
  696. TEST(FromCharsTest, Double) {
  697. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  698. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  699. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  700. auto parse = [](const std::string &s, double &v) {
  701. return detail::from_chars(s.data(), s.data() + s.size(), v);
  702. };
  703. double v = -1.0;
  704. // Representative quality values.
  705. EXPECT_EQ(parse("0", v).ec, std::errc{});
  706. EXPECT_DOUBLE_EQ(v, 0.0);
  707. EXPECT_EQ(parse("1", v).ec, std::errc{});
  708. EXPECT_DOUBLE_EQ(v, 1.0);
  709. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  710. EXPECT_DOUBLE_EQ(v, 0.8);
  711. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  712. EXPECT_DOUBLE_EQ(v, 0.001);
  713. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 1.0);
  715. // A missing integer or fractional part is tolerated.
  716. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  717. EXPECT_DOUBLE_EQ(v, 0.5);
  718. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 5.0);
  720. // Values outside [0, 1] still parse; the caller range-checks them.
  721. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  722. EXPECT_DOUBLE_EQ(v, 123.456);
  723. // Stops at the first byte that is not part of the number and reports where.
  724. std::string trailing = "0.9, text/html";
  725. auto r = parse(trailing, v);
  726. EXPECT_EQ(r.ec, std::errc{});
  727. EXPECT_DOUBLE_EQ(v, 0.9);
  728. EXPECT_EQ(*r.ptr, ',');
  729. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  730. // outright, and an 'e'/'E' simply ends the number.
  731. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  732. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  733. std::string exp_input = "1.5e3";
  734. r = parse(exp_input, v);
  735. EXPECT_EQ(r.ec, std::errc{});
  736. EXPECT_DOUBLE_EQ(v, 1.5);
  737. EXPECT_EQ(*r.ptr, 'e');
  738. // Invalid inputs.
  739. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  743. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  744. // Pathological but well-formed inputs must stay bounded (no overflow, no
  745. // out-of-bounds table access) and stay within [0, 1] for the caller.
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  747. std::errc{});
  748. EXPECT_DOUBLE_EQ(v, 0.0);
  749. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  750. std::errc{});
  751. EXPECT_GE(v, 0.0);
  752. EXPECT_LE(v, 1.0);
  753. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  754. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  755. }
  756. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  757. // Simple case without quality values
  758. std::vector<std::string> result1;
  759. EXPECT_TRUE(detail::parse_accept_header(
  760. "text/html,application/json,text/plain", result1));
  761. EXPECT_EQ(result1.size(), 3U);
  762. EXPECT_EQ(result1[0], "text/html");
  763. EXPECT_EQ(result1[1], "application/json");
  764. EXPECT_EQ(result1[2], "text/plain");
  765. // With quality values
  766. std::vector<std::string> result2;
  767. EXPECT_TRUE(detail::parse_accept_header(
  768. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  769. EXPECT_EQ(result2.size(), 3U);
  770. EXPECT_EQ(result2[0], "application/json"); // highest q value
  771. EXPECT_EQ(result2[1], "text/html");
  772. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  773. }
  774. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  775. // Mixed with and without quality values
  776. std::vector<std::string> result;
  777. EXPECT_TRUE(detail::parse_accept_header(
  778. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  779. EXPECT_EQ(result.size(), 3U);
  780. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  781. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  782. EXPECT_EQ(result[2], "application/json"); // q=0.5
  783. }
  784. TEST(ParseAcceptHeaderTest, EdgeCases) {
  785. // Empty header
  786. std::vector<std::string> empty_result;
  787. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  788. EXPECT_TRUE(empty_result.empty());
  789. // Single type
  790. std::vector<std::string> single_result;
  791. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  792. EXPECT_EQ(single_result.size(), 1U);
  793. EXPECT_EQ(single_result[0], "application/json");
  794. // Wildcard types
  795. std::vector<std::string> wildcard_result;
  796. EXPECT_TRUE(detail::parse_accept_header(
  797. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  798. EXPECT_EQ(wildcard_result.size(), 3U);
  799. EXPECT_EQ(wildcard_result[0], "application/json");
  800. EXPECT_EQ(wildcard_result[1], "text/*");
  801. EXPECT_EQ(wildcard_result[2], "*/*");
  802. }
  803. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  804. // Common browser Accept header
  805. std::vector<std::string> browser_result;
  806. EXPECT_TRUE(
  807. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  808. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  809. browser_result));
  810. EXPECT_EQ(browser_result.size(), 6U);
  811. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  815. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  816. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  817. // API client header
  818. std::vector<std::string> api_result;
  819. EXPECT_TRUE(detail::parse_accept_header(
  820. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  821. api_result));
  822. EXPECT_EQ(api_result.size(), 3U);
  823. EXPECT_EQ(api_result[0], "application/json");
  824. EXPECT_EQ(api_result[1], "application/xml");
  825. EXPECT_EQ(api_result[2], "text/plain");
  826. }
  827. TEST(ParseAcceptHeaderTest, SpecialCases) {
  828. // Quality value with 3 decimal places
  829. std::vector<std::string> decimal_result;
  830. EXPECT_TRUE(detail::parse_accept_header(
  831. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  832. EXPECT_EQ(decimal_result.size(), 2U);
  833. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  834. EXPECT_EQ(decimal_result[1], "text/html");
  835. // Zero quality (should still be included but with lowest priority)
  836. std::vector<std::string> zero_q_result;
  837. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  838. zero_q_result));
  839. EXPECT_EQ(zero_q_result.size(), 2U);
  840. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  841. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  842. // No spaces around commas
  843. std::vector<std::string> no_space_result;
  844. EXPECT_TRUE(detail::parse_accept_header(
  845. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  846. no_space_result));
  847. EXPECT_EQ(no_space_result.size(), 3U);
  848. EXPECT_EQ(no_space_result[0], "text/html");
  849. EXPECT_EQ(no_space_result[1], "application/json");
  850. EXPECT_EQ(no_space_result[2], "text/plain");
  851. }
  852. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  853. // Quality values always use '.' as the decimal separator, so parsing must
  854. // not depend on the process locale. An embedding application may have
  855. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  856. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  857. std::string saved = cur ? cur : "C";
  858. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  859. "fr_FR.UTF-8"};
  860. bool switched = false;
  861. for (const auto loc : comma_locales) {
  862. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  863. std::localeconv()->decimal_point[0] == ',') {
  864. switched = true;
  865. break;
  866. }
  867. }
  868. if (!switched) {
  869. std::setlocale(LC_NUMERIC, saved.c_str());
  870. GTEST_SKIP() << "no comma-decimal locale available on this host";
  871. }
  872. // The higher-weighted type appears later in the list, so a correct parse
  873. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  874. // sensitive parse reads both weights as 0 and leaves the original order.
  875. std::vector<std::string> result;
  876. EXPECT_TRUE(detail::parse_accept_header(
  877. "application/json;q=0.1,text/html;q=0.9", result));
  878. ASSERT_EQ(result.size(), 2U);
  879. EXPECT_EQ(result[0], "text/html");
  880. EXPECT_EQ(result[1], "application/json");
  881. std::setlocale(LC_NUMERIC, saved.c_str());
  882. }
  883. TEST(ParseAcceptHeaderTest, InvalidCases) {
  884. std::vector<std::string> result;
  885. // Invalid quality value (> 1.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  888. // Invalid quality value (< 0.0)
  889. EXPECT_FALSE(
  890. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  891. // Invalid quality value (not a number)
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=invalid,application/json", result));
  894. // A valid numeric prefix does not make the entire quality value valid.
  895. EXPECT_FALSE(detail::parse_accept_header(
  896. "text/html;q=0.5junk,application/json", result));
  897. // Empty quality value
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("text/html;q=,application/json", result));
  900. // Invalid media type format (no slash and not wildcard)
  901. EXPECT_FALSE(
  902. detail::parse_accept_header("invalidtype,application/json", result));
  903. // Valid cases should still work
  904. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*/*");
  907. EXPECT_TRUE(detail::parse_accept_header("*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "*");
  910. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  911. EXPECT_EQ(result.size(), 1U);
  912. EXPECT_EQ(result[0], "text/*");
  913. }
  914. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  915. // elements, so a leading, trailing or doubled comma is a legal Accept value
  916. // and must not be answered with 400 Bad Request.
  917. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  918. struct {
  919. const char *value;
  920. std::vector<std::string> expected;
  921. } cases[] = {
  922. {",application/json", {"application/json"}},
  923. {"text/html,", {"text/html"}},
  924. {"text/html,,*/*", {"text/html", "*/*"}},
  925. // An empty element may be spelled with whitespace in it
  926. {"text/html, , application/json", {"text/html", "application/json"}},
  927. // Nothing but empty elements is an empty list, which means the same
  928. // thing as no Accept header at all
  929. {",,,", {}},
  930. // Quality values still apply across ignored empty elements
  931. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  932. };
  933. for (const auto &c : cases) {
  934. std::vector<std::string> result;
  935. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  936. << "value: " << c.value;
  937. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  938. }
  939. // An invalid entry is still rejected when empty elements surround it
  940. std::vector<std::string> result;
  941. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  942. }
  943. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  944. // or ';' inside one does not end the list element or the parameter. Section
  945. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  946. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  947. struct {
  948. const char *value;
  949. std::vector<std::string> expected;
  950. } cases[] = {
  951. {"text/html;profile=\"a,b\",application/json",
  952. {"text/html", "application/json"}},
  953. // A "q=" inside a quoted value is not the weight
  954. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  955. {"text/html", "application/json"}},
  956. // The weight after a quoted value still applies
  957. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  958. {"application/json", "text/html"}},
  959. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  960. {"application/json", "text/html"}},
  961. {"text/html;profile=\"a\\\"b\",application/json",
  962. {"text/html", "application/json"}},
  963. // An escaped backslash does not escape the '"' after it
  964. {"text/html;profile=\"a\\\\\",application/json",
  965. {"text/html", "application/json"}},
  966. };
  967. for (const auto &c : cases) {
  968. std::vector<std::string> result;
  969. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  970. << "value: " << c.value;
  971. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  972. }
  973. }
  974. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  975. Server svr;
  976. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  977. EXPECT_EQ(req.accept_content_types.size(), 3U);
  978. EXPECT_EQ(req.accept_content_types[0], "application/json");
  979. EXPECT_EQ(req.accept_content_types[1], "text/html");
  980. EXPECT_EQ(req.accept_content_types[2], "*/*");
  981. res.set_content("ok", "text/plain");
  982. });
  983. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  984. EXPECT_TRUE(false);
  985. res.set_content("bad request", "text/plain");
  986. });
  987. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. listen_thread.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. Client cli("localhost", PORT);
  995. {
  996. auto res = cli.Get(
  997. "/accept_ok",
  998. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. }
  1002. {
  1003. auto res = cli.Get("/accept_bad_request",
  1004. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1006. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1007. }
  1008. }
  1009. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1010. Server svr;
  1011. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1012. res.set_content("ok", "text/plain");
  1013. });
  1014. std::atomic<int> start_count{0};
  1015. std::atomic<bool> running_when_called{false};
  1016. svr.set_start_handler([&]() {
  1017. running_when_called = svr.is_running();
  1018. start_count++;
  1019. });
  1020. auto port = svr.bind_to_any_port(HOST);
  1021. std::thread t([&]() { svr.listen_after_bind(); });
  1022. auto se = detail::scope_exit([&] {
  1023. svr.stop();
  1024. t.join();
  1025. ASSERT_FALSE(svr.is_running());
  1026. });
  1027. svr.wait_until_ready();
  1028. // A successful request proves the accept loop is running, which the start
  1029. // handler precedes; so by now the handler must have run exactly once.
  1030. Client cli(HOST, port);
  1031. cli.set_connection_timeout(std::chrono::seconds(5));
  1032. auto res = cli.Get("/");
  1033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1034. EXPECT_EQ(StatusCode::OK_200, res->status);
  1035. EXPECT_EQ(1, start_count.load());
  1036. EXPECT_TRUE(running_when_called.load());
  1037. }
  1038. TEST(DivideTest, DivideStringTests) {
  1039. auto divide = [](const std::string &str, char d) {
  1040. std::string lhs;
  1041. std::string rhs;
  1042. detail::divide(str, d,
  1043. [&](const char *lhs_data, std::size_t lhs_size,
  1044. const char *rhs_data, std::size_t rhs_size) {
  1045. lhs.assign(lhs_data, lhs_size);
  1046. rhs.assign(rhs_data, rhs_size);
  1047. });
  1048. return std::make_pair(std::move(lhs), std::move(rhs));
  1049. };
  1050. {
  1051. const auto res = divide("", '=');
  1052. EXPECT_EQ(res.first, "");
  1053. EXPECT_EQ(res.second, "");
  1054. }
  1055. {
  1056. const auto res = divide("=", '=');
  1057. EXPECT_EQ(res.first, "");
  1058. EXPECT_EQ(res.second, "");
  1059. }
  1060. {
  1061. const auto res = divide(" ", '=');
  1062. EXPECT_EQ(res.first, " ");
  1063. EXPECT_EQ(res.second, "");
  1064. }
  1065. {
  1066. const auto res = divide("a", '=');
  1067. EXPECT_EQ(res.first, "a");
  1068. EXPECT_EQ(res.second, "");
  1069. }
  1070. {
  1071. const auto res = divide("a=", '=');
  1072. EXPECT_EQ(res.first, "a");
  1073. EXPECT_EQ(res.second, "");
  1074. }
  1075. {
  1076. const auto res = divide("=b", '=');
  1077. EXPECT_EQ(res.first, "");
  1078. EXPECT_EQ(res.second, "b");
  1079. }
  1080. {
  1081. const auto res = divide("a=b", '=');
  1082. EXPECT_EQ(res.first, "a");
  1083. EXPECT_EQ(res.second, "b");
  1084. }
  1085. {
  1086. const auto res = divide("a=b=", '=');
  1087. EXPECT_EQ(res.first, "a");
  1088. EXPECT_EQ(res.second, "b=");
  1089. }
  1090. {
  1091. const auto res = divide("a=b=c", '=');
  1092. EXPECT_EQ(res.first, "a");
  1093. EXPECT_EQ(res.second, "b=c");
  1094. }
  1095. }
  1096. TEST(SplitTest, ParseQueryString) {
  1097. string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1100. [&](const char *b, const char *e) {
  1101. string key, val;
  1102. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1103. if (key.empty()) {
  1104. key.assign(b2, e2);
  1105. } else {
  1106. val.assign(b2, e2);
  1107. }
  1108. });
  1109. dic.emplace(key, val);
  1110. });
  1111. EXPECT_EQ("val1", dic.find("key1")->second);
  1112. EXPECT_EQ("val2", dic.find("key2")->second);
  1113. EXPECT_EQ("val3", dic.find("key3")->second);
  1114. }
  1115. TEST(SplitTest, ParseInvalidQueryTests) {
  1116. {
  1117. string s = " ";
  1118. Params dict;
  1119. detail::parse_query_text(s, dict);
  1120. EXPECT_TRUE(dict.empty());
  1121. }
  1122. {
  1123. string s = " = =";
  1124. Params dict;
  1125. detail::parse_query_text(s, dict);
  1126. EXPECT_TRUE(dict.empty());
  1127. }
  1128. }
  1129. TEST(ParseQueryTest, ParseQueryString) {
  1130. {
  1131. std::string s = "key1=val1&key2=val2&key3=val3";
  1132. Params dic;
  1133. detail::parse_query_text(s, dic);
  1134. EXPECT_EQ("val1", dic.find("key1")->second);
  1135. EXPECT_EQ("val2", dic.find("key2")->second);
  1136. EXPECT_EQ("val3", dic.find("key3")->second);
  1137. }
  1138. {
  1139. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1140. Params dic;
  1141. detail::parse_query_text(s, dic);
  1142. EXPECT_EQ("", dic.find("key1")->second);
  1143. EXPECT_EQ("val1", dic.find("key2")->second);
  1144. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1145. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1146. }
  1147. }
  1148. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1149. Params dic;
  1150. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1151. dic.emplace("key1", "val1");
  1152. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1153. dic.emplace("key2", "val2");
  1154. dic.emplace("key3", "val3");
  1155. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1156. }
  1157. // Joins every entry of a Headers or Params into "key=value " so a whole
  1158. // traversal can be compared in one assertion. Both are instantiations of the
  1159. // same insertion-ordered container, so one helper serves both.
  1160. template <typename Map> static std::string entries_to_string(const Map &m) {
  1161. std::string s;
  1162. for (const auto &entry : m) {
  1163. s += entry.first + "=" + entry.second + " ";
  1164. }
  1165. return s;
  1166. }
  1167. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1168. // Params used to be a std::multimap, which sorted by name and handed the
  1169. // caller's query back alphabetised. A client signing its query string could
  1170. // not reproduce the order it asked for.
  1171. Params dic;
  1172. dic.emplace("zulu", "1");
  1173. dic.emplace("alpha", "2");
  1174. dic.emplace("mike", "3");
  1175. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1176. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1177. }
  1178. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1179. Params dic;
  1180. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1181. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1182. }
  1183. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1184. Request req;
  1185. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1186. req.params);
  1187. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1188. EXPECT_EQ("first", req.get_param_value("tag"));
  1189. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1190. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1191. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1192. EXPECT_EQ("", req.get_param_value("tag", 3));
  1193. }
  1194. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1195. // Params shares its container with Headers, which matches field names
  1196. // case-insensitively. Parameter names must not pick that up.
  1197. Params dic;
  1198. dic.emplace("Key", "upper");
  1199. dic.emplace("key", "lower");
  1200. EXPECT_EQ(2U, dic.size());
  1201. EXPECT_EQ(1U, dic.count("Key"));
  1202. EXPECT_EQ(1U, dic.count("key"));
  1203. EXPECT_EQ("upper", dic.find("Key")->second);
  1204. EXPECT_EQ("lower", dic.find("key")->second);
  1205. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1206. }
  1207. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1208. Server svr;
  1209. std::string order;
  1210. svr.Get("/order", [&](const Request &req, Response &res) {
  1211. order = entries_to_string(req.params);
  1212. res.set_content("ok", "text/plain");
  1213. });
  1214. auto port = svr.bind_to_any_port(HOST);
  1215. thread t = thread([&] { svr.listen_after_bind(); });
  1216. auto se = detail::scope_exit([&] {
  1217. svr.stop();
  1218. t.join();
  1219. ASSERT_FALSE(svr.is_running());
  1220. });
  1221. svr.wait_until_ready();
  1222. Client cli(HOST, port);
  1223. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1226. }
  1227. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1228. Server svr;
  1229. std::string field_order, file_order;
  1230. svr.Post("/order", [&](const Request &req, Response &res) {
  1231. for (const auto &field : req.form.fields) {
  1232. field_order += field.first + "=" + field.second.content + " ";
  1233. }
  1234. for (const auto &file : req.form.files) {
  1235. file_order += file.first + "=" + file.second.filename + " ";
  1236. }
  1237. res.set_content("ok", "text/plain");
  1238. });
  1239. auto port = svr.bind_to_any_port(HOST);
  1240. thread t = thread([&] { svr.listen_after_bind(); });
  1241. auto se = detail::scope_exit([&] {
  1242. svr.stop();
  1243. t.join();
  1244. ASSERT_FALSE(svr.is_running());
  1245. });
  1246. svr.wait_until_ready();
  1247. UploadFormDataItems items = {
  1248. {"zulu", "1", "", ""},
  1249. {"alpha", "2", "", ""},
  1250. {"mike", "3", "", ""},
  1251. {"zebra", "z", "z.txt", "text/plain"},
  1252. {"apple", "a", "a.txt", "text/plain"},
  1253. };
  1254. Client cli(HOST, port);
  1255. auto res = cli.Post("/order", items);
  1256. ASSERT_TRUE(res);
  1257. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1258. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1259. }
  1260. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1261. Server svr;
  1262. std::vector<std::string> values;
  1263. std::string first, second, out_of_range, order;
  1264. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1265. values = req.form.get_fields("tag");
  1266. first = req.form.get_field("tag", 0);
  1267. second = req.form.get_field("tag", 1);
  1268. out_of_range = req.form.get_field("tag", 2);
  1269. for (const auto &field : req.form.fields) {
  1270. order += field.first + "=" + field.second.content + " ";
  1271. }
  1272. res.set_content("ok", "text/plain");
  1273. });
  1274. auto port = svr.bind_to_any_port(HOST);
  1275. thread t = thread([&] { svr.listen_after_bind(); });
  1276. auto se = detail::scope_exit([&] {
  1277. svr.stop();
  1278. t.join();
  1279. ASSERT_FALSE(svr.is_running());
  1280. });
  1281. svr.wait_until_ready();
  1282. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1283. // not adjacent in the container.
  1284. UploadFormDataItems items = {
  1285. {"tag", "first", "", ""},
  1286. {"other", "x", "", ""},
  1287. {"tag", "second", "", ""},
  1288. };
  1289. Client cli(HOST, port);
  1290. auto res = cli.Post("/repeated", items);
  1291. ASSERT_TRUE(res);
  1292. ASSERT_EQ(2U, values.size());
  1293. EXPECT_EQ("first", values[0]);
  1294. EXPECT_EQ("second", values[1]);
  1295. EXPECT_EQ("first", first);
  1296. EXPECT_EQ("second", second);
  1297. // std::multimap already kept entries sharing a name in insertion order, so
  1298. // everything above passes without this change too. The whole traversal is
  1299. // what tells the two apart: sorting by name would hoist "other" to the front
  1300. // and the two "tag" parts would end up adjacent.
  1301. EXPECT_EQ("tag=first other=x tag=second ", order);
  1302. // Advancing past the last entry of a name used to run off the container;
  1303. // the container's saturating increment makes it return the default instead.
  1304. EXPECT_EQ("", out_of_range);
  1305. }
  1306. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1307. // Server::read_content() keeps a FormFields::iterator alive across the
  1308. // content callbacks that fill the part it points at. The container is
  1309. // vector-backed, so a later emplace can reallocate and invalidate an older
  1310. // iterator; 64 parts grow the vector through seven reallocations, which
  1311. // checks that every part's content still lands in its own entry.
  1312. const size_t part_count = 64;
  1313. // One formula for both the parts sent and the values expected back, so the
  1314. // two cannot drift apart.
  1315. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1316. auto content_of = [](size_t i) {
  1317. return std::string(64, static_cast<char>('a' + (i % 26)));
  1318. };
  1319. Server svr;
  1320. std::vector<std::pair<std::string, std::string>> received;
  1321. svr.Post("/many", [&](const Request &req, Response &res) {
  1322. for (const auto &field : req.form.fields) {
  1323. received.emplace_back(field.first, field.second.content);
  1324. }
  1325. res.set_content("ok", "text/plain");
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. thread t = thread([&] { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. UploadFormDataItems items;
  1336. for (size_t i = 0; i < part_count; i++) {
  1337. items.push_back({name_of(i), content_of(i), "", ""});
  1338. }
  1339. Client cli(HOST, port);
  1340. auto res = cli.Post("/many", items);
  1341. ASSERT_TRUE(res);
  1342. ASSERT_EQ(part_count, received.size());
  1343. for (size_t i = 0; i < part_count; i++) {
  1344. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1345. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1346. }
  1347. }
  1348. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1349. string content_type = "multipart/form-data; boundary=something";
  1350. string boundary;
  1351. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1352. EXPECT_TRUE(ret);
  1353. EXPECT_EQ(boundary, "something");
  1354. }
  1355. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1356. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1357. string boundary;
  1358. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1359. EXPECT_TRUE(ret);
  1360. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1361. }
  1362. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1363. string content_type =
  1364. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1365. string boundary;
  1366. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1367. EXPECT_TRUE(ret);
  1368. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1369. }
  1370. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1371. string content_type =
  1372. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1373. string boundary;
  1374. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1375. EXPECT_TRUE(ret);
  1376. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1377. }
  1378. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1379. const string boundary(70, 'a');
  1380. string content_type = "multipart/form-data; boundary=" + boundary;
  1381. string parsed;
  1382. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1383. EXPECT_TRUE(ret);
  1384. EXPECT_EQ(parsed, boundary);
  1385. }
  1386. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1387. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1388. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1389. string parsed;
  1390. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1391. EXPECT_FALSE(ret);
  1392. }
  1393. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1394. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1395. // is 72 characters on the wire and still valid.
  1396. const string boundary(70, 'a');
  1397. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1398. string parsed;
  1399. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1400. EXPECT_EQ(parsed, boundary);
  1401. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1402. parsed.clear();
  1403. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1404. }
  1405. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1406. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1407. // The parameter parser must not treat that '=' as the key/value separator.
  1408. string content_type =
  1409. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1410. "charset=UTF-8";
  1411. string parsed;
  1412. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1413. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1414. }
  1415. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1416. // A ';' inside the quoted-string is part of the value, not a parameter
  1417. // separator, so it must not truncate the boundary.
  1418. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1419. string parsed;
  1420. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1421. EXPECT_EQ(parsed, "a;b");
  1422. }
  1423. TEST(ParseDispositionParamsTest, QuotedValues) {
  1424. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1425. // ';' and '=' are ordinary characters inside one.
  1426. struct {
  1427. const char *value;
  1428. std::vector<std::pair<const char *, const char *>> expected;
  1429. } cases[] = {
  1430. {"name=\"file1\"; filename=\"a.txt\"",
  1431. {{"name", "file1"}, {"filename", "a.txt"}}},
  1432. // Whitespace around '=' and ';' is still trimmed
  1433. {"name=\"file2\" ;filename = \"a.html\"",
  1434. {{"name", "file2"}, {"filename", "a.html"}}},
  1435. // '=' inside the value used to leave only the text after the last one
  1436. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1437. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1438. {"name=\"x=y\"", {{"name", "x=y"}}},
  1439. // ';' inside the value used to truncate the pair and leave a bogus one
  1440. {"name=\"file3\"; filename=\"a;b.txt\"",
  1441. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1442. // An unquoted value keeps working, and so does filename*
  1443. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1444. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1445. // A parameter with no key is dropped rather than turned into one whose
  1446. // key is the value
  1447. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1448. };
  1449. for (const auto &c : cases) {
  1450. Params params;
  1451. detail::parse_disposition_params(c.value, params);
  1452. for (const auto &kv : c.expected) {
  1453. auto it = params.find(kv.first);
  1454. ASSERT_NE(it, params.end())
  1455. << "value: " << c.value << ", key: " << kv.first;
  1456. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1457. }
  1458. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1459. }
  1460. }
  1461. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1462. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1463. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1464. Server svr;
  1465. std::string field_value, file_name, file_filename;
  1466. bool has_field = false, has_file = false;
  1467. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1468. has_field = req.form.has_field("x=y");
  1469. field_value = req.form.get_field("x=y");
  1470. has_file = req.form.has_file("file1");
  1471. const auto &file = req.form.get_file("file1");
  1472. file_name = file.name;
  1473. file_filename = file.filename;
  1474. res.set_content("ok", "text/plain");
  1475. });
  1476. auto port = svr.bind_to_any_port(HOST);
  1477. thread t = thread([&] { svr.listen_after_bind(); });
  1478. auto se = detail::scope_exit([&] {
  1479. svr.stop();
  1480. t.join();
  1481. ASSERT_FALSE(svr.is_running());
  1482. });
  1483. svr.wait_until_ready();
  1484. UploadFormDataItems items = {
  1485. {"x=y", "field-value", "", ""},
  1486. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1487. };
  1488. Client cli(HOST, port);
  1489. auto res = cli.Post("/quoted", items);
  1490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1491. ASSERT_EQ(StatusCode::OK_200, res->status);
  1492. EXPECT_TRUE(has_field);
  1493. EXPECT_EQ("field-value", field_value);
  1494. EXPECT_TRUE(has_file);
  1495. EXPECT_EQ("file1", file_name);
  1496. EXPECT_EQ("a;b=report.pdf", file_filename);
  1497. }
  1498. TEST(GetHeaderValueTest, DefaultValue) {
  1499. Headers headers = {{"Dummy", "Dummy"}};
  1500. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1501. EXPECT_STREQ("text/plain", val);
  1502. }
  1503. TEST(GetHeaderValueTest, DefaultValueInt) {
  1504. Headers headers = {{"Dummy", "Dummy"}};
  1505. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1506. EXPECT_EQ(100ull, val);
  1507. }
  1508. TEST(GetHeaderValueTest, RegularValue) {
  1509. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1510. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1511. EXPECT_STREQ("text/html", val);
  1512. }
  1513. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1514. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1515. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1516. EXPECT_STREQ("text/html", val);
  1517. }
  1518. TEST(GetHeaderValueTest, SetContent) {
  1519. Response res;
  1520. res.set_content("html", "text/html");
  1521. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1522. res.set_content("text", "text/plain");
  1523. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1524. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1525. }
  1526. TEST(GetHeaderValueTest, RegularValueInt) {
  1527. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1528. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1529. EXPECT_EQ(100ull, val);
  1530. }
  1531. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1532. Headers headers = {{"Content-Length", "x"}};
  1533. auto is_invalid_value = false;
  1534. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1535. is_invalid_value);
  1536. EXPECT_EQ(0ull, val);
  1537. EXPECT_TRUE(is_invalid_value);
  1538. }
  1539. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1540. // An all-digit value that overflows size_t must be reported as invalid, not
  1541. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1542. // a large length to a small one on 32-bit builds, leaving the framing length
  1543. // wrong while is_invalid_value stayed false.
  1544. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1545. auto is_invalid_value = false;
  1546. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1547. is_invalid_value);
  1548. EXPECT_TRUE(is_invalid_value);
  1549. // A well-formed length is unaffected.
  1550. Headers ok = {{"Content-Length", "1234"}};
  1551. is_invalid_value = false;
  1552. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1553. is_invalid_value);
  1554. EXPECT_EQ(1234ull, val);
  1555. EXPECT_FALSE(is_invalid_value);
  1556. }
  1557. TEST(GetHeaderValueTest, Range) {
  1558. {
  1559. Headers headers = {make_range_header({{1, -1}})};
  1560. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1561. EXPECT_STREQ("bytes=1-", val);
  1562. }
  1563. {
  1564. Headers headers = {make_range_header({{-1, 1}})};
  1565. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1566. EXPECT_STREQ("bytes=-1", val);
  1567. }
  1568. {
  1569. Headers headers = {make_range_header({{1, 10}})};
  1570. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1571. EXPECT_STREQ("bytes=1-10", val);
  1572. }
  1573. {
  1574. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1575. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1576. EXPECT_STREQ("bytes=1-10, 100-", val);
  1577. }
  1578. {
  1579. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1580. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1581. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1582. }
  1583. {
  1584. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1585. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1586. EXPECT_STREQ("bytes=0-0, -1", val);
  1587. }
  1588. }
  1589. TEST(BearerTokenAuthTest, SchemeValidation) {
  1590. // A value shorter than "Bearer " must not throw from the fixed-length
  1591. // substr, and a non-Bearer scheme must not be reported as a token.
  1592. struct {
  1593. const char *value;
  1594. const char *expected;
  1595. } cases[] = {
  1596. {"x", ""},
  1597. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1598. {"Bearer abc123", "abc123"},
  1599. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1600. };
  1601. for (const auto &c : cases) {
  1602. Request req;
  1603. req.set_header("Authorization", c.value);
  1604. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1605. }
  1606. }
  1607. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1608. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1609. // to depend on the standard library (libstdc++ handed back duplicates in
  1610. // reverse insertion order, libc++ in insertion order).
  1611. Request req;
  1612. req.set_header("Accept-Encoding", "gzip");
  1613. req.set_header("Accept-Encoding", "deflate");
  1614. req.set_header("Accept-Encoding", "br");
  1615. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1616. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1617. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1618. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1619. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1620. }
  1621. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1622. Request req;
  1623. req.set_header("X-Test", "only");
  1624. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1625. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1626. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1627. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1628. }
  1629. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1630. Request req;
  1631. req.set_header("X-First", "1");
  1632. req.set_header("X-Test", "2");
  1633. req.params.emplace("first", "1");
  1634. req.params.emplace("test", "2");
  1635. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1636. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1637. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1638. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1639. // The second one is negative when read as a signed value
  1640. const auto max_id = (std::numeric_limits<size_t>::max)();
  1641. for (auto id : {max_id / 2, max_id}) {
  1642. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1643. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1644. EXPECT_EQ("", req.get_param_value("test", id));
  1645. EXPECT_EQ("", req.form.get_field("test", id));
  1646. EXPECT_EQ("", req.form.get_file("test", id).content);
  1647. }
  1648. }
  1649. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1650. Headers headers;
  1651. headers.emplace("Host", "example.com");
  1652. headers.emplace("Accept-Encoding", "gzip");
  1653. headers.emplace("User-Agent", "test");
  1654. headers.emplace("Accept-Encoding", "deflate");
  1655. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1656. "Accept-Encoding=deflate ",
  1657. entries_to_string(headers));
  1658. }
  1659. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1660. Headers headers = {{"Content-Type", "text/html"},
  1661. {"CONTENT-TYPE", "text/xml"}};
  1662. EXPECT_EQ(2U, headers.count("content-type"));
  1663. auto it = headers.find("content-type");
  1664. ASSERT_TRUE(it != headers.end());
  1665. EXPECT_EQ("text/html", it->second);
  1666. }
  1667. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1668. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1669. // drop only those fields and leave everything positioned between them.
  1670. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1671. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1672. auto rng = headers.equal_range("a");
  1673. headers.erase(rng.first, rng.second);
  1674. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1675. }
  1676. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1677. Headers headers = {
  1678. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1679. EXPECT_EQ(3U, headers.erase("A"));
  1680. EXPECT_EQ(0U, headers.count("A"));
  1681. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1682. }
  1683. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1684. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1685. headers.emplace_front("Host", "example.com");
  1686. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1687. entries_to_string(headers));
  1688. }
  1689. TEST(ParseHeaderValueTest, Range) {
  1690. {
  1691. Ranges ranges;
  1692. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1693. EXPECT_TRUE(ret);
  1694. EXPECT_EQ(1u, ranges.size());
  1695. EXPECT_EQ(1u, ranges[0].first);
  1696. EXPECT_EQ(-1, ranges[0].second);
  1697. }
  1698. {
  1699. Ranges ranges;
  1700. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1701. EXPECT_TRUE(ret);
  1702. EXPECT_EQ(1u, ranges.size());
  1703. EXPECT_EQ(-1, ranges[0].first);
  1704. EXPECT_EQ(1u, ranges[0].second);
  1705. }
  1706. {
  1707. Ranges ranges;
  1708. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1709. EXPECT_TRUE(ret);
  1710. EXPECT_EQ(1u, ranges.size());
  1711. EXPECT_EQ(1u, ranges[0].first);
  1712. EXPECT_EQ(10u, ranges[0].second);
  1713. }
  1714. {
  1715. Ranges ranges;
  1716. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1717. EXPECT_FALSE(ret);
  1718. }
  1719. {
  1720. Ranges ranges;
  1721. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1722. EXPECT_TRUE(ret);
  1723. EXPECT_EQ(2u, ranges.size());
  1724. EXPECT_EQ(1u, ranges[0].first);
  1725. EXPECT_EQ(10u, ranges[0].second);
  1726. EXPECT_EQ(100u, ranges[1].first);
  1727. EXPECT_EQ(-1, ranges[1].second);
  1728. }
  1729. {
  1730. Ranges ranges;
  1731. auto ret =
  1732. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1733. EXPECT_TRUE(ret);
  1734. EXPECT_EQ(3u, ranges.size());
  1735. EXPECT_EQ(1u, ranges[0].first);
  1736. EXPECT_EQ(10u, ranges[0].second);
  1737. EXPECT_EQ(100u, ranges[1].first);
  1738. EXPECT_EQ(200u, ranges[1].second);
  1739. EXPECT_EQ(300u, ranges[2].first);
  1740. EXPECT_EQ(400u, ranges[2].second);
  1741. }
  1742. {
  1743. Ranges ranges;
  1744. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1745. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1746. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1747. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1748. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1749. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1750. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1751. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1752. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1753. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1754. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1755. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1756. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1757. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1758. EXPECT_FALSE(
  1759. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1760. EXPECT_TRUE(ranges.empty());
  1761. }
  1762. {
  1763. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1764. // remainder of the representation, so it stays accepted.
  1765. Ranges ranges;
  1766. auto ret =
  1767. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1768. EXPECT_TRUE(ret);
  1769. ASSERT_EQ(1u, ranges.size());
  1770. EXPECT_EQ(0, ranges[0].first);
  1771. EXPECT_EQ(-1, ranges[0].second);
  1772. }
  1773. // RFC 9110 14.1: range unit names are case-insensitive.
  1774. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1775. Ranges ranges;
  1776. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1777. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1778. }
  1779. }
  1780. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1781. Request req;
  1782. req.set_header("Accept-Encoding", "gzip");
  1783. Response res;
  1784. res.set_header("Content-Type", "text/plain");
  1785. auto ret = detail::encoding_type(req, res);
  1786. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1787. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1788. #else
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. #endif
  1791. }
  1792. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1793. Request req;
  1794. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1795. Response res;
  1796. res.set_header("Content-Type", "text/plain");
  1797. auto ret = detail::encoding_type(req, res);
  1798. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1799. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1800. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1801. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1802. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1803. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1804. #else
  1805. EXPECT_TRUE(ret == detail::EncodingType::None);
  1806. #endif
  1807. }
  1808. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1809. Request req;
  1810. req.set_header("Accept-Encoding",
  1811. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1812. Response res;
  1813. res.set_header("Content-Type", "text/plain");
  1814. auto ret = detail::encoding_type(req, res);
  1815. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1816. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1817. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1818. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1819. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1820. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1821. #else
  1822. EXPECT_TRUE(ret == detail::EncodingType::None);
  1823. #endif
  1824. }
  1825. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1826. // All supported encodings rejected with q=0 should return None
  1827. Request req;
  1828. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1829. Response res;
  1830. res.set_header("Content-Type", "text/plain");
  1831. auto ret = detail::encoding_type(req, res);
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. }
  1834. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1835. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1836. Request req;
  1837. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1838. Response res;
  1839. res.set_header("Content-Type", "text/plain");
  1840. auto ret = detail::encoding_type(req, res);
  1841. EXPECT_TRUE(ret == detail::EncodingType::None);
  1842. }
  1843. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1844. Request req;
  1845. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1846. Response res;
  1847. res.set_header("Content-Type", "text/plain");
  1848. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1849. }
  1850. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1851. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1852. Request req;
  1853. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1854. Response res;
  1855. res.set_header("Content-Type", "text/plain");
  1856. auto ret = detail::encoding_type(req, res);
  1857. EXPECT_TRUE(ret == detail::EncodingType::None);
  1858. }
  1859. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1860. // RFC 7231: Accept-Encoding values are case-insensitive
  1861. Request req;
  1862. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1863. Response res;
  1864. res.set_header("Content-Type", "text/plain");
  1865. auto ret = detail::encoding_type(req, res);
  1866. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1867. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1868. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1869. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1870. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1871. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1872. #else
  1873. EXPECT_TRUE(ret == detail::EncodingType::None);
  1874. #endif
  1875. }
  1876. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1877. // q value should determine priority, not hardcoded order
  1878. Request req;
  1879. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1880. Response res;
  1881. res.set_header("Content-Type", "text/plain");
  1882. auto ret = detail::encoding_type(req, res);
  1883. // gzip has highest q=1.0, so it should be selected even though
  1884. // br and zstd are also supported
  1885. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1886. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1887. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1888. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1889. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1890. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1891. #else
  1892. EXPECT_TRUE(ret == detail::EncodingType::None);
  1893. #endif
  1894. }
  1895. TEST(BufferStreamTest, read) {
  1896. detail::BufferStream strm1;
  1897. Stream &strm = strm1;
  1898. EXPECT_EQ(5, strm.write("hello"));
  1899. char buf[512];
  1900. EXPECT_EQ(2, strm.read(buf, 2));
  1901. EXPECT_EQ('h', buf[0]);
  1902. EXPECT_EQ('e', buf[1]);
  1903. EXPECT_EQ(2, strm.read(buf, 2));
  1904. EXPECT_EQ('l', buf[0]);
  1905. EXPECT_EQ('l', buf[1]);
  1906. EXPECT_EQ(1, strm.read(buf, 1));
  1907. EXPECT_EQ('o', buf[0]);
  1908. EXPECT_EQ(0, strm.read(buf, 1));
  1909. }
  1910. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1911. auto host = "www.httpwatch.com";
  1912. auto ip = hosted_at(host);
  1913. EXPECT_EQ("23.96.13.243", ip);
  1914. std::vector<std::string> addrs;
  1915. hosted_at(host, addrs);
  1916. EXPECT_EQ(1u, addrs.size());
  1917. }
  1918. #if 0 // It depends on each test environment...
  1919. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1920. auto host = "www.youtube.com";
  1921. std::vector<std::string> addrs;
  1922. hosted_at(host, addrs);
  1923. EXPECT_EQ(20u, addrs.size());
  1924. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1925. EXPECT_TRUE(it != addrs.end());
  1926. }
  1927. #endif
  1928. class ChunkedEncodingTest : public ::testing::Test {
  1929. protected:
  1930. ChunkedEncodingTest()
  1931. : cli_(HOST, PORT)
  1932. #ifdef CPPHTTPLIB_SSL_ENABLED
  1933. ,
  1934. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1935. #endif
  1936. {
  1937. cli_.set_connection_timeout(2);
  1938. #ifdef CPPHTTPLIB_SSL_ENABLED
  1939. cli_.enable_server_certificate_verification(false);
  1940. #endif
  1941. }
  1942. virtual void SetUp() {
  1943. read_file("./image.jpg", image_data_);
  1944. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1945. res.set_content("Hello World!", "text/plain");
  1946. });
  1947. svr_.Get(
  1948. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1949. res.set_chunked_content_provider(
  1950. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1951. size_t remaining = image_data_.size() - offset;
  1952. if (remaining == 0) {
  1953. sink.done();
  1954. } else {
  1955. constexpr size_t CHUNK_SIZE = 1024;
  1956. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1957. sink.write(&image_data_[offset], send_size);
  1958. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1959. }
  1960. return true;
  1961. });
  1962. });
  1963. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1964. svr_.wait_until_ready();
  1965. }
  1966. virtual void TearDown() {
  1967. svr_.stop();
  1968. if (!request_threads_.empty()) {
  1969. std::this_thread::sleep_for(std::chrono::seconds(1));
  1970. for (auto &t : request_threads_) {
  1971. t.join();
  1972. }
  1973. }
  1974. t_.join();
  1975. }
  1976. #ifdef CPPHTTPLIB_SSL_ENABLED
  1977. SSLClient cli_;
  1978. SSLServer svr_;
  1979. #else
  1980. Client cli_;
  1981. Server svr_;
  1982. #endif
  1983. thread t_;
  1984. std::vector<thread> request_threads_;
  1985. std::string image_data_;
  1986. };
  1987. TEST_F(ChunkedEncodingTest, NormalGet) {
  1988. auto res = cli_.Get("/chunked");
  1989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1990. std::string out;
  1991. read_file("./image.jpg", out);
  1992. EXPECT_EQ(StatusCode::OK_200, res->status);
  1993. EXPECT_EQ(out, res->body);
  1994. }
  1995. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1996. std::string body;
  1997. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1998. body.append(data, data_length);
  1999. return true;
  2000. });
  2001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2002. std::string out;
  2003. read_file("./image.jpg", out);
  2004. EXPECT_EQ(StatusCode::OK_200, res->status);
  2005. EXPECT_EQ(out, body);
  2006. }
  2007. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2008. std::string body;
  2009. auto res = cli_.Get(
  2010. "/chunked",
  2011. [&](const Response &response) {
  2012. EXPECT_EQ(StatusCode::OK_200, response.status);
  2013. return true;
  2014. },
  2015. [&](const char *data, size_t data_length) {
  2016. body.append(data, data_length);
  2017. return true;
  2018. });
  2019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2020. std::string out;
  2021. read_file("./image.jpg", out);
  2022. EXPECT_EQ(StatusCode::OK_200, res->status);
  2023. EXPECT_EQ(out, body);
  2024. }
  2025. TEST(RangeTest, FromHTTPBin_Online) {
  2026. auto host = "httpbingo.org";
  2027. auto path = std::string{"/range/32"};
  2028. #ifdef CPPHTTPLIB_SSL_ENABLED
  2029. auto port = 443;
  2030. SSLClient cli(host, port);
  2031. #else
  2032. auto port = 80;
  2033. Client cli(host, port);
  2034. #endif
  2035. cli.set_connection_timeout(5);
  2036. {
  2037. auto res = cli.Get(path);
  2038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2039. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2040. EXPECT_EQ(StatusCode::OK_200, res->status);
  2041. }
  2042. {
  2043. Headers headers = {make_range_header({{1, -1}})};
  2044. auto res = cli.Get(path, headers);
  2045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2046. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2048. }
  2049. {
  2050. Headers headers = {make_range_header({{1, 10}})};
  2051. auto res = cli.Get(path, headers);
  2052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2053. EXPECT_EQ("bcdefghijk", res->body);
  2054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2055. }
  2056. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2057. // entire resource, while the original httpbin returned 200. Both are
  2058. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2059. {
  2060. Headers headers = {make_range_header({{0, 31}})};
  2061. auto res = cli.Get(path, headers);
  2062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2063. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2064. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2065. res->status == StatusCode::PartialContent_206);
  2066. }
  2067. {
  2068. Headers headers = {make_range_header({{0, -1}})};
  2069. auto res = cli.Get(path, headers);
  2070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2071. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2072. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2073. res->status == StatusCode::PartialContent_206);
  2074. }
  2075. // go-httpbin returns 206 with clamped range for over-range requests,
  2076. // while the original httpbin returned 416. Both behaviors are observed
  2077. // in real servers, so we only verify the request succeeds.
  2078. {
  2079. Headers headers = {make_range_header({{0, 32}})};
  2080. auto res = cli.Get(path, headers);
  2081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2082. }
  2083. }
  2084. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2085. auto host = "unresolvableaddress.local";
  2086. auto path = std::string{"/"};
  2087. #ifdef CPPHTTPLIB_SSL_ENABLED
  2088. auto port = 443;
  2089. SSLClient cli(host, port);
  2090. #else
  2091. auto port = 80;
  2092. Client cli(host, port);
  2093. #endif
  2094. cli.set_connection_timeout(1);
  2095. {
  2096. auto res = cli.Get(path);
  2097. ASSERT_FALSE(res);
  2098. }
  2099. std::this_thread::sleep_for(std::chrono::seconds(8));
  2100. }
  2101. #if defined(__linux__) && defined(__GLIBC__) && \
  2102. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2103. // Forward declaration: in split builds split.py strips `inline` and moves the
  2104. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2105. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2106. // against the symbol in both header-only and split builds.
  2107. namespace httplib {
  2108. namespace detail {
  2109. int getaddrinfo_with_timeout(const char *node, const char *service,
  2110. const struct addrinfo *hints,
  2111. struct addrinfo **res, time_t timeout_sec);
  2112. } // namespace detail
  2113. } // namespace httplib
  2114. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2115. //
  2116. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2117. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2118. // gai_suspend() call hits the connection timeout the function calls
  2119. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2120. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2121. // still alive and still references the now-destroyed stack frame.
  2122. //
  2123. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2124. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2125. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2126. // and runs them in a container.
  2127. namespace {
  2128. bool should_run_issue_2431_tests() {
  2129. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2130. return v && *v && std::string(v) != "0";
  2131. }
  2132. std::string unique_unresolvable_host(int n) {
  2133. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2134. // glibc still asks the configured nameserver — which is exactly the path
  2135. // we want to exercise. A unique label per call avoids the resolver cache.
  2136. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2137. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2138. std::to_string(n) + ".invalid";
  2139. }
  2140. } // namespace
  2141. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2142. if (!should_run_issue_2431_tests()) {
  2143. GTEST_SKIP()
  2144. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2145. }
  2146. for (int i = 0; i < 8; ++i) {
  2147. struct addrinfo hints;
  2148. memset(&hints, 0, sizeof(hints));
  2149. hints.ai_family = AF_UNSPEC;
  2150. hints.ai_socktype = SOCK_STREAM;
  2151. auto host = unique_unresolvable_host(i);
  2152. struct addrinfo *result = nullptr;
  2153. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2154. &result, /*timeout_sec=*/1);
  2155. if (rc == 0 && result) { freeaddrinfo(result); }
  2156. }
  2157. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2158. // stack region they still believe holds their gaicb.
  2159. std::this_thread::sleep_for(std::chrono::seconds(3));
  2160. }
  2161. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2162. if (!should_run_issue_2431_tests()) {
  2163. GTEST_SKIP()
  2164. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2165. }
  2166. std::atomic<bool> stop{false};
  2167. std::vector<std::thread> threads;
  2168. for (int t = 0; t < 8; ++t) {
  2169. threads.emplace_back([t, &stop] {
  2170. int i = 0;
  2171. while (!stop.load(std::memory_order_relaxed)) {
  2172. struct addrinfo hints;
  2173. memset(&hints, 0, sizeof(hints));
  2174. hints.ai_family = AF_UNSPEC;
  2175. hints.ai_socktype = SOCK_STREAM;
  2176. auto host = unique_unresolvable_host(t * 100000 + i++);
  2177. struct addrinfo *result = nullptr;
  2178. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2179. &result, /*timeout_sec=*/1);
  2180. if (rc == 0 && result) { freeaddrinfo(result); }
  2181. }
  2182. });
  2183. }
  2184. std::this_thread::sleep_for(std::chrono::seconds(8));
  2185. stop.store(true, std::memory_order_relaxed);
  2186. for (auto &th : threads) {
  2187. th.join();
  2188. }
  2189. std::this_thread::sleep_for(std::chrono::seconds(3));
  2190. }
  2191. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2192. if (!should_run_issue_2431_tests()) {
  2193. GTEST_SKIP()
  2194. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2195. }
  2196. std::atomic<bool> stop{false};
  2197. std::vector<std::thread> threads;
  2198. for (int t = 0; t < 8; ++t) {
  2199. threads.emplace_back([t, &stop] {
  2200. int i = 0;
  2201. while (!stop.load(std::memory_order_relaxed)) {
  2202. auto host = unique_unresolvable_host(t * 100000 + i++);
  2203. Client cli(host, 80);
  2204. cli.set_connection_timeout(1, 0);
  2205. cli.set_read_timeout(1, 0);
  2206. cli.set_write_timeout(1, 0);
  2207. (void)cli.Get("/");
  2208. }
  2209. });
  2210. }
  2211. std::this_thread::sleep_for(std::chrono::seconds(8));
  2212. stop.store(true, std::memory_order_relaxed);
  2213. for (auto &th : threads) {
  2214. th.join();
  2215. }
  2216. std::this_thread::sleep_for(std::chrono::seconds(3));
  2217. }
  2218. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2219. TEST(ConnectionErrorTest, InvalidHost) {
  2220. auto host = "-abcde.com";
  2221. #ifdef CPPHTTPLIB_SSL_ENABLED
  2222. auto port = 443;
  2223. SSLClient cli(host, port);
  2224. #else
  2225. auto port = 80;
  2226. Client cli(host, port);
  2227. #endif
  2228. cli.set_connection_timeout(std::chrono::seconds(2));
  2229. auto res = cli.Get("/");
  2230. ASSERT_TRUE(!res);
  2231. EXPECT_EQ(Error::Connection, res.error());
  2232. }
  2233. TEST(ConnectionErrorTest, InvalidHost2) {
  2234. auto host = "httpcan.org/";
  2235. #ifdef CPPHTTPLIB_SSL_ENABLED
  2236. SSLClient cli(host);
  2237. #else
  2238. Client cli(host);
  2239. #endif
  2240. cli.set_connection_timeout(std::chrono::seconds(2));
  2241. auto res = cli.Get("/");
  2242. ASSERT_TRUE(!res);
  2243. EXPECT_EQ(Error::Connection, res.error());
  2244. }
  2245. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2246. auto host = "httpcan.org/";
  2247. #ifdef CPPHTTPLIB_SSL_ENABLED
  2248. SSLClient cli(host);
  2249. #else
  2250. Client cli(host);
  2251. #endif
  2252. cli.set_connection_timeout(std::chrono::seconds(2));
  2253. auto res = cli.Get("/");
  2254. ASSERT_TRUE(!res);
  2255. stringstream s;
  2256. s << "error code: " << res.error();
  2257. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2258. }
  2259. TEST(ConnectionErrorTest, InvalidPort) {
  2260. auto host = "localhost";
  2261. auto port = 44380;
  2262. #ifdef CPPHTTPLIB_SSL_ENABLED
  2263. SSLClient cli(host, port);
  2264. #else
  2265. Client cli(host, port);
  2266. #endif
  2267. cli.set_connection_timeout(std::chrono::seconds(2));
  2268. auto res = cli.Get("/");
  2269. ASSERT_TRUE(!res);
  2270. EXPECT_TRUE(Error::Connection == res.error() ||
  2271. Error::ConnectionTimeout == res.error());
  2272. }
  2273. TEST(ConnectionErrorTest, Timeout_Online) {
  2274. auto host = "google.com";
  2275. #ifdef CPPHTTPLIB_SSL_ENABLED
  2276. auto port = 44380;
  2277. SSLClient cli(host, port);
  2278. #else
  2279. auto port = 8080;
  2280. Client cli(host, port);
  2281. #endif
  2282. cli.set_connection_timeout(std::chrono::seconds(2));
  2283. // only probe one address type so that the error reason
  2284. // correlates to the timed-out IPv4, not the unsupported
  2285. // IPv6 connection attempt
  2286. cli.set_address_family(AF_INET);
  2287. auto res = cli.Get("/");
  2288. ASSERT_TRUE(!res);
  2289. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2290. }
  2291. TEST(CancelTest, NoCancel_Online) {
  2292. auto host = "httpbingo.org";
  2293. auto path = std::string{"/range/32"};
  2294. #ifdef CPPHTTPLIB_SSL_ENABLED
  2295. auto port = 443;
  2296. SSLClient cli(host, port);
  2297. #else
  2298. auto port = 80;
  2299. Client cli(host, port);
  2300. #endif
  2301. cli.set_connection_timeout(std::chrono::seconds(5));
  2302. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2304. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2305. EXPECT_EQ(StatusCode::OK_200, res->status);
  2306. }
  2307. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2308. // Use /bytes with a large payload so that the DownloadProgress callback
  2309. // (which only fires for Content-Length responses) is invoked before the
  2310. // entire body is received, giving cancellation a chance to fire.
  2311. auto host = "httpbingo.org";
  2312. auto path = std::string{"/bytes/524288"};
  2313. #ifdef CPPHTTPLIB_SSL_ENABLED
  2314. auto port = 443;
  2315. SSLClient cli(host, port);
  2316. #else
  2317. auto port = 80;
  2318. Client cli(host, port);
  2319. #endif
  2320. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2321. cli.set_connection_timeout(std::chrono::seconds(5));
  2322. ASSERT_TRUE(!res);
  2323. EXPECT_EQ(Error::Canceled, res.error());
  2324. }
  2325. TEST(CancelTest, WithCancelLargePayload_Online) {
  2326. auto host = "httpbingo.org";
  2327. auto path = std::string{"/bytes/524288"};
  2328. #ifdef CPPHTTPLIB_SSL_ENABLED
  2329. auto port = 443;
  2330. SSLClient cli(host, port);
  2331. #else
  2332. auto port = 80;
  2333. Client cli(host, port);
  2334. #endif
  2335. cli.set_connection_timeout(std::chrono::seconds(5));
  2336. uint32_t count = 0;
  2337. auto res =
  2338. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2339. ASSERT_TRUE(!res);
  2340. EXPECT_EQ(Error::Canceled, res.error());
  2341. }
  2342. TEST(CancelTest, NoCancelPost) {
  2343. Server svr;
  2344. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2345. res.set_content("Hello World!", "text/plain");
  2346. });
  2347. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2348. auto se = detail::scope_exit([&] {
  2349. svr.stop();
  2350. thread.join();
  2351. ASSERT_FALSE(svr.is_running());
  2352. });
  2353. svr.wait_until_ready();
  2354. Client cli(HOST, PORT);
  2355. cli.set_connection_timeout(std::chrono::seconds(5));
  2356. auto res =
  2357. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2358. "application/json", [](uint64_t, uint64_t) { return true; });
  2359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2360. EXPECT_EQ("Hello World!", res->body);
  2361. EXPECT_EQ(StatusCode::OK_200, res->status);
  2362. }
  2363. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2364. Server svr;
  2365. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2366. res.set_content("Hello World!", "text/plain");
  2367. });
  2368. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2369. auto se = detail::scope_exit([&] {
  2370. svr.stop();
  2371. thread.join();
  2372. ASSERT_FALSE(svr.is_running());
  2373. });
  2374. svr.wait_until_ready();
  2375. Client cli(HOST, PORT);
  2376. cli.set_connection_timeout(std::chrono::seconds(5));
  2377. auto res =
  2378. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2379. "application/json", [](uint64_t, uint64_t) { return false; });
  2380. ASSERT_TRUE(!res);
  2381. EXPECT_EQ(Error::Canceled, res.error());
  2382. }
  2383. TEST(CancelTest, WithCancelLargePayloadPost) {
  2384. Server svr;
  2385. svr.set_payload_max_length(200 * 1024 * 1024);
  2386. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2387. res.set_content(LARGE_DATA, "text/plain");
  2388. });
  2389. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2390. auto se = detail::scope_exit([&] {
  2391. svr.stop();
  2392. thread.join();
  2393. ASSERT_FALSE(svr.is_running());
  2394. });
  2395. svr.wait_until_ready();
  2396. Client cli(HOST, PORT);
  2397. cli.set_payload_max_length(200 * 1024 * 1024);
  2398. cli.set_connection_timeout(std::chrono::seconds(5));
  2399. auto res =
  2400. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2401. "application/json", [](uint64_t, uint64_t) { return false; });
  2402. ASSERT_TRUE(!res);
  2403. EXPECT_EQ(Error::Canceled, res.error());
  2404. }
  2405. TEST(CancelTest, NoCancelPut) {
  2406. Server svr;
  2407. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2408. res.set_content("Hello World!", "text/plain");
  2409. });
  2410. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2411. auto se = detail::scope_exit([&] {
  2412. svr.stop();
  2413. thread.join();
  2414. ASSERT_FALSE(svr.is_running());
  2415. });
  2416. svr.wait_until_ready();
  2417. Client cli(HOST, PORT);
  2418. cli.set_connection_timeout(std::chrono::seconds(5));
  2419. auto res =
  2420. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2421. "application/json", [](uint64_t, uint64_t) { return true; });
  2422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2423. EXPECT_EQ("Hello World!", res->body);
  2424. EXPECT_EQ(StatusCode::OK_200, res->status);
  2425. }
  2426. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2427. Server svr;
  2428. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2429. res.set_content("Hello World!", "text/plain");
  2430. });
  2431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2432. auto se = detail::scope_exit([&] {
  2433. svr.stop();
  2434. thread.join();
  2435. ASSERT_FALSE(svr.is_running());
  2436. });
  2437. svr.wait_until_ready();
  2438. Client cli(HOST, PORT);
  2439. cli.set_connection_timeout(std::chrono::seconds(5));
  2440. auto res =
  2441. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2442. "application/json", [](uint64_t, uint64_t) { return false; });
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_EQ(Error::Canceled, res.error());
  2445. }
  2446. TEST(CancelTest, WithCancelLargePayloadPut) {
  2447. Server svr;
  2448. svr.set_payload_max_length(200 * 1024 * 1024);
  2449. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2450. res.set_content(LARGE_DATA, "text/plain");
  2451. });
  2452. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2453. auto se = detail::scope_exit([&] {
  2454. svr.stop();
  2455. thread.join();
  2456. ASSERT_FALSE(svr.is_running());
  2457. });
  2458. svr.wait_until_ready();
  2459. Client cli(HOST, PORT);
  2460. cli.set_payload_max_length(200 * 1024 * 1024);
  2461. cli.set_connection_timeout(std::chrono::seconds(5));
  2462. auto res =
  2463. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2464. "application/json", [](uint64_t, uint64_t) { return false; });
  2465. ASSERT_TRUE(!res);
  2466. EXPECT_EQ(Error::Canceled, res.error());
  2467. }
  2468. TEST(CancelTest, NoCancelPatch) {
  2469. Server svr;
  2470. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2471. res.set_content("Hello World!", "text/plain");
  2472. });
  2473. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2474. auto se = detail::scope_exit([&] {
  2475. svr.stop();
  2476. thread.join();
  2477. ASSERT_FALSE(svr.is_running());
  2478. });
  2479. svr.wait_until_ready();
  2480. Client cli(HOST, PORT);
  2481. cli.set_connection_timeout(std::chrono::seconds(5));
  2482. auto res =
  2483. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2484. "application/json", [](uint64_t, uint64_t) { return true; });
  2485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2486. EXPECT_EQ("Hello World!", res->body);
  2487. EXPECT_EQ(StatusCode::OK_200, res->status);
  2488. }
  2489. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2490. Server svr;
  2491. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2492. res.set_content("Hello World!", "text/plain");
  2493. });
  2494. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2495. auto se = detail::scope_exit([&] {
  2496. svr.stop();
  2497. thread.join();
  2498. ASSERT_FALSE(svr.is_running());
  2499. });
  2500. svr.wait_until_ready();
  2501. Client cli(HOST, PORT);
  2502. cli.set_connection_timeout(std::chrono::seconds(5));
  2503. auto res =
  2504. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2505. "application/json", [](uint64_t, uint64_t) { return false; });
  2506. ASSERT_TRUE(!res);
  2507. EXPECT_EQ(Error::Canceled, res.error());
  2508. }
  2509. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2510. Server svr;
  2511. svr.set_payload_max_length(200 * 1024 * 1024);
  2512. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2513. res.set_content(LARGE_DATA, "text/plain");
  2514. });
  2515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2516. auto se = detail::scope_exit([&] {
  2517. svr.stop();
  2518. thread.join();
  2519. ASSERT_FALSE(svr.is_running());
  2520. });
  2521. svr.wait_until_ready();
  2522. Client cli(HOST, PORT);
  2523. cli.set_payload_max_length(200 * 1024 * 1024);
  2524. cli.set_connection_timeout(std::chrono::seconds(5));
  2525. auto res =
  2526. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2527. "application/json", [](uint64_t, uint64_t) { return false; });
  2528. ASSERT_TRUE(!res);
  2529. EXPECT_EQ(Error::Canceled, res.error());
  2530. }
  2531. TEST(CancelTest, NoCancelDelete) {
  2532. Server svr;
  2533. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2534. res.set_content("Hello World!", "text/plain");
  2535. });
  2536. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2537. auto se = detail::scope_exit([&] {
  2538. svr.stop();
  2539. thread.join();
  2540. ASSERT_FALSE(svr.is_running());
  2541. });
  2542. svr.wait_until_ready();
  2543. Client cli(HOST, PORT);
  2544. cli.set_connection_timeout(std::chrono::seconds(5));
  2545. auto res =
  2546. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2547. "application/json", [](uint64_t, uint64_t) { return true; });
  2548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2549. EXPECT_EQ("Hello World!", res->body);
  2550. EXPECT_EQ(StatusCode::OK_200, res->status);
  2551. }
  2552. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2553. Server svr;
  2554. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2555. res.set_content("Hello World!", "text/plain");
  2556. });
  2557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2558. auto se = detail::scope_exit([&] {
  2559. svr.stop();
  2560. thread.join();
  2561. ASSERT_FALSE(svr.is_running());
  2562. });
  2563. svr.wait_until_ready();
  2564. Client cli(HOST, PORT);
  2565. cli.set_connection_timeout(std::chrono::seconds(5));
  2566. auto res =
  2567. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2568. "application/json", [](uint64_t, uint64_t) { return false; });
  2569. ASSERT_TRUE(!res);
  2570. EXPECT_EQ(Error::Canceled, res.error());
  2571. }
  2572. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2573. Server svr;
  2574. svr.set_payload_max_length(200 * 1024 * 1024);
  2575. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2576. res.set_content(LARGE_DATA, "text/plain");
  2577. });
  2578. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2579. auto se = detail::scope_exit([&] {
  2580. svr.stop();
  2581. thread.join();
  2582. ASSERT_FALSE(svr.is_running());
  2583. });
  2584. svr.wait_until_ready();
  2585. Client cli(HOST, PORT);
  2586. cli.set_payload_max_length(200 * 1024 * 1024);
  2587. cli.set_connection_timeout(std::chrono::seconds(5));
  2588. auto res =
  2589. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2590. "application/json", [](uint64_t, uint64_t) { return false; });
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::Canceled, res.error());
  2593. }
  2594. static std::string remove_whitespace(const std::string &input) {
  2595. std::string output;
  2596. output.reserve(input.size());
  2597. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2598. [](unsigned char c) { return !std::isspace(c); });
  2599. return output;
  2600. }
  2601. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2602. auto host = "httpbingo.org";
  2603. auto path = std::string{"/basic-auth/hello/world"};
  2604. #ifdef CPPHTTPLIB_SSL_ENABLED
  2605. auto port = 443;
  2606. SSLClient cli(host, port);
  2607. #else
  2608. auto port = 80;
  2609. Client cli(host, port);
  2610. #endif
  2611. {
  2612. auto res = cli.Get(path);
  2613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2614. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2615. }
  2616. {
  2617. auto res = cli.Get(
  2618. path, Headers{make_basic_authentication_header("hello", "world")});
  2619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2620. auto body = remove_whitespace(res->body);
  2621. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2622. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2623. EXPECT_EQ(StatusCode::OK_200, res->status);
  2624. }
  2625. {
  2626. cli.set_basic_auth("hello", "world");
  2627. auto res = cli.Get(path);
  2628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2629. auto body = remove_whitespace(res->body);
  2630. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2631. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2632. EXPECT_EQ(StatusCode::OK_200, res->status);
  2633. }
  2634. {
  2635. cli.set_basic_auth("hello", "bad");
  2636. auto res = cli.Get(path);
  2637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2638. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2639. }
  2640. {
  2641. cli.set_basic_auth("bad", "world");
  2642. auto res = cli.Get(path);
  2643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2644. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2645. }
  2646. }
  2647. #ifdef CPPHTTPLIB_SSL_ENABLED
  2648. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2649. auto host = "httpbingo.org";
  2650. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2651. auto paths = std::vector<std::string>{
  2652. "/digest-auth/auth/hello/world/MD5",
  2653. "/digest-auth/auth/hello/world/SHA-256",
  2654. };
  2655. auto port = 443;
  2656. SSLClient cli(host, port);
  2657. {
  2658. auto res = cli.Get(unauth_path);
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2661. }
  2662. {
  2663. cli.set_digest_auth("hello", "world");
  2664. for (const auto &path : paths) {
  2665. auto res = cli.Get(path.c_str());
  2666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2667. auto body = remove_whitespace(res->body);
  2668. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2669. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2670. EXPECT_EQ(StatusCode::OK_200, res->status);
  2671. }
  2672. cli.set_digest_auth("hello", "bad");
  2673. for (const auto &path : paths) {
  2674. auto res = cli.Get(path.c_str());
  2675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2676. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2677. }
  2678. }
  2679. }
  2680. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2681. // comma-separated list of challenges, and each challenge may itself carry a
  2682. // comma-separated auth-param list, so a server can legally offer Basic
  2683. // before Digest, either as two field lines or packed into one. Runs one 401
  2684. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2685. // value() joins them in receipt order) and checks that the retry carries a
  2686. // well-formed Digest Authorization header naming expected_realm.
  2687. static void
  2688. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2689. const std::string &expected_realm) {
  2690. std::atomic<int> hits{0};
  2691. Server svr;
  2692. svr.Get("/x", [&](const Request &req, Response &res) {
  2693. if (++hits == 1) {
  2694. res.status = StatusCode::Unauthorized_401;
  2695. for (const auto &challenge : challenges) {
  2696. res.set_header("WWW-Authenticate", challenge);
  2697. }
  2698. } else {
  2699. auto authorization = req.get_header_value("Authorization");
  2700. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2701. EXPECT_NE(std::string::npos,
  2702. authorization.find("realm=\"" + expected_realm + "\""));
  2703. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2704. res.set_content("ok", "text/plain");
  2705. }
  2706. });
  2707. auto port = svr.bind_to_any_port(HOST);
  2708. std::thread t([&]() { svr.listen_after_bind(); });
  2709. auto se = detail::scope_exit([&] {
  2710. svr.stop();
  2711. t.join();
  2712. });
  2713. svr.wait_until_ready();
  2714. Client cli(HOST, port);
  2715. cli.set_digest_auth("hello", "world");
  2716. auto res = cli.Get("/x");
  2717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2718. EXPECT_EQ(2, hits.load());
  2719. }
  2720. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2721. static const char *kDigestChallenge =
  2722. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2723. "algorithm=MD5";
  2724. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2725. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2726. "testrealm");
  2727. }
  2728. // Same challenge list with the schemes in the opposite order, to make sure
  2729. // the fix above didn't just special-case "Basic first".
  2730. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2731. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2732. "testrealm");
  2733. }
  2734. // A comma inside a quoted auth-param value must not be mistaken for the
  2735. // separator between two challenges (or two auth-params).
  2736. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2737. run_digest_challenge_list_test(
  2738. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2739. "algorithm=MD5"},
  2740. "test,realm");
  2741. }
  2742. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2743. // make_digest_authentication_header() dereferences both unconditionally, so
  2744. // a server sending a challenge missing either one must not be treated as
  2745. // usable -- doing so used to crash the client with std::out_of_range.
  2746. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2747. Server svr;
  2748. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2749. res.status = StatusCode::Unauthorized_401;
  2750. res.set_header("WWW-Authenticate", challenge);
  2751. });
  2752. auto port = svr.bind_to_any_port(HOST);
  2753. std::thread t([&]() { svr.listen_after_bind(); });
  2754. auto se = detail::scope_exit([&] {
  2755. svr.stop();
  2756. t.join();
  2757. });
  2758. svr.wait_until_ready();
  2759. Client cli(HOST, port);
  2760. cli.set_digest_auth("hello", "world");
  2761. auto res = cli.Get("/x");
  2762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2763. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2764. }
  2765. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2766. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2767. }
  2768. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2769. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2770. }
  2771. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2772. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2773. }
  2774. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2775. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2776. // when storing the values, so the header builder has to re-escape them (and
  2777. // keep algorithm a bare token); otherwise the value breaks out of its
  2778. // quoted-string and injects extra auth-params into the client's Authorization.
  2779. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2780. std::atomic<int> hits{0};
  2781. std::string authorization;
  2782. Server svr;
  2783. svr.Get("/x", [&](const Request &req, Response &res) {
  2784. if (++hits == 1) {
  2785. res.status = StatusCode::Unauthorized_401;
  2786. // On the wire the quotes embedded in the values are backslash-escaped.
  2787. res.set_header("WWW-Authenticate",
  2788. "Digest realm=\"testrealm\", "
  2789. "nonce=\"n\\\"; injected=\\\"x\", "
  2790. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2791. } else {
  2792. authorization = req.get_header_value("Authorization");
  2793. res.set_content("ok", "text/plain");
  2794. }
  2795. });
  2796. auto port = svr.bind_to_any_port(HOST);
  2797. std::thread t([&]() { svr.listen_after_bind(); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. t.join();
  2801. });
  2802. svr.wait_until_ready();
  2803. Client cli(HOST, port);
  2804. cli.set_digest_auth("hello", "world");
  2805. auto res = cli.Get("/x");
  2806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2807. EXPECT_EQ(2, hits.load());
  2808. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2809. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2810. // inside its quoted-string rather than starting an "injected" auth-param.
  2811. EXPECT_NE(std::string::npos,
  2812. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2813. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2814. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2815. }
  2816. #endif
  2817. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2818. auto host = "google.com";
  2819. auto another_host = "example.com";
  2820. auto wrong_ip = "0.0.0.0";
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. SSLClient cli(host);
  2823. #else
  2824. Client cli(host);
  2825. #endif
  2826. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2827. auto res = cli.Get("/");
  2828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2829. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2830. }
  2831. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2832. auto host = "google.com";
  2833. auto wrong_ip = "0.0.0.0";
  2834. #ifdef CPPHTTPLIB_SSL_ENABLED
  2835. SSLClient cli(host);
  2836. #else
  2837. Client cli(host);
  2838. #endif
  2839. cli.set_hostname_addr_map({{host, wrong_ip}});
  2840. auto res = cli.Get("/");
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::Connection, res.error());
  2843. }
  2844. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2845. // A mapped value that is not an IP literal must be resolved. "localhost"
  2846. // resolves from the hosts file, so this test needs no external DNS.
  2847. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2848. auto host = "target.invalid";
  2849. Server svr;
  2850. std::string received_host;
  2851. svr.Get("/hi", [&](const Request &req, Response &res) {
  2852. received_host = req.get_header_value("Host");
  2853. res.set_content("Hello World!", "text/plain");
  2854. });
  2855. auto port = svr.bind_to_any_port(HOST);
  2856. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2857. auto se = detail::scope_exit([&] {
  2858. svr.stop();
  2859. thread.join();
  2860. ASSERT_FALSE(svr.is_running());
  2861. });
  2862. svr.wait_until_ready();
  2863. Client cli(host, port);
  2864. cli.set_hostname_addr_map({{host, HOST}});
  2865. auto res = cli.Get("/hi");
  2866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2867. EXPECT_EQ(StatusCode::OK_200, res->status);
  2868. // The mapping only redirects the connection; the identity stays host_.
  2869. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2870. }
  2871. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2872. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2873. auto host = "target.invalid";
  2874. Server svr;
  2875. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2876. res.set_content("Hello World!", "text/plain");
  2877. });
  2878. auto port = svr.bind_to_any_port("127.0.0.1");
  2879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2880. auto se = detail::scope_exit([&] {
  2881. svr.stop();
  2882. thread.join();
  2883. ASSERT_FALSE(svr.is_running());
  2884. });
  2885. svr.wait_until_ready();
  2886. Client cli(host, port);
  2887. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2888. auto res = cli.Get("/hi");
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::OK_200, res->status);
  2891. }
  2892. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2893. // An empty mapped value must leave host_ as the connection target. Without
  2894. // that guard the empty value would become the host argument, getaddrinfo
  2895. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2896. // loopback - silently connecting somewhere the caller never asked for.
  2897. // The server listens on loopback, so such a fallback would succeed and is
  2898. // therefore observable as a failure of this test.
  2899. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2900. Server svr;
  2901. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2902. res.set_content("Hello World!", "text/plain");
  2903. });
  2904. auto port = svr.bind_to_any_port(HOST);
  2905. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. Client cli(blackhole, port);
  2913. cli.set_hostname_addr_map({{blackhole, ""}});
  2914. cli.set_connection_timeout(1);
  2915. auto res = cli.Get("/hi");
  2916. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2917. }
  2918. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2919. auto host = "httpbingo.org";
  2920. auto path = std::string{"/absolute-redirect/3"};
  2921. #ifdef CPPHTTPLIB_SSL_ENABLED
  2922. SSLClient cli(host);
  2923. #else
  2924. Client cli(host);
  2925. #endif
  2926. cli.set_follow_location(true);
  2927. auto res = cli.Get(path);
  2928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2929. EXPECT_EQ(StatusCode::OK_200, res->status);
  2930. }
  2931. TEST(RedirectTest, Redirect_Online) {
  2932. auto host = "httpbingo.org";
  2933. auto path = std::string{"/redirect/3"};
  2934. #ifdef CPPHTTPLIB_SSL_ENABLED
  2935. SSLClient cli(host);
  2936. #else
  2937. Client cli(host);
  2938. #endif
  2939. cli.set_follow_location(true);
  2940. auto res = cli.Get(path);
  2941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2942. EXPECT_EQ(StatusCode::OK_200, res->status);
  2943. }
  2944. TEST(RelativeRedirectTest, Redirect_Online) {
  2945. auto host = "httpbingo.org";
  2946. auto path = std::string{"/relative-redirect/3"};
  2947. #ifdef CPPHTTPLIB_SSL_ENABLED
  2948. SSLClient cli(host);
  2949. #else
  2950. Client cli(host);
  2951. #endif
  2952. cli.set_follow_location(true);
  2953. auto res = cli.Get(path);
  2954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2955. EXPECT_EQ(StatusCode::OK_200, res->status);
  2956. }
  2957. TEST(TooManyRedirectTest, Redirect_Online) {
  2958. auto host = "httpbingo.org";
  2959. auto path = std::string{"/redirect/21"};
  2960. #ifdef CPPHTTPLIB_SSL_ENABLED
  2961. SSLClient cli(host);
  2962. #else
  2963. Client cli(host);
  2964. #endif
  2965. cli.set_follow_location(true);
  2966. auto res = cli.Get(path);
  2967. ASSERT_TRUE(!res);
  2968. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2969. }
  2970. #ifdef CPPHTTPLIB_SSL_ENABLED
  2971. TEST(YahooRedirectTest, Redirect_Online) {
  2972. Client cli("yahoo.com");
  2973. auto res = cli.Get("/");
  2974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2975. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2976. cli.set_follow_location(true);
  2977. res = cli.Get("/");
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(StatusCode::OK_200, res->status);
  2980. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2981. }
  2982. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2983. #define REDIR_HOST "httpbingo.org"
  2984. #define REDIR_PATH "/redirect-to"
  2985. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2986. SSLClient cli(REDIR_HOST);
  2987. cli.set_follow_location(true);
  2988. auto res =
  2989. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2991. EXPECT_EQ(StatusCode::OK_200, res->status);
  2992. }
  2993. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2994. SSLClient cli(REDIR_HOST);
  2995. cli.set_follow_location(true);
  2996. Params params;
  2997. params.emplace("url", "http://example.com");
  2998. params.emplace("status_code", "302");
  2999. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3001. EXPECT_EQ(StatusCode::OK_200, res->status);
  3002. }
  3003. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3004. SSLClient cli(REDIR_HOST);
  3005. cli.set_follow_location(true);
  3006. Params params;
  3007. params.emplace("url", "http://example.com");
  3008. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. EXPECT_EQ(StatusCode::OK_200, res->status);
  3011. }
  3012. TEST(UrlWithSpace, Redirect_Online) {
  3013. SSLClient cli("edge.forgecdn.net");
  3014. cli.set_follow_location(true);
  3015. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3017. EXPECT_EQ(StatusCode::OK_200, res->status);
  3018. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3019. }
  3020. #endif
  3021. #if !defined(_WIN32) && !defined(_WIN64)
  3022. TEST(ReceiveSignals, Signal) {
  3023. auto setupSignalHandlers = []() {
  3024. struct sigaction act;
  3025. sigemptyset(&act.sa_mask);
  3026. act.sa_flags = SA_SIGINFO;
  3027. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3028. switch (sig) {
  3029. case SIGINT:
  3030. default: break;
  3031. }
  3032. };
  3033. ::sigaction(SIGINT, &act, nullptr);
  3034. };
  3035. Server svr;
  3036. int port = 0;
  3037. auto thread = std::thread([&]() {
  3038. setupSignalHandlers();
  3039. port = svr.bind_to_any_port(HOST);
  3040. svr.listen_after_bind();
  3041. });
  3042. auto se = detail::scope_exit([&] {
  3043. svr.stop();
  3044. thread.join();
  3045. ASSERT_FALSE(svr.is_running());
  3046. });
  3047. svr.wait_until_ready();
  3048. ASSERT_TRUE(svr.is_running());
  3049. pthread_kill(thread.native_handle(), SIGINT);
  3050. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3051. ASSERT_TRUE(svr.is_running());
  3052. }
  3053. #endif
  3054. TEST(RedirectToDifferentPort, Redirect) {
  3055. Server svr1;
  3056. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3057. res.set_content("Hello World!", "text/plain");
  3058. });
  3059. int svr1_port = 0;
  3060. auto thread1 = std::thread([&]() {
  3061. svr1_port = svr1.bind_to_any_port(HOST);
  3062. svr1.listen_after_bind();
  3063. });
  3064. Server svr2;
  3065. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3066. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3067. });
  3068. int svr2_port = 0;
  3069. auto thread2 = std::thread([&]() {
  3070. svr2_port = svr2.bind_to_any_port(HOST);
  3071. svr2.listen_after_bind();
  3072. });
  3073. auto se = detail::scope_exit([&] {
  3074. svr2.stop();
  3075. thread2.join();
  3076. svr1.stop();
  3077. thread1.join();
  3078. ASSERT_FALSE(svr2.is_running());
  3079. ASSERT_FALSE(svr1.is_running());
  3080. });
  3081. svr1.wait_until_ready();
  3082. svr2.wait_until_ready();
  3083. Client cli("localhost", svr2_port);
  3084. cli.set_follow_location(true);
  3085. auto res = cli.Get("/2");
  3086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3087. EXPECT_EQ(StatusCode::OK_200, res->status);
  3088. EXPECT_EQ("Hello World!", res->body);
  3089. }
  3090. static void
  3091. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3092. Server svr1;
  3093. std::string captured_authorization;
  3094. svr1.Get("/target", [&](const Request &req, Response &res) {
  3095. captured_authorization = req.get_header_value("Authorization");
  3096. res.set_content("OK", "text/plain");
  3097. });
  3098. int svr1_port = 0;
  3099. auto thread1 = std::thread([&]() {
  3100. svr1_port = svr1.bind_to_any_port(HOST);
  3101. svr1.listen_after_bind();
  3102. });
  3103. Server svr2;
  3104. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3105. res.set_redirect(
  3106. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3107. });
  3108. int svr2_port = 0;
  3109. auto thread2 = std::thread([&]() {
  3110. svr2_port = svr2.bind_to_any_port(HOST);
  3111. svr2.listen_after_bind();
  3112. });
  3113. auto se = detail::scope_exit([&] {
  3114. svr2.stop();
  3115. thread2.join();
  3116. svr1.stop();
  3117. thread1.join();
  3118. ASSERT_FALSE(svr2.is_running());
  3119. ASSERT_FALSE(svr1.is_running());
  3120. });
  3121. svr1.wait_until_ready();
  3122. svr2.wait_until_ready();
  3123. Client cli("localhost", svr2_port);
  3124. cli.set_follow_location(true);
  3125. set_auth(cli);
  3126. auto res = cli.Get("/redir");
  3127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3128. EXPECT_EQ(StatusCode::OK_200, res->status);
  3129. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3130. EXPECT_TRUE(captured_authorization.empty());
  3131. }
  3132. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3133. TestDoNotForwardCredentialsOnRedirect(
  3134. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3135. }
  3136. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3137. TestDoNotForwardCredentialsOnRedirect(
  3138. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3139. }
  3140. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3141. Server svr1;
  3142. std::string captured_cookie;
  3143. bool target_hit = false;
  3144. svr1.Get("/target", [&](const Request &req, Response &res) {
  3145. captured_cookie = req.get_header_value("Cookie");
  3146. target_hit = true;
  3147. res.set_content("OK", "text/plain");
  3148. });
  3149. int svr1_port = 0;
  3150. auto thread1 = std::thread([&]() {
  3151. svr1_port = svr1.bind_to_any_port(HOST);
  3152. svr1.listen_after_bind();
  3153. });
  3154. Server svr2;
  3155. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3156. res.set_redirect(
  3157. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3158. });
  3159. int svr2_port = 0;
  3160. auto thread2 = std::thread([&]() {
  3161. svr2_port = svr2.bind_to_any_port(HOST);
  3162. svr2.listen_after_bind();
  3163. });
  3164. auto se = detail::scope_exit([&] {
  3165. svr2.stop();
  3166. thread2.join();
  3167. svr1.stop();
  3168. thread1.join();
  3169. ASSERT_FALSE(svr2.is_running());
  3170. ASSERT_FALSE(svr1.is_running());
  3171. });
  3172. svr1.wait_until_ready();
  3173. svr2.wait_until_ready();
  3174. Client cli("localhost", svr2_port);
  3175. cli.set_follow_location(true);
  3176. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3177. auto res = cli.Get("/redir", headers);
  3178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3179. EXPECT_EQ(StatusCode::OK_200, res->status);
  3180. EXPECT_TRUE(target_hit);
  3181. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3182. EXPECT_TRUE(captured_cookie.empty());
  3183. }
  3184. TEST(RedirectToSamePort, ForwardCookie) {
  3185. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3186. // header so that ordinary session flows keep working.
  3187. Server svr;
  3188. std::string captured_cookie;
  3189. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3190. res.set_redirect("/target", 302);
  3191. });
  3192. svr.Get("/target", [&](const Request &req, Response &res) {
  3193. captured_cookie = req.get_header_value("Cookie");
  3194. res.set_content("OK", "text/plain");
  3195. });
  3196. auto port = svr.bind_to_any_port(HOST);
  3197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3198. auto se = detail::scope_exit([&] {
  3199. svr.stop();
  3200. thread.join();
  3201. ASSERT_FALSE(svr.is_running());
  3202. });
  3203. svr.wait_until_ready();
  3204. Client cli(HOST, port);
  3205. cli.set_follow_location(true);
  3206. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3207. auto res = cli.Get("/redir", headers);
  3208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3209. EXPECT_EQ(StatusCode::OK_200, res->status);
  3210. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3211. }
  3212. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3213. Server svr;
  3214. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3215. // Port number that overflows int — should not crash
  3216. res.set_redirect("http://localhost:99999999999999999999/target");
  3217. });
  3218. auto port = svr.bind_to_any_port(HOST);
  3219. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3220. auto se = detail::scope_exit([&] {
  3221. svr.stop();
  3222. thread.join();
  3223. ASSERT_FALSE(svr.is_running());
  3224. });
  3225. svr.wait_until_ready();
  3226. Client cli(HOST, port);
  3227. cli.set_follow_location(true);
  3228. auto res = cli.Get("/redir");
  3229. // Should fail gracefully, not crash (no valid response due to bad port)
  3230. EXPECT_FALSE(res);
  3231. }
  3232. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3233. Server svr;
  3234. auto port = svr.bind_to_any_port(HOST);
  3235. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3236. // The server's own port followed by junk must not be followed
  3237. res.set_redirect("http://" + std::string(HOST) + ":" +
  3238. std::to_string(port) + "junk/target");
  3239. });
  3240. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3241. res.set_content("target", "text/plain");
  3242. });
  3243. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3244. auto se = detail::scope_exit([&] {
  3245. svr.stop();
  3246. thread.join();
  3247. ASSERT_FALSE(svr.is_running());
  3248. });
  3249. svr.wait_until_ready();
  3250. Client cli(HOST, port);
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get("/redir");
  3253. EXPECT_FALSE(res);
  3254. }
  3255. TEST(RedirectFromPageWithContent, Redirect) {
  3256. Server svr;
  3257. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3258. res.set_content("___", "text/plain");
  3259. res.set_redirect("/2");
  3260. });
  3261. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3262. res.set_content("Hello World!", "text/plain");
  3263. });
  3264. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3265. auto se = detail::scope_exit([&] {
  3266. svr.stop();
  3267. th.join();
  3268. ASSERT_FALSE(svr.is_running());
  3269. });
  3270. svr.wait_until_ready();
  3271. {
  3272. Client cli("localhost", PORT);
  3273. cli.set_follow_location(true);
  3274. std::string body;
  3275. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3276. body.append(data, data_length);
  3277. return true;
  3278. });
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. EXPECT_EQ("Hello World!", body);
  3282. }
  3283. {
  3284. Client cli("localhost", PORT);
  3285. std::string body;
  3286. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3287. body.append(data, data_length);
  3288. return true;
  3289. });
  3290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3291. EXPECT_EQ(StatusCode::Found_302, res->status);
  3292. EXPECT_EQ("___", body);
  3293. }
  3294. }
  3295. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3296. Server svr;
  3297. auto port_str = std::to_string(PORT);
  3298. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3299. auto expected_host = "[::1]:" + port_str;
  3300. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3301. res.set_content("___", "text/plain");
  3302. // res.set_redirect("/2");
  3303. res.set_redirect(redirect_url);
  3304. });
  3305. svr.Get("/2", [&](const Request &req, Response &res) {
  3306. auto host_header = req.headers.find("Host");
  3307. ASSERT_TRUE(host_header != req.headers.end());
  3308. EXPECT_EQ(expected_host, host_header->second);
  3309. res.set_content("Hello World!", "text/plain");
  3310. });
  3311. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3312. auto se = detail::scope_exit([&] {
  3313. svr.stop();
  3314. th.join();
  3315. ASSERT_FALSE(svr.is_running());
  3316. });
  3317. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3318. // actually starts anything, so the condition !svr.is_running() will
  3319. // always remain true, and the loop never stops.
  3320. // This basically counts how many milliseconds have passed since the
  3321. // call to svr.listen(), and if after 5 seconds nothing started yet
  3322. // aborts the test.
  3323. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3324. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3325. ASSERT_LT(milliseconds, 5000U);
  3326. }
  3327. {
  3328. Client cli("::1", PORT);
  3329. cli.set_follow_location(true);
  3330. std::string body;
  3331. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3332. body.append(data, data_length);
  3333. return true;
  3334. });
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. EXPECT_EQ(StatusCode::OK_200, res->status);
  3337. EXPECT_EQ("Hello World!", body);
  3338. }
  3339. {
  3340. Client cli("::1", PORT);
  3341. std::string body;
  3342. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3343. body.append(data, data_length);
  3344. return true;
  3345. });
  3346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3347. EXPECT_EQ(StatusCode::Found_302, res->status);
  3348. EXPECT_EQ("___", body);
  3349. }
  3350. }
  3351. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3352. Server svr;
  3353. svr.Get("/foo", [](const Request &req, Response &res) {
  3354. auto a = req.params.find("a");
  3355. if (a != req.params.end()) {
  3356. res.set_content((*a).second, "text/plain");
  3357. res.status = StatusCode::OK_200;
  3358. } else {
  3359. res.status = StatusCode::BadRequest_400;
  3360. }
  3361. });
  3362. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3363. auto se = detail::scope_exit([&] {
  3364. svr.stop();
  3365. thread.join();
  3366. ASSERT_FALSE(svr.is_running());
  3367. });
  3368. svr.wait_until_ready();
  3369. {
  3370. Client cli(HOST, PORT);
  3371. cli.set_path_encode(false);
  3372. auto res = cli.Get("/foo?a=explicitly+encoded");
  3373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3374. EXPECT_EQ(StatusCode::OK_200, res->status);
  3375. // This expects it back with a space, as the `+` won't have been
  3376. // url-encoded, and server-side the params get decoded turning `+`
  3377. // into spaces.
  3378. EXPECT_EQ("explicitly encoded", res->body);
  3379. }
  3380. }
  3381. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3382. // When path encoding is disabled the client must transmit the supplied
  3383. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3384. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3385. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3386. // than a space (0x20). Assert on the raw wire target to catch this.
  3387. Server svr;
  3388. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3389. svr.Get("/foo", [&](const Request &req, Response &res) {
  3390. EXPECT_EQ(expected_target, req.target);
  3391. res.status = StatusCode::OK_200;
  3392. });
  3393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3394. auto se = detail::scope_exit([&] {
  3395. svr.stop();
  3396. thread.join();
  3397. ASSERT_FALSE(svr.is_running());
  3398. });
  3399. svr.wait_until_ready();
  3400. {
  3401. Client cli(HOST, PORT);
  3402. cli.set_path_encode(false);
  3403. auto res = cli.Get(expected_target.c_str());
  3404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3405. EXPECT_EQ(StatusCode::OK_200, res->status);
  3406. }
  3407. }
  3408. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3409. // `open_stream()` used to skip the path encoding that the buffered send
  3410. // path applies, so the same `path` produced different bytes in the request
  3411. // line depending on which API was used. Assert the two agree.
  3412. Server svr;
  3413. std::string target;
  3414. svr.Get(".*", [&](const Request &req, Response &res) {
  3415. target = req.target;
  3416. res.status = StatusCode::OK_200;
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. struct {
  3427. const char *path;
  3428. const char *expected;
  3429. } cases[] = {
  3430. {"/a b?x=1", "/a%20b?x=1"},
  3431. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3432. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3433. };
  3434. for (const auto &c : cases) {
  3435. Client cli(HOST, port);
  3436. target.clear();
  3437. auto res = cli.Get(c.path);
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3440. auto buffered_target = target;
  3441. target.clear();
  3442. auto handle = cli.open_stream("GET", c.path);
  3443. EXPECT_TRUE(handle.is_valid())
  3444. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3445. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3446. }
  3447. }
  3448. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3449. // The `set_path_encode(false)` contract — transmit the supplied target
  3450. // verbatim — must hold for the streaming API too.
  3451. Server svr;
  3452. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3453. std::string target;
  3454. svr.Get("/foo", [&](const Request &req, Response &res) {
  3455. target = req.target;
  3456. res.status = StatusCode::OK_200;
  3457. });
  3458. auto port = svr.bind_to_any_port(HOST);
  3459. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3460. auto se = detail::scope_exit([&] {
  3461. svr.stop();
  3462. thread.join();
  3463. ASSERT_FALSE(svr.is_running());
  3464. });
  3465. svr.wait_until_ready();
  3466. {
  3467. Client cli(HOST, port);
  3468. cli.set_path_encode(false);
  3469. auto handle = cli.open_stream("GET", expected_target);
  3470. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3471. EXPECT_EQ(expected_target, target);
  3472. }
  3473. }
  3474. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3475. // With path encoding enabled a CR/LF in the target is percent-encoded
  3476. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3477. // write_request_line still backstops `set_path_encode(false)`, which is
  3478. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3479. Server svr;
  3480. // Captured before routing: the decoded path contains a newline, which a
  3481. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3482. std::string target;
  3483. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3484. target = req.target;
  3485. res.status = StatusCode::OK_200;
  3486. return Server::HandlerResponse::Handled;
  3487. });
  3488. auto port = svr.bind_to_any_port(HOST);
  3489. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3490. auto se = detail::scope_exit([&] {
  3491. svr.stop();
  3492. thread.join();
  3493. ASSERT_FALSE(svr.is_running());
  3494. });
  3495. svr.wait_until_ready();
  3496. {
  3497. Client cli(HOST, port);
  3498. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3499. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3500. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3501. }
  3502. }
  3503. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3504. // Every control character is percent-encoded, not just CR/LF, so the target
  3505. // passes the request-target check in write_request_line.
  3506. Server svr;
  3507. std::string target;
  3508. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3509. target = req.target;
  3510. res.status = StatusCode::OK_200;
  3511. return Server::HandlerResponse::Handled;
  3512. });
  3513. auto port = svr.bind_to_any_port(HOST);
  3514. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3515. auto se = detail::scope_exit([&] {
  3516. svr.stop();
  3517. thread.join();
  3518. ASSERT_FALSE(svr.is_running());
  3519. });
  3520. svr.wait_until_ready();
  3521. {
  3522. Client cli(HOST, port);
  3523. auto res = cli.Get("/a\tb\x1b\x7f");
  3524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3525. EXPECT_EQ("/a%09b%1B%7F", target);
  3526. }
  3527. }
  3528. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3529. // Nothing may reach the wire: a raw CR/LF target would split the request
  3530. // line and inject headers.
  3531. Server svr;
  3532. // Pre-routing so that "not called" means nothing reached the server at all,
  3533. // rather than merely failing to match a handler pattern.
  3534. auto handler_called = false;
  3535. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3536. handler_called = true;
  3537. res.status = StatusCode::OK_200;
  3538. return Server::HandlerResponse::Handled;
  3539. });
  3540. auto port = svr.bind_to_any_port(HOST);
  3541. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3542. auto se = detail::scope_exit([&] {
  3543. svr.stop();
  3544. thread.join();
  3545. ASSERT_FALSE(svr.is_running());
  3546. });
  3547. svr.wait_until_ready();
  3548. {
  3549. Client cli(HOST, port);
  3550. cli.set_path_encode(false);
  3551. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3552. EXPECT_FALSE(handle.is_valid());
  3553. EXPECT_EQ(Error::Write, handle.error);
  3554. EXPECT_FALSE(handler_called);
  3555. }
  3556. }
  3557. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3558. // Which of the two branches runs is decided by whether the query component
  3559. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3560. // an empty query and must still fall back to building one from
  3561. // `req.params`, while a non-empty query must win over `req.params`.
  3562. Server svr;
  3563. std::string target;
  3564. svr.Get("/foo", [&](const Request &req, Response &res) {
  3565. target = req.target;
  3566. res.status = StatusCode::OK_200;
  3567. });
  3568. auto port = svr.bind_to_any_port(HOST);
  3569. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3570. auto se = detail::scope_exit([&] {
  3571. svr.stop();
  3572. thread.join();
  3573. ASSERT_FALSE(svr.is_running());
  3574. });
  3575. svr.wait_until_ready();
  3576. {
  3577. // Trailing `?` -> empty query component -> `req.params` is used.
  3578. Client cli(HOST, port);
  3579. Request req;
  3580. req.method = "GET";
  3581. req.path = "/foo?";
  3582. req.params.emplace("a", "1");
  3583. target.clear();
  3584. auto res = cli.send(req);
  3585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3586. EXPECT_EQ("/foo?a=1", target);
  3587. }
  3588. {
  3589. // Non-empty query in `req.path` -> `req.params` is not appended.
  3590. Client cli(HOST, port);
  3591. Request req;
  3592. req.method = "GET";
  3593. req.path = "/foo?b=2";
  3594. req.params.emplace("a", "1");
  3595. target.clear();
  3596. auto res = cli.send(req);
  3597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3598. EXPECT_EQ("/foo?b=2", target);
  3599. }
  3600. }
  3601. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3602. Server svr;
  3603. svr.Get("/", [](const Request &req, Response &) {
  3604. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3605. });
  3606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3607. auto se = detail::scope_exit([&] {
  3608. svr.stop();
  3609. thread.join();
  3610. ASSERT_FALSE(svr.is_running());
  3611. });
  3612. svr.wait_until_ready();
  3613. {
  3614. Client cli(HOST, PORT);
  3615. cli.set_path_encode(false);
  3616. auto res = cli.Get("/?something=%0A");
  3617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3618. EXPECT_EQ(StatusCode::OK_200, res->status);
  3619. }
  3620. }
  3621. TEST(BindServerTest, BindDualStack) {
  3622. Server svr;
  3623. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. thread.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. {
  3634. Client cli("127.0.0.1", PORT);
  3635. auto res = cli.Get("/1");
  3636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3637. EXPECT_EQ(StatusCode::OK_200, res->status);
  3638. EXPECT_EQ("Hello World!", res->body);
  3639. }
  3640. {
  3641. Client cli("::1", PORT);
  3642. auto res = cli.Get("/1");
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(StatusCode::OK_200, res->status);
  3645. EXPECT_EQ("Hello World!", res->body);
  3646. }
  3647. }
  3648. TEST(BindServerTest, BindAndListenSeparately) {
  3649. Server svr;
  3650. int port = svr.bind_to_any_port("0.0.0.0");
  3651. ASSERT_TRUE(svr.is_valid());
  3652. ASSERT_TRUE(port > 0);
  3653. svr.stop();
  3654. }
  3655. // Reports whether anything is still listening on a loopback port. A plain
  3656. // connect() is used instead of a Client request because a socket left bound by
  3657. // mistake accepts the connection into its backlog and never answers, which
  3658. // would hang the test instead of failing it.
  3659. static bool is_loopback_port_accepting(int port) {
  3660. sockaddr_in addr{};
  3661. addr.sin_family = AF_INET;
  3662. addr.sin_port = htons(static_cast<uint16_t>(port));
  3663. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3664. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3665. EXPECT_NE(sock, INVALID_SOCKET);
  3666. if (sock == INVALID_SOCKET) { return false; }
  3667. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3668. static_cast<socklen_t>(sizeof(addr)));
  3669. detail::close_socket(sock);
  3670. return ret == 0;
  3671. }
  3672. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3673. Server svr;
  3674. auto port = svr.bind_to_any_port("127.0.0.1");
  3675. ASSERT_TRUE(port > 0);
  3676. svr.stop();
  3677. // bind_to_any_port() already called listen(2), so until stop() closed the
  3678. // descriptor the port kept accepting connections into the backlog. ASSERT
  3679. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3680. // below blocks forever in the accept loop.
  3681. ASSERT_FALSE(is_loopback_port_accepting(port));
  3682. // Nothing is left to accept on, so listen_after_bind() must report failure
  3683. // instead of returning success without ever serving.
  3684. EXPECT_FALSE(svr.listen_after_bind());
  3685. // The failed listen marks the server decommissioned, so a waiter returns
  3686. // instead of spinning forever.
  3687. svr.wait_until_ready();
  3688. }
  3689. #ifdef CPPHTTPLIB_SSL_ENABLED
  3690. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3692. CLIENT_CA_CERT_DIR);
  3693. int port = svr.bind_to_any_port("0.0.0.0");
  3694. ASSERT_TRUE(svr.is_valid());
  3695. ASSERT_TRUE(port > 0);
  3696. svr.stop();
  3697. }
  3698. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3699. // or a rejected CustomRoute() registration would not stop the server binding.
  3700. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3702. CLIENT_CA_CERT_DIR);
  3703. ASSERT_TRUE(svr.is_valid());
  3704. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3705. EXPECT_FALSE(svr.is_valid());
  3706. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3707. }
  3708. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3709. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3710. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3711. int port = svr.bind_to_any_port("0.0.0.0");
  3712. ASSERT_TRUE(svr.is_valid());
  3713. ASSERT_TRUE(port > 0);
  3714. svr.stop();
  3715. }
  3716. TEST(BindServerTest, UpdateCertsPem) {
  3717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3718. int port = svr.bind_to_any_port("0.0.0.0");
  3719. ASSERT_TRUE(svr.is_valid());
  3720. ASSERT_TRUE(port > 0);
  3721. // Read PEM files
  3722. std::string cert_pem, key_pem, ca_pem;
  3723. read_file(SERVER_CERT_FILE, cert_pem);
  3724. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3725. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3726. // Update server certificates using PEM API
  3727. ASSERT_TRUE(
  3728. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3729. ASSERT_TRUE(svr.is_valid());
  3730. svr.stop();
  3731. }
  3732. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3733. // Start server with client CA (enables client auth)
  3734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3735. ASSERT_TRUE(svr.is_valid());
  3736. bool handler_called = false;
  3737. svr.Get("/test", [&](const Request &req, Response &res) {
  3738. handler_called = true;
  3739. // Verify client certificate is present
  3740. auto cert = req.peer_cert();
  3741. EXPECT_TRUE(static_cast<bool>(cert));
  3742. res.set_content("ok", "text/plain");
  3743. });
  3744. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3745. auto se = detail::scope_exit([&] {
  3746. svr.stop();
  3747. t.join();
  3748. ASSERT_FALSE(svr.is_running());
  3749. });
  3750. svr.wait_until_ready();
  3751. // Read PEM files
  3752. std::string cert_pem, key_pem, ca_pem;
  3753. read_file(SERVER_CERT_FILE, cert_pem);
  3754. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3755. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3756. // Update server certificates and client CA using PEM API while server running
  3757. ASSERT_TRUE(
  3758. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3759. // Connect with client certificate
  3760. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3761. cli.enable_server_certificate_verification(false);
  3762. cli.set_connection_timeout(30);
  3763. auto res = cli.Get("/test");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. ASSERT_EQ(StatusCode::OK_200, res->status);
  3766. ASSERT_TRUE(handler_called);
  3767. EXPECT_EQ("ok", res->body);
  3768. }
  3769. #endif
  3770. TEST(ErrorHandlerTest, ContentLength) {
  3771. Server svr;
  3772. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3773. res.status = StatusCode::OK_200;
  3774. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3775. "text/html"); // <= Content-Length still 13
  3776. });
  3777. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3778. res.set_content("Hello World!\n", "text/plain");
  3779. res.status = 524;
  3780. });
  3781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3782. auto se = detail::scope_exit([&] {
  3783. svr.stop();
  3784. thread.join();
  3785. ASSERT_FALSE(svr.is_running());
  3786. });
  3787. svr.wait_until_ready();
  3788. {
  3789. Client cli(HOST, PORT);
  3790. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3792. EXPECT_EQ(StatusCode::OK_200, res->status);
  3793. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3794. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3795. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3796. }
  3797. }
  3798. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3799. TEST(ExceptionTest, WithoutExceptionHandler) {
  3800. Server svr;
  3801. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3802. throw std::runtime_error("exception...");
  3803. });
  3804. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3805. throw std::runtime_error("exception\r\n...");
  3806. });
  3807. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3808. auto se = detail::scope_exit([&] {
  3809. svr.stop();
  3810. listen_thread.join();
  3811. ASSERT_FALSE(svr.is_running());
  3812. });
  3813. svr.wait_until_ready();
  3814. Client cli("localhost", PORT);
  3815. {
  3816. auto res = cli.Get("/exception");
  3817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3818. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3819. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3820. }
  3821. {
  3822. auto res = cli.Get("/unknown");
  3823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3824. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3825. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3826. }
  3827. }
  3828. TEST(ExceptionTest, WithExceptionHandler) {
  3829. Server svr;
  3830. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3831. std::exception_ptr ep) {
  3832. EXPECT_FALSE(ep == nullptr);
  3833. try {
  3834. std::rethrow_exception(ep);
  3835. } catch (std::exception &e) {
  3836. EXPECT_EQ("abc", std::string(e.what()));
  3837. } catch (...) {}
  3838. res.status = StatusCode::InternalServerError_500;
  3839. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3840. "text/html"); // <= Content-Length still 13 at this point
  3841. });
  3842. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3843. res.set_content("Hello World!\n", "text/plain");
  3844. throw std::runtime_error("abc");
  3845. });
  3846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3847. auto se = detail::scope_exit([&] {
  3848. svr.stop();
  3849. thread.join();
  3850. ASSERT_FALSE(svr.is_running());
  3851. });
  3852. svr.wait_until_ready();
  3853. for (size_t i = 0; i < 10; i++) {
  3854. Client cli(HOST, PORT);
  3855. for (size_t j = 0; j < 100; j++) {
  3856. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3858. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3859. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3860. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3861. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3862. }
  3863. cli.set_keep_alive(true);
  3864. for (size_t j = 0; j < 100; j++) {
  3865. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3867. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3868. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3869. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3870. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3871. }
  3872. }
  3873. }
  3874. TEST(ExceptionTest, AndErrorHandler) {
  3875. Server svr;
  3876. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3877. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3878. });
  3879. svr.set_exception_handler(
  3880. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3881. EXPECT_FALSE(ep == nullptr);
  3882. try {
  3883. std::rethrow_exception(ep);
  3884. } catch (std::exception &e) {
  3885. res.set_content(e.what(), "text/html");
  3886. } catch (...) {}
  3887. res.status = StatusCode::InternalServerError_500;
  3888. });
  3889. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3890. throw std::runtime_error("EXCEPTION");
  3891. });
  3892. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3893. res.set_content("ERROR", "text/html");
  3894. res.status = StatusCode::InternalServerError_500;
  3895. });
  3896. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3897. auto se = detail::scope_exit([&] {
  3898. svr.stop();
  3899. thread.join();
  3900. ASSERT_FALSE(svr.is_running());
  3901. });
  3902. svr.wait_until_ready();
  3903. Client cli(HOST, PORT);
  3904. {
  3905. auto res = cli.Get("/exception");
  3906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3907. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3908. EXPECT_EQ("EXCEPTION", res->body);
  3909. }
  3910. {
  3911. auto res = cli.Get("/error");
  3912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3913. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3914. EXPECT_EQ("ERROR", res->body);
  3915. }
  3916. {
  3917. auto res = cli.Get("/invalid");
  3918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3920. EXPECT_EQ("NOT_FOUND", res->body);
  3921. }
  3922. }
  3923. #endif
  3924. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3925. // process_request() wraps only routing() in a try/catch, so an exception from
  3926. // any other user callback used to unwind into the task queue - which does not
  3927. // catch - and terminate the process. Each test below runs the server on a
  3928. // single worker thread: a guard that catches the exception but still loses the
  3929. // thread would otherwise be hidden by a spare worker serving the follow-up
  3930. // request. Note that a regression here aborts the whole test binary rather
  3931. // than failing one test.
  3932. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3933. Server svr;
  3934. svr.new_task_queue = [] { return new ThreadPool(1); };
  3935. std::atomic<int> reported{0};
  3936. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3937. if (err == Error::UserCallbackException) { reported++; }
  3938. });
  3939. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3940. res.set_content_provider(
  3941. 1024, "text/plain",
  3942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3943. sink.write("hello", 5);
  3944. throw std::runtime_error("from the content provider");
  3945. });
  3946. });
  3947. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3948. res.set_content("ok", "text/plain");
  3949. });
  3950. auto port = svr.bind_to_any_port(HOST);
  3951. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3952. auto se = detail::scope_exit([&] {
  3953. svr.stop();
  3954. listen_thread.join();
  3955. ASSERT_FALSE(svr.is_running());
  3956. });
  3957. svr.wait_until_ready();
  3958. {
  3959. Client cli(HOST, port);
  3960. cli.set_read_timeout(5, 0);
  3961. EXPECT_FALSE(cli.Get("/throw"));
  3962. }
  3963. EXPECT_TRUE(svr.is_running());
  3964. EXPECT_EQ(1, reported.load());
  3965. // A request on a fresh connection is still served.
  3966. {
  3967. Client cli(HOST, port);
  3968. auto res = cli.Get("/ok");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. EXPECT_EQ(StatusCode::OK_200, res->status);
  3971. EXPECT_EQ("ok", res->body);
  3972. }
  3973. }
  3974. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3975. Server svr;
  3976. svr.new_task_queue = [] { return new ThreadPool(1); };
  3977. std::atomic<bool> should_throw{true};
  3978. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3979. res.set_content("hi", "text/plain");
  3980. });
  3981. svr.set_post_routing_handler(
  3982. [&](const Request & /*req*/, Response & /*res*/) {
  3983. if (should_throw) {
  3984. throw std::runtime_error("from the post-routing handler");
  3985. }
  3986. });
  3987. auto port = svr.bind_to_any_port(HOST);
  3988. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3989. auto se = detail::scope_exit([&] {
  3990. svr.stop();
  3991. listen_thread.join();
  3992. ASSERT_FALSE(svr.is_running());
  3993. });
  3994. svr.wait_until_ready();
  3995. {
  3996. Client cli(HOST, port);
  3997. cli.set_read_timeout(5, 0);
  3998. EXPECT_FALSE(cli.Get("/hi"));
  3999. }
  4000. EXPECT_TRUE(svr.is_running());
  4001. should_throw = false;
  4002. {
  4003. Client cli(HOST, port);
  4004. auto res = cli.Get("/hi");
  4005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4006. EXPECT_EQ(StatusCode::OK_200, res->status);
  4007. EXPECT_EQ("hi", res->body);
  4008. }
  4009. }
  4010. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4011. // The guard reports the caught exception through the error logger, which is
  4012. // a user callback too. A logger that throws has to be contained as well, or
  4013. // the process would terminate from inside the catch.
  4014. Server svr;
  4015. svr.new_task_queue = [] { return new ThreadPool(1); };
  4016. std::atomic<int> reported{0};
  4017. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4018. if (err == Error::UserCallbackException) {
  4019. reported++;
  4020. throw std::runtime_error("from the error logger");
  4021. }
  4022. });
  4023. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4024. res.set_content_provider(
  4025. 1024, "text/plain",
  4026. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4027. sink.write("hello", 5);
  4028. throw std::runtime_error("from the content provider");
  4029. });
  4030. });
  4031. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4032. res.set_content("ok", "text/plain");
  4033. });
  4034. auto port = svr.bind_to_any_port(HOST);
  4035. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4036. auto se = detail::scope_exit([&] {
  4037. svr.stop();
  4038. listen_thread.join();
  4039. ASSERT_FALSE(svr.is_running());
  4040. });
  4041. svr.wait_until_ready();
  4042. {
  4043. Client cli(HOST, port);
  4044. cli.set_read_timeout(5, 0);
  4045. EXPECT_FALSE(cli.Get("/throw"));
  4046. }
  4047. EXPECT_TRUE(svr.is_running());
  4048. EXPECT_EQ(1, reported.load());
  4049. {
  4050. Client cli(HOST, port);
  4051. auto res = cli.Get("/ok");
  4052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4053. EXPECT_EQ(StatusCode::OK_200, res->status);
  4054. EXPECT_EQ("ok", res->body);
  4055. }
  4056. }
  4057. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4058. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4059. // so the exception unwinds through the ws::WebSocket object on its way to
  4060. // the guard. None of the HTTP cases above cross that.
  4061. Server svr;
  4062. svr.new_task_queue = [] { return new ThreadPool(1); };
  4063. std::atomic<int> reported{0};
  4064. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4065. if (err == Error::UserCallbackException) { reported++; }
  4066. });
  4067. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4068. throw std::runtime_error("from the WebSocket handler");
  4069. });
  4070. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4071. res.set_content("ok", "text/plain");
  4072. });
  4073. auto port = svr.bind_to_any_port(HOST);
  4074. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4075. auto se = detail::scope_exit([&] {
  4076. svr.stop();
  4077. listen_thread.join();
  4078. ASSERT_FALSE(svr.is_running());
  4079. });
  4080. svr.wait_until_ready();
  4081. {
  4082. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4083. "/ws");
  4084. auto res = client.connect();
  4085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4086. // The server dropped the connection instead of dying.
  4087. std::string msg;
  4088. EXPECT_FALSE(client.read(msg));
  4089. client.close();
  4090. }
  4091. EXPECT_TRUE(svr.is_running());
  4092. EXPECT_EQ(1, reported.load());
  4093. {
  4094. Client cli(HOST, port);
  4095. auto res = cli.Get("/ok");
  4096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4097. EXPECT_EQ(StatusCode::OK_200, res->status);
  4098. EXPECT_EQ("ok", res->body);
  4099. }
  4100. }
  4101. #ifdef CPPHTTPLIB_SSL_ENABLED
  4102. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4103. // SSLServer::process_and_close_socket() is a separate overload with its own
  4104. // guard, so it is exercised on its own.
  4105. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4106. ASSERT_TRUE(svr.is_valid());
  4107. svr.new_task_queue = [] { return new ThreadPool(1); };
  4108. std::atomic<int> reported{0};
  4109. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4110. if (err == Error::UserCallbackException) { reported++; }
  4111. });
  4112. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4113. res.set_content_provider(
  4114. 1024, "text/plain",
  4115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4116. sink.write("hello", 5);
  4117. throw std::runtime_error("from the content provider");
  4118. });
  4119. });
  4120. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4121. res.set_content("ok", "text/plain");
  4122. });
  4123. auto port = svr.bind_to_any_port(HOST);
  4124. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4125. auto se = detail::scope_exit([&] {
  4126. svr.stop();
  4127. listen_thread.join();
  4128. ASSERT_FALSE(svr.is_running());
  4129. });
  4130. svr.wait_until_ready();
  4131. {
  4132. SSLClient cli(HOST, port);
  4133. cli.enable_server_certificate_verification(false);
  4134. cli.set_read_timeout(5, 0);
  4135. EXPECT_FALSE(cli.Get("/throw"));
  4136. }
  4137. EXPECT_TRUE(svr.is_running());
  4138. EXPECT_EQ(1, reported.load());
  4139. {
  4140. SSLClient cli(HOST, port);
  4141. cli.enable_server_certificate_verification(false);
  4142. auto res = cli.Get("/ok");
  4143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4144. EXPECT_EQ(StatusCode::OK_200, res->status);
  4145. EXPECT_EQ("ok", res->body);
  4146. }
  4147. }
  4148. #endif
  4149. #endif
  4150. TEST(NoContentTest, ContentLength) {
  4151. Server svr;
  4152. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4153. res.status = StatusCode::NoContent_204;
  4154. });
  4155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4156. auto se = detail::scope_exit([&] {
  4157. svr.stop();
  4158. thread.join();
  4159. ASSERT_FALSE(svr.is_running());
  4160. });
  4161. svr.wait_until_ready();
  4162. {
  4163. Client cli(HOST, PORT);
  4164. auto res = cli.Get("/hi");
  4165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4166. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4167. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4168. }
  4169. }
  4170. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4171. #ifdef CPPHTTPLIB_SSL_ENABLED
  4172. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4173. ASSERT_TRUE(svr.is_valid());
  4174. #else
  4175. Server svr;
  4176. #endif
  4177. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4178. if (req.path == "/routing_handler") {
  4179. res.set_header("PRE_ROUTING", "on");
  4180. res.set_content("Routing Handler", "text/plain");
  4181. return httplib::Server::HandlerResponse::Handled;
  4182. }
  4183. return httplib::Server::HandlerResponse::Unhandled;
  4184. });
  4185. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4186. res.set_content("Error", "text/html");
  4187. });
  4188. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4189. if (req.path == "/routing_handler") {
  4190. res.set_header("POST_ROUTING", "on");
  4191. }
  4192. });
  4193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4194. res.set_content("Hello World!\n", "text/plain");
  4195. });
  4196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4197. auto se = detail::scope_exit([&] {
  4198. svr.stop();
  4199. thread.join();
  4200. ASSERT_FALSE(svr.is_running());
  4201. });
  4202. svr.wait_until_ready();
  4203. {
  4204. #ifdef CPPHTTPLIB_SSL_ENABLED
  4205. SSLClient cli(HOST, PORT);
  4206. cli.enable_server_certificate_verification(false);
  4207. #else
  4208. Client cli(HOST, PORT);
  4209. #endif
  4210. auto res = cli.Get("/routing_handler");
  4211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4212. EXPECT_EQ(StatusCode::OK_200, res->status);
  4213. EXPECT_EQ("Routing Handler", res->body);
  4214. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4215. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4216. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4217. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4218. }
  4219. {
  4220. #ifdef CPPHTTPLIB_SSL_ENABLED
  4221. SSLClient cli(HOST, PORT);
  4222. cli.enable_server_certificate_verification(false);
  4223. #else
  4224. Client cli(HOST, PORT);
  4225. #endif
  4226. auto res = cli.Get("/hi");
  4227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4228. EXPECT_EQ(StatusCode::OK_200, res->status);
  4229. EXPECT_EQ("Hello World!\n", res->body);
  4230. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4231. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4232. }
  4233. {
  4234. #ifdef CPPHTTPLIB_SSL_ENABLED
  4235. SSLClient cli(HOST, PORT);
  4236. cli.enable_server_certificate_verification(false);
  4237. #else
  4238. Client cli(HOST, PORT);
  4239. #endif
  4240. auto res = cli.Get("/aaa");
  4241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4243. EXPECT_EQ("Error", res->body);
  4244. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4245. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4246. }
  4247. }
  4248. TEST(RequestHandlerTest, PreRequestHandler) {
  4249. auto route_path = "/user/:user";
  4250. Server svr;
  4251. svr.Get("/hi", [](const Request &, Response &res) {
  4252. res.set_content("hi", "text/plain");
  4253. });
  4254. svr.Get(route_path, [](const Request &req, Response &res) {
  4255. res.set_content(req.path_params.at("user"), "text/plain");
  4256. });
  4257. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4258. if (req.matched_route == route_path) {
  4259. auto user = req.path_params.at("user");
  4260. if (user != "john") {
  4261. res.status = StatusCode::Forbidden_403;
  4262. res.set_content("error", "text/html");
  4263. return Server::HandlerResponse::Handled;
  4264. }
  4265. }
  4266. return Server::HandlerResponse::Unhandled;
  4267. });
  4268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4269. auto se = detail::scope_exit([&] {
  4270. svr.stop();
  4271. thread.join();
  4272. ASSERT_FALSE(svr.is_running());
  4273. });
  4274. svr.wait_until_ready();
  4275. Client cli(HOST, PORT);
  4276. {
  4277. auto res = cli.Get("/hi");
  4278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4279. EXPECT_EQ(StatusCode::OK_200, res->status);
  4280. EXPECT_EQ("hi", res->body);
  4281. }
  4282. {
  4283. auto res = cli.Get("/user/john");
  4284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4285. EXPECT_EQ(StatusCode::OK_200, res->status);
  4286. EXPECT_EQ("john", res->body);
  4287. }
  4288. {
  4289. auto res = cli.Get("/user/invalid-user");
  4290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4291. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4292. EXPECT_EQ("error", res->body);
  4293. }
  4294. }
  4295. // The pre-request handler must run before the request body is read, so a
  4296. // rejected request never forces the server to buffer a (potentially large)
  4297. // body. Here the posted body is larger than the payload limit: if the body
  4298. // were read first the server would answer 413, but because the pre-request
  4299. // handler runs first it answers 403 and the body is never read.
  4300. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4301. Server svr;
  4302. svr.set_payload_max_length(8);
  4303. auto handler_ran = false;
  4304. svr.Post("/reject", [&](const Request &req, Response &res) {
  4305. handler_ran = true;
  4306. res.set_content(req.body, "text/plain");
  4307. });
  4308. svr.Post("/accept", [](const Request &req, Response &res) {
  4309. res.set_content(req.body, "text/plain");
  4310. });
  4311. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4312. if (req.matched_route == "/reject") {
  4313. res.status = StatusCode::Forbidden_403;
  4314. res.set_content("denied", "text/plain");
  4315. return Server::HandlerResponse::Handled;
  4316. }
  4317. return Server::HandlerResponse::Unhandled;
  4318. });
  4319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4320. auto se = detail::scope_exit([&] {
  4321. svr.stop();
  4322. thread.join();
  4323. ASSERT_FALSE(svr.is_running());
  4324. });
  4325. svr.wait_until_ready();
  4326. Client cli(HOST, PORT);
  4327. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4328. // rejects with 403 before the body is read, so 413 is never reached.
  4329. {
  4330. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4332. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4333. EXPECT_EQ("denied", res->body);
  4334. EXPECT_FALSE(handler_ran);
  4335. }
  4336. // An approved route still reads the body and enforces the payload limit.
  4337. {
  4338. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4341. }
  4342. }
  4343. TEST(UserDataTest, BasicOperations) {
  4344. httplib::UserData ud;
  4345. // Initially empty
  4346. EXPECT_FALSE(ud.has("key"));
  4347. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4348. // set and get
  4349. ud.set("key", 42);
  4350. EXPECT_TRUE(ud.has("key"));
  4351. auto *p = ud.get<int>("key");
  4352. ASSERT_NE(nullptr, p);
  4353. EXPECT_EQ(42, *p);
  4354. // Type mismatch → nullptr
  4355. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4356. // Overwrite with different type
  4357. ud.set("key", std::string("hello"));
  4358. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4359. auto *s = ud.get<std::string>("key");
  4360. ASSERT_NE(nullptr, s);
  4361. EXPECT_EQ("hello", *s);
  4362. // erase
  4363. ud.erase("key");
  4364. EXPECT_FALSE(ud.has("key"));
  4365. // clear
  4366. ud.set("a", 1);
  4367. ud.set("b", 2);
  4368. ud.clear();
  4369. EXPECT_FALSE(ud.has("a"));
  4370. EXPECT_FALSE(ud.has("b"));
  4371. }
  4372. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4373. struct AuthCtx {
  4374. std::string user_id;
  4375. };
  4376. Server svr;
  4377. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4378. res.user_data.set("auth", AuthCtx{"alice"});
  4379. return Server::HandlerResponse::Unhandled;
  4380. });
  4381. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4382. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4383. ASSERT_NE(nullptr, ctx);
  4384. res.set_content("Hello " + ctx->user_id, "text/plain");
  4385. });
  4386. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4387. auto se = detail::scope_exit([&] {
  4388. svr.stop();
  4389. thread.join();
  4390. ASSERT_FALSE(svr.is_running());
  4391. });
  4392. svr.wait_until_ready();
  4393. Client cli(HOST, PORT);
  4394. auto res = cli.Get("/me");
  4395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4396. EXPECT_EQ(StatusCode::OK_200, res->status);
  4397. EXPECT_EQ("Hello alice", res->body);
  4398. }
  4399. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4400. struct RoleCtx {
  4401. std::string role;
  4402. };
  4403. Server svr;
  4404. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4405. res.user_data.set("role", RoleCtx{"admin"});
  4406. return Server::HandlerResponse::Unhandled;
  4407. });
  4408. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4409. auto *ctx = res.user_data.get<RoleCtx>("role");
  4410. ASSERT_NE(nullptr, ctx);
  4411. res.set_content(ctx->role, "text/plain");
  4412. });
  4413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4414. auto se = detail::scope_exit([&] {
  4415. svr.stop();
  4416. thread.join();
  4417. ASSERT_FALSE(svr.is_running());
  4418. });
  4419. svr.wait_until_ready();
  4420. Client cli(HOST, PORT);
  4421. auto res = cli.Get("/role");
  4422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4423. EXPECT_EQ(StatusCode::OK_200, res->status);
  4424. EXPECT_EQ("admin", res->body);
  4425. }
  4426. TEST(InvalidFormatTest, StatusCode) {
  4427. Server svr;
  4428. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4429. res.set_content("Hello World!\n", "text/plain");
  4430. res.status = 9999; // Status should be a three-digit code...
  4431. });
  4432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4433. auto se = detail::scope_exit([&] {
  4434. svr.stop();
  4435. thread.join();
  4436. ASSERT_FALSE(svr.is_running());
  4437. });
  4438. svr.wait_until_ready();
  4439. {
  4440. Client cli(HOST, PORT);
  4441. auto res = cli.Get("/hi");
  4442. ASSERT_FALSE(res);
  4443. }
  4444. }
  4445. TEST(URLFragmentTest, WithFragment) {
  4446. Server svr;
  4447. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4448. EXPECT_TRUE(req.target == "/hi");
  4449. });
  4450. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4451. auto se = detail::scope_exit([&] {
  4452. svr.stop();
  4453. thread.join();
  4454. ASSERT_FALSE(svr.is_running());
  4455. });
  4456. svr.wait_until_ready();
  4457. {
  4458. Client cli(HOST, PORT);
  4459. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4460. EXPECT_TRUE(res);
  4461. EXPECT_EQ(StatusCode::OK_200, res->status);
  4462. res = cli.Get("/hi%23key1=val1=key2=val2");
  4463. EXPECT_TRUE(res);
  4464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4465. }
  4466. }
  4467. TEST(HeaderWriter, SetHeaderWriter) {
  4468. Server svr;
  4469. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4470. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4471. return detail::write_headers(strm, hdrs);
  4472. });
  4473. svr.Get("/hi", [](const Request &req, Response &res) {
  4474. auto it = req.headers.find("CustomClientHeader");
  4475. EXPECT_TRUE(it != req.headers.end());
  4476. EXPECT_EQ(it->second, "CustomClientValue");
  4477. res.set_content("Hello World!\n", "text/plain");
  4478. });
  4479. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4480. auto se = detail::scope_exit([&] {
  4481. svr.stop();
  4482. thread.join();
  4483. ASSERT_FALSE(svr.is_running());
  4484. });
  4485. svr.wait_until_ready();
  4486. {
  4487. Client cli(HOST, PORT);
  4488. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4489. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4490. return detail::write_headers(strm, hdrs);
  4491. });
  4492. auto res = cli.Get("/hi");
  4493. EXPECT_TRUE(res);
  4494. EXPECT_EQ(StatusCode::OK_200, res->status);
  4495. auto it = res->headers.find("CustomServerHeader");
  4496. EXPECT_TRUE(it != res->headers.end());
  4497. EXPECT_EQ(it->second, "CustomServerValue");
  4498. }
  4499. }
  4500. class ServerTest : public ::testing::Test {
  4501. protected:
  4502. ServerTest()
  4503. : cli_(HOST, PORT)
  4504. #ifdef CPPHTTPLIB_SSL_ENABLED
  4505. ,
  4506. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4507. #endif
  4508. {
  4509. #ifdef CPPHTTPLIB_SSL_ENABLED
  4510. cli_.enable_server_certificate_verification(false);
  4511. #endif
  4512. // Allow LARGE_DATA (100MB) responses
  4513. cli_.set_payload_max_length(200 * 1024 * 1024);
  4514. }
  4515. virtual void SetUp() {
  4516. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4517. svr_.set_payload_max_length(200 * 1024 * 1024);
  4518. svr_.set_mount_point("/", "./www");
  4519. svr_.set_mount_point("/mount", "./www2");
  4520. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4521. svr_.Get("/hi",
  4522. [&](const Request & /*req*/, Response &res) {
  4523. res.set_content("Hello World!", "text/plain");
  4524. })
  4525. .Get("/file_content",
  4526. [&](const Request & /*req*/, Response &res) {
  4527. res.set_file_content("./www/dir/test.html");
  4528. })
  4529. .Get("/file_content_with_content_type",
  4530. [&](const Request & /*req*/, Response &res) {
  4531. res.set_file_content("./www/file", "text/plain");
  4532. })
  4533. .Get("/invalid_file_content",
  4534. [&](const Request & /*req*/, Response &res) {
  4535. res.set_file_content("./www/dir/invalid_file_path");
  4536. })
  4537. .Get("/http_response_splitting",
  4538. [&](const Request & /*req*/, Response &res) {
  4539. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4540. EXPECT_EQ(0U, res.headers.size());
  4541. EXPECT_FALSE(res.has_header("a"));
  4542. res.set_header("a", "1\nSet-Cookie: a=1");
  4543. EXPECT_EQ(0U, res.headers.size());
  4544. EXPECT_FALSE(res.has_header("a"));
  4545. res.set_header("a", "1\rSet-Cookie: a=1");
  4546. EXPECT_EQ(0U, res.headers.size());
  4547. EXPECT_FALSE(res.has_header("a"));
  4548. res.set_header("a\r\nb", "0");
  4549. EXPECT_EQ(0U, res.headers.size());
  4550. EXPECT_FALSE(res.has_header("a"));
  4551. res.set_header("a\rb", "0");
  4552. EXPECT_EQ(0U, res.headers.size());
  4553. EXPECT_FALSE(res.has_header("a"));
  4554. res.set_header("a\nb", "0");
  4555. EXPECT_EQ(0U, res.headers.size());
  4556. EXPECT_FALSE(res.has_header("a"));
  4557. res.set_redirect("1\r\nSet-Cookie: a=1");
  4558. EXPECT_EQ(0U, res.headers.size());
  4559. EXPECT_FALSE(res.has_header("Location"));
  4560. })
  4561. .Get("/slow",
  4562. [&](const Request & /*req*/, Response &res) {
  4563. std::this_thread::sleep_for(std::chrono::seconds(4));
  4564. res.set_content("slow", "text/plain");
  4565. })
  4566. #if 0
  4567. .Post("/slowpost",
  4568. [&](const Request & /*req*/, Response &res) {
  4569. std::this_thread::sleep_for(std::chrono::seconds(2));
  4570. res.set_content("slow", "text/plain");
  4571. })
  4572. #endif
  4573. .Get("/remote_addr",
  4574. [&](const Request &req, Response &res) {
  4575. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4576. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4577. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4578. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4579. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4580. #endif
  4581. res.set_content(req.remote_addr, "text/plain");
  4582. })
  4583. .Get("/local_addr",
  4584. [&](const Request &req, Response &res) {
  4585. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4586. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4587. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4588. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4589. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4590. #endif
  4591. auto local_addr = req.local_addr;
  4592. auto local_port = std::to_string(req.local_port);
  4593. res.set_content(local_addr.append(":").append(local_port),
  4594. "text/plain");
  4595. })
  4596. .Get("/endwith%",
  4597. [&](const Request & /*req*/, Response &res) {
  4598. res.set_content("Hello World!", "text/plain");
  4599. })
  4600. .Get("/a\\+\\+b",
  4601. [&](const Request &req, Response &res) {
  4602. ASSERT_TRUE(req.has_param("a +b"));
  4603. auto val = req.get_param_value("a +b");
  4604. res.set_content(val, "text/plain");
  4605. })
  4606. .Get("/", [&](const Request & /*req*/,
  4607. Response &res) { res.set_redirect("/hi"); })
  4608. .Post("/1",
  4609. [](const Request & /*req*/, Response &res) {
  4610. res.set_redirect("/2", StatusCode::SeeOther_303);
  4611. })
  4612. .Get("/2",
  4613. [](const Request & /*req*/, Response &res) {
  4614. res.set_content("redirected.", "text/plain");
  4615. res.status = StatusCode::OK_200;
  4616. })
  4617. .Post("/person",
  4618. [&](const Request &req, Response &res) {
  4619. if (req.has_param("name") && req.has_param("note")) {
  4620. persons_[req.get_param_value("name")] =
  4621. req.get_param_value("note");
  4622. } else {
  4623. res.status = StatusCode::BadRequest_400;
  4624. }
  4625. })
  4626. .Put("/person",
  4627. [&](const Request &req, Response &res) {
  4628. if (req.has_param("name") && req.has_param("note")) {
  4629. persons_[req.get_param_value("name")] =
  4630. req.get_param_value("note");
  4631. } else {
  4632. res.status = StatusCode::BadRequest_400;
  4633. }
  4634. })
  4635. .Get("/person/(.*)",
  4636. [&](const Request &req, Response &res) {
  4637. string name = req.matches[1];
  4638. if (persons_.find(name) != persons_.end()) {
  4639. auto note = persons_[name];
  4640. res.set_content(note, "text/plain");
  4641. } else {
  4642. res.status = StatusCode::NotFound_404;
  4643. }
  4644. })
  4645. .Delete("/person",
  4646. [&](const Request &req, Response &res) {
  4647. if (req.has_param("name")) {
  4648. string name = req.get_param_value("name");
  4649. if (persons_.find(name) != persons_.end()) {
  4650. persons_.erase(name);
  4651. res.set_content("DELETED", "text/plain");
  4652. } else {
  4653. res.status = StatusCode::NotFound_404;
  4654. }
  4655. } else {
  4656. res.status = StatusCode::BadRequest_400;
  4657. }
  4658. })
  4659. .Post("/x-www-form-urlencoded-json",
  4660. [&](const Request &req, Response &res) {
  4661. auto json = req.get_param_value("json");
  4662. ASSERT_EQ(JSON_DATA, json);
  4663. res.set_content(json, "appliation/json");
  4664. res.status = StatusCode::OK_200;
  4665. })
  4666. .Get("/streamed-chunked",
  4667. [&](const Request & /*req*/, Response &res) {
  4668. res.set_chunked_content_provider(
  4669. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4670. sink.os << "123";
  4671. sink.os << "456";
  4672. sink.os << "789";
  4673. sink.done();
  4674. return true;
  4675. });
  4676. })
  4677. .Get("/streamed-chunked-with-prohibited-trailer",
  4678. [&](const Request & /*req*/, Response &res) {
  4679. auto i = new int(0);
  4680. // Declare both a prohibited trailer (Content-Length) and an
  4681. // allowed one
  4682. res.set_header("Trailer", "Content-Length, X-Allowed");
  4683. res.set_chunked_content_provider(
  4684. "text/plain",
  4685. [i](size_t /*offset*/, DataSink &sink) {
  4686. switch (*i) {
  4687. case 0: sink.os << "123"; break;
  4688. case 1: sink.os << "456"; break;
  4689. case 2: sink.os << "789"; break;
  4690. case 3: {
  4691. sink.done_with_trailer(
  4692. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4693. } break;
  4694. }
  4695. (*i)++;
  4696. return true;
  4697. },
  4698. [i](bool success) {
  4699. EXPECT_TRUE(success);
  4700. delete i;
  4701. });
  4702. })
  4703. .Get("/streamed-chunked2",
  4704. [&](const Request & /*req*/, Response &res) {
  4705. auto i = new int(0);
  4706. res.set_chunked_content_provider(
  4707. "text/plain",
  4708. [i](size_t /*offset*/, DataSink &sink) {
  4709. switch (*i) {
  4710. case 0: sink.os << "123"; break;
  4711. case 1: sink.os << "456"; break;
  4712. case 2: sink.os << "789"; break;
  4713. case 3: sink.done(); break;
  4714. }
  4715. (*i)++;
  4716. return true;
  4717. },
  4718. [i](bool success) {
  4719. EXPECT_TRUE(success);
  4720. delete i;
  4721. });
  4722. })
  4723. .Get("/streamed-chunked-with-trailer",
  4724. [&](const Request & /*req*/, Response &res) {
  4725. auto i = new int(0);
  4726. res.set_header("Trailer", "Dummy1, Dummy2");
  4727. res.set_chunked_content_provider(
  4728. "text/plain",
  4729. [i](size_t /*offset*/, DataSink &sink) {
  4730. switch (*i) {
  4731. case 0: sink.os << "123"; break;
  4732. case 1: sink.os << "456"; break;
  4733. case 2: sink.os << "789"; break;
  4734. case 3: {
  4735. sink.done_with_trailer(
  4736. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4737. } break;
  4738. }
  4739. (*i)++;
  4740. return true;
  4741. },
  4742. [i](bool success) {
  4743. EXPECT_TRUE(success);
  4744. delete i;
  4745. });
  4746. })
  4747. .Get("/streamed",
  4748. [&](const Request & /*req*/, Response &res) {
  4749. res.set_content_provider(
  4750. 6, "text/plain",
  4751. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4752. sink.os << (offset < 3 ? "a" : "b");
  4753. return true;
  4754. });
  4755. })
  4756. .Get("/streamed-without-length",
  4757. [&](const Request & /*req*/, Response &res) {
  4758. auto data = new std::string("abcdefg");
  4759. res.set_content_provider(
  4760. "text/plain",
  4761. [data](size_t offset, DataSink &sink) {
  4762. if (offset < data->size()) {
  4763. sink.os << data->substr(offset);
  4764. }
  4765. sink.done();
  4766. return true;
  4767. },
  4768. [data](bool success) {
  4769. EXPECT_TRUE(success);
  4770. delete data;
  4771. });
  4772. })
  4773. .Get("/streamed-with-range",
  4774. [&](const Request &req, Response &res) {
  4775. auto data = new std::string("abcdefg");
  4776. // An explicit status keeps the server from picking the 206 it
  4777. // would otherwise choose for a ranged request, so the response
  4778. // is not a partial representation.
  4779. auto status = req.get_param_value("status");
  4780. if (status == "200") {
  4781. res.status = StatusCode::OK_200;
  4782. } else if (status == "403") {
  4783. res.status = StatusCode::Forbidden_403;
  4784. }
  4785. res.set_content_provider(
  4786. data->size(), "text/plain",
  4787. [data](size_t offset, size_t length, DataSink &sink) {
  4788. size_t DATA_CHUNK_SIZE = 4;
  4789. const auto &d = *data;
  4790. auto out_len =
  4791. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4792. auto ret =
  4793. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4794. EXPECT_TRUE(ret);
  4795. return true;
  4796. },
  4797. [data, &req](bool success) {
  4798. EXPECT_EQ(success, !req.has_param("error"));
  4799. delete data;
  4800. });
  4801. })
  4802. .Get("/streamed-cancel",
  4803. [&](const Request & /*req*/, Response &res) {
  4804. res.set_content_provider(
  4805. size_t(-1), "text/plain",
  4806. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4807. sink.os << "data_chunk";
  4808. return true;
  4809. });
  4810. })
  4811. .Get("/regex-with-delimiter",
  4812. [&](const Request &req, Response & /*res*/) {
  4813. ASSERT_TRUE(req.has_param("key"));
  4814. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4815. })
  4816. .Get("/with-range",
  4817. [&](const Request & /*req*/, Response &res) {
  4818. res.set_content("abcdefg", "text/plain");
  4819. })
  4820. .Get("/test-start-time",
  4821. [&](const Request &req, Response & /*res*/) {
  4822. EXPECT_NE(req.start_time_,
  4823. std::chrono::steady_clock::time_point::min());
  4824. })
  4825. .Get("/with-range-customized-response",
  4826. [&](const Request & /*req*/, Response &res) {
  4827. res.status = StatusCode::BadRequest_400;
  4828. res.set_content(JSON_DATA, "application/json");
  4829. })
  4830. .Post("/chunked",
  4831. [&](const Request &req, Response & /*res*/) {
  4832. EXPECT_EQ(req.body, "dechunked post body");
  4833. })
  4834. .Post("/large-chunked",
  4835. [&](const Request &req, Response & /*res*/) {
  4836. std::string expected(6 * 30 * 1024u, 'a');
  4837. EXPECT_EQ(req.body, expected);
  4838. })
  4839. .Post("/multipart",
  4840. [&](const Request &req, Response & /*res*/) {
  4841. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4842. req.form.get_field_count("text2") +
  4843. req.form.get_field_count("file3") +
  4844. req.form.get_field_count("file4"));
  4845. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4846. req.form.get_file_count("file2"));
  4847. ASSERT_TRUE(!req.form.has_file("???"));
  4848. ASSERT_TRUE(!req.form.has_field("???"));
  4849. ASSERT_TRUE(req.body.empty());
  4850. {
  4851. const auto &text = req.form.get_field("text1");
  4852. EXPECT_EQ("text default", text);
  4853. }
  4854. {
  4855. const auto &text = req.form.get_field("text2");
  4856. EXPECT_EQ("aωb", text);
  4857. }
  4858. {
  4859. const auto &file = req.form.get_file("file1");
  4860. EXPECT_EQ("hello.txt", file.filename);
  4861. EXPECT_EQ("text/plain", file.content_type);
  4862. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4863. }
  4864. {
  4865. const auto &file = req.form.get_file("file2");
  4866. EXPECT_EQ("world.json", file.filename);
  4867. EXPECT_EQ("application/json", file.content_type);
  4868. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4869. }
  4870. {
  4871. const auto &text = req.form.get_field("file3");
  4872. EXPECT_EQ(0u, text.size());
  4873. }
  4874. {
  4875. const auto &text = req.form.get_field("file4");
  4876. EXPECT_EQ(0u, text.size());
  4877. }
  4878. })
  4879. .Post("/multipart/multi_file_values",
  4880. [&](const Request &req, Response & /*res*/) {
  4881. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4882. req.form.get_field_count("multi_text1"));
  4883. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4884. ASSERT_TRUE(!req.form.has_file("???"));
  4885. ASSERT_TRUE(!req.form.has_field("???"));
  4886. ASSERT_TRUE(req.body.empty());
  4887. {
  4888. const auto &text = req.form.get_field("text");
  4889. EXPECT_EQ("default text", text);
  4890. }
  4891. {
  4892. const auto &text1_values = req.form.get_fields("multi_text1");
  4893. EXPECT_EQ(2u, text1_values.size());
  4894. EXPECT_EQ("aaaaa", text1_values[0]);
  4895. EXPECT_EQ("bbbbb", text1_values[1]);
  4896. }
  4897. {
  4898. const auto &file1_values = req.form.get_files("multi_file1");
  4899. EXPECT_EQ(2u, file1_values.size());
  4900. auto file1 = file1_values[0];
  4901. EXPECT_EQ(file1.filename, "hello.txt");
  4902. EXPECT_EQ(file1.content_type, "text/plain");
  4903. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4904. auto file2 = file1_values[1];
  4905. EXPECT_EQ(file2.filename, "world.json");
  4906. EXPECT_EQ(file2.content_type, "application/json");
  4907. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4908. }
  4909. })
  4910. .Post("/empty",
  4911. [&](const Request &req, Response &res) {
  4912. EXPECT_EQ(req.body, "");
  4913. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4914. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4915. res.set_content("empty", "text/plain");
  4916. })
  4917. .Post("/empty-no-content-type",
  4918. [&](const Request &req, Response &res) {
  4919. EXPECT_EQ(req.body, "");
  4920. EXPECT_FALSE(req.has_header("Content-Type"));
  4921. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4922. res.set_content("empty-no-content-type", "text/plain");
  4923. })
  4924. .Post("/path-only",
  4925. [&](const Request &req, Response &res) {
  4926. EXPECT_EQ(req.body, "");
  4927. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4928. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4929. res.set_content("path-only", "text/plain");
  4930. })
  4931. .Post("/path-headers-only",
  4932. [&](const Request &req, Response &res) {
  4933. EXPECT_EQ(req.body, "");
  4934. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4935. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4936. EXPECT_EQ("world", req.get_header_value("hello"));
  4937. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4938. res.set_content("path-headers-only", "text/plain");
  4939. })
  4940. .Post("/post-large",
  4941. [&](const Request &req, Response &res) {
  4942. EXPECT_EQ(req.body, LARGE_DATA);
  4943. res.set_content(req.body, "text/plain");
  4944. })
  4945. .Post("/post-loopback",
  4946. [&](const Request &, Response &res,
  4947. ContentReader const &content_reader) {
  4948. std::string body;
  4949. content_reader([&](const char *data, size_t data_length) {
  4950. body.append(data, data_length);
  4951. return true;
  4952. });
  4953. res.set_content(body, "text/plain");
  4954. })
  4955. .Put("/put-loopback",
  4956. [&](const Request &, Response &res,
  4957. ContentReader const &content_reader) {
  4958. std::string body;
  4959. content_reader([&](const char *data, size_t data_length) {
  4960. body.append(data, data_length);
  4961. return true;
  4962. });
  4963. res.set_content(body, "text/plain");
  4964. })
  4965. .Patch("/patch-loopback",
  4966. [&](const Request &, Response &res,
  4967. ContentReader const &content_reader) {
  4968. std::string body;
  4969. content_reader([&](const char *data, size_t data_length) {
  4970. body.append(data, data_length);
  4971. return true;
  4972. });
  4973. res.set_content(body, "text/plain");
  4974. })
  4975. .Put("/empty-no-content-type",
  4976. [&](const Request &req, Response &res) {
  4977. EXPECT_EQ(req.body, "");
  4978. EXPECT_FALSE(req.has_header("Content-Type"));
  4979. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4980. res.set_content("empty-no-content-type", "text/plain");
  4981. })
  4982. .Put("/put",
  4983. [&](const Request &req, Response &res) {
  4984. EXPECT_EQ(req.body, "PUT");
  4985. res.set_content(req.body, "text/plain");
  4986. })
  4987. .Put("/put-large",
  4988. [&](const Request &req, Response &res) {
  4989. EXPECT_EQ(req.body, LARGE_DATA);
  4990. res.set_content(req.body, "text/plain");
  4991. })
  4992. .Patch("/patch",
  4993. [&](const Request &req, Response &res) {
  4994. EXPECT_EQ(req.body, "PATCH");
  4995. res.set_content(req.body, "text/plain");
  4996. })
  4997. .Delete("/delete",
  4998. [&](const Request & /*req*/, Response &res) {
  4999. res.set_content("DELETE", "text/plain");
  5000. })
  5001. .Delete("/delete-body",
  5002. [&](const Request &req, Response &res) {
  5003. EXPECT_EQ(req.body, "content");
  5004. res.set_content(req.body, "text/plain");
  5005. })
  5006. .Options(R"(\*)",
  5007. [&](const Request & /*req*/, Response &res) {
  5008. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5009. })
  5010. .CustomRoute("PROPFIND", "/dav/:id",
  5011. [&](const Request &req, Response &res) {
  5012. res.set_header("x-body-size",
  5013. std::to_string(req.body.size()));
  5014. res.set_header("x-matched-route", req.matched_route);
  5015. res.set_header("x-dav-id", req.path_params.at("id"));
  5016. res.status = StatusCode::MultiStatus_207;
  5017. res.set_content(req.body, "application/xml");
  5018. })
  5019. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5020. [&](const Request &req, Response &res) {
  5021. res.set_header("x-dav-match", req.matches[1]);
  5022. res.status = StatusCode::MultiStatus_207;
  5023. })
  5024. .CustomRoute("MKCOL", "/dav-mkcol",
  5025. [&](const Request &req, Response &res) {
  5026. EXPECT_TRUE(req.body.empty());
  5027. res.status = StatusCode::Created_201;
  5028. })
  5029. .CustomRoute(
  5030. "REPORT", "/dav-report",
  5031. [&](const Request & /*req*/, Response &res,
  5032. const ContentReader &content_reader) {
  5033. std::string body;
  5034. content_reader([&](const char *data, size_t data_length) {
  5035. body.append(data, data_length);
  5036. return true;
  5037. });
  5038. res.set_header("x-body-size", std::to_string(body.size()));
  5039. res.status = StatusCode::MultiStatus_207;
  5040. res.set_content(body, "application/xml");
  5041. })
  5042. .Get("/request-target",
  5043. [&](const Request &req, Response & /*res*/) {
  5044. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5045. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5046. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5047. })
  5048. .Get("/long-query-value",
  5049. [&](const Request &req, Response & /*res*/) {
  5050. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5051. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5052. })
  5053. .Get("/too-long-query-value",
  5054. [&](const Request &req, Response & /*res*/) {
  5055. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5056. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5057. })
  5058. .Get("/array-param",
  5059. [&](const Request &req, Response & /*res*/) {
  5060. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5061. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5062. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5063. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5064. })
  5065. .Get("/array-param-values",
  5066. [&](const Request &req, Response & /*res*/) {
  5067. auto values = req.get_param_values("array");
  5068. EXPECT_EQ(3u, values.size());
  5069. EXPECT_EQ("value1", values[0]);
  5070. EXPECT_EQ("value2", values[1]);
  5071. EXPECT_EQ("value3", values[2]);
  5072. auto empty = req.get_param_values("nonexistent");
  5073. EXPECT_TRUE(empty.empty());
  5074. })
  5075. .Post("/validate-no-multiple-headers",
  5076. [&](const Request &req, Response & /*res*/) {
  5077. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5078. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5079. })
  5080. .Post("/content_receiver",
  5081. [&](const Request &req, Response &res,
  5082. const ContentReader &content_reader) {
  5083. if (req.is_multipart_form_data()) {
  5084. std::vector<FormData> items;
  5085. content_reader(
  5086. [&](const FormData &file) {
  5087. items.push_back(file);
  5088. return true;
  5089. },
  5090. [&](const char *data, size_t data_length) {
  5091. items.back().content.append(data, data_length);
  5092. return true;
  5093. });
  5094. EXPECT_EQ(5u, items.size());
  5095. {
  5096. const auto &file = get_file_value(items, "text1");
  5097. EXPECT_TRUE(file.filename.empty());
  5098. EXPECT_EQ("text default", file.content);
  5099. }
  5100. {
  5101. const auto &file = get_file_value(items, "text2");
  5102. EXPECT_TRUE(file.filename.empty());
  5103. EXPECT_EQ("aωb", file.content);
  5104. }
  5105. {
  5106. const auto &file = get_file_value(items, "file1");
  5107. EXPECT_EQ("hello.txt", file.filename);
  5108. EXPECT_EQ("text/plain", file.content_type);
  5109. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5110. }
  5111. {
  5112. const auto &file = get_file_value(items, "file2");
  5113. EXPECT_EQ("world.json", file.filename);
  5114. EXPECT_EQ("application/json", file.content_type);
  5115. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5116. }
  5117. {
  5118. const auto &file = get_file_value(items, "file3");
  5119. EXPECT_TRUE(file.filename.empty());
  5120. EXPECT_EQ("application/octet-stream", file.content_type);
  5121. EXPECT_EQ(0u, file.content.size());
  5122. }
  5123. } else {
  5124. std::string body;
  5125. content_reader([&](const char *data, size_t data_length) {
  5126. EXPECT_EQ(7U, data_length);
  5127. body.append(data, data_length);
  5128. return true;
  5129. });
  5130. EXPECT_EQ(body, "content");
  5131. res.set_content(body, "text/plain");
  5132. }
  5133. })
  5134. .Put("/content_receiver",
  5135. [&](const Request & /*req*/, Response &res,
  5136. const ContentReader &content_reader) {
  5137. std::string body;
  5138. content_reader([&](const char *data, size_t data_length) {
  5139. body.append(data, data_length);
  5140. return true;
  5141. });
  5142. EXPECT_EQ(body, "content");
  5143. res.set_content(body, "text/plain");
  5144. })
  5145. .Patch("/content_receiver",
  5146. [&](const Request & /*req*/, Response &res,
  5147. const ContentReader &content_reader) {
  5148. std::string body;
  5149. content_reader([&](const char *data, size_t data_length) {
  5150. body.append(data, data_length);
  5151. return true;
  5152. });
  5153. EXPECT_EQ(body, "content");
  5154. res.set_content(body, "text/plain");
  5155. })
  5156. .Post("/query-string-and-body",
  5157. [&](const Request &req, Response & /*res*/) {
  5158. ASSERT_TRUE(req.has_param("key"));
  5159. EXPECT_EQ(req.get_param_value("key"), "value");
  5160. EXPECT_EQ(req.body, "content");
  5161. })
  5162. .Get("/last-request",
  5163. [&](const Request &req, Response & /*res*/) {
  5164. EXPECT_EQ("close", req.get_header_value("Connection"));
  5165. })
  5166. .Get(R"(/redirect/(\d+))",
  5167. [&](const Request &req, Response &res) {
  5168. auto num = std::stoi(req.matches[1]) + 1;
  5169. std::string url = "/redirect/" + std::to_string(num);
  5170. res.set_redirect(url);
  5171. })
  5172. .Post("/binary",
  5173. [&](const Request &req, Response &res) {
  5174. EXPECT_EQ(4U, req.body.size());
  5175. EXPECT_EQ("application/octet-stream",
  5176. req.get_header_value("Content-Type"));
  5177. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5178. res.set_content(req.body, "application/octet-stream");
  5179. })
  5180. .Put("/binary",
  5181. [&](const Request &req, Response &res) {
  5182. EXPECT_EQ(4U, req.body.size());
  5183. EXPECT_EQ("application/octet-stream",
  5184. req.get_header_value("Content-Type"));
  5185. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5186. res.set_content(req.body, "application/octet-stream");
  5187. })
  5188. .Patch("/binary",
  5189. [&](const Request &req, Response &res) {
  5190. EXPECT_EQ(4U, req.body.size());
  5191. EXPECT_EQ("application/octet-stream",
  5192. req.get_header_value("Content-Type"));
  5193. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5194. res.set_content(req.body, "application/octet-stream");
  5195. })
  5196. .Delete("/binary",
  5197. [&](const Request &req, Response &res) {
  5198. EXPECT_EQ(4U, req.body.size());
  5199. EXPECT_EQ("application/octet-stream",
  5200. req.get_header_value("Content-Type"));
  5201. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5202. res.set_content(req.body, "application/octet-stream");
  5203. })
  5204. .Get("/issue1772",
  5205. [&](const Request & /*req*/, Response &res) {
  5206. res.status = 401;
  5207. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5208. })
  5209. .Delete("/issue609",
  5210. [](const httplib::Request &, httplib::Response &res,
  5211. const httplib::ContentReader &) {
  5212. res.set_content("ok", "text/plain");
  5213. })
  5214. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5215. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5216. .Get("/compress",
  5217. [&](const Request & /*req*/, Response &res) {
  5218. res.set_content(
  5219. "12345678901234567890123456789012345678901234567890123456789"
  5220. "01234567890123456789012345678901234567890",
  5221. "text/plain");
  5222. })
  5223. .Get("/compress-with-charset",
  5224. [&](const Request & /*req*/, Response &res) {
  5225. res.set_content(
  5226. "12345678901234567890123456789012345678901234567890123456789"
  5227. "01234567890123456789012345678901234567890",
  5228. "application/json; charset=utf-8");
  5229. })
  5230. .Get("/nocompress",
  5231. [&](const Request & /*req*/, Response &res) {
  5232. res.set_content(
  5233. "12345678901234567890123456789012345678901234567890123456789"
  5234. "01234567890123456789012345678901234567890",
  5235. "application/octet-stream");
  5236. })
  5237. .Post("/compress-multipart",
  5238. [&](const Request &req, Response & /*res*/) {
  5239. EXPECT_EQ(2u, req.form.fields.size());
  5240. ASSERT_TRUE(!req.form.has_field("???"));
  5241. {
  5242. const auto &text = req.form.get_field("key1");
  5243. EXPECT_EQ("test", text);
  5244. }
  5245. {
  5246. const auto &text = req.form.get_field("key2");
  5247. EXPECT_EQ("--abcdefg123", text);
  5248. }
  5249. })
  5250. #endif
  5251. ;
  5252. persons_["john"] = "programmer";
  5253. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5254. svr_.wait_until_ready();
  5255. }
  5256. virtual void TearDown() {
  5257. svr_.stop();
  5258. if (!request_threads_.empty()) {
  5259. std::this_thread::sleep_for(std::chrono::seconds(1));
  5260. for (auto &t : request_threads_) {
  5261. t.join();
  5262. }
  5263. }
  5264. t_.join();
  5265. }
  5266. map<string, string> persons_;
  5267. #ifdef CPPHTTPLIB_SSL_ENABLED
  5268. SSLClient cli_;
  5269. SSLServer svr_;
  5270. #else
  5271. Client cli_;
  5272. Server svr_;
  5273. #endif
  5274. thread t_;
  5275. std::vector<thread> request_threads_;
  5276. };
  5277. TEST_F(ServerTest, GetMethod200) {
  5278. auto res = cli_.Get("/hi");
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. EXPECT_EQ("HTTP/1.1", res->version);
  5281. EXPECT_EQ(StatusCode::OK_200, res->status);
  5282. EXPECT_EQ("OK", res->reason);
  5283. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5284. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5285. EXPECT_EQ("Hello World!", res->body);
  5286. }
  5287. TEST_F(ServerTest, GetEmptyFile) {
  5288. auto res = cli_.Get("/empty_file");
  5289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5290. EXPECT_EQ(StatusCode::OK_200, res->status);
  5291. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5292. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5293. EXPECT_EQ("", res->body);
  5294. }
  5295. TEST_F(ServerTest, GetFileContent) {
  5296. auto res = cli_.Get("/file_content");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5300. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5301. EXPECT_EQ("test.html", res->body);
  5302. }
  5303. TEST_F(ServerTest, GetFileContentWithRange) {
  5304. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5307. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5308. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5309. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5310. EXPECT_EQ("est", res->body);
  5311. }
  5312. TEST_F(ServerTest, GetFileContentWithContentType) {
  5313. auto res = cli_.Get("/file_content_with_content_type");
  5314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5315. EXPECT_EQ(StatusCode::OK_200, res->status);
  5316. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5317. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5318. EXPECT_EQ("file\n", res->body);
  5319. }
  5320. TEST_F(ServerTest, GetInvalidFileContent) {
  5321. auto res = cli_.Get("/invalid_file_content");
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5324. }
  5325. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5326. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5328. EXPECT_EQ("HTTP/1.1", res->version);
  5329. EXPECT_EQ(StatusCode::OK_200, res->status);
  5330. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5331. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5332. EXPECT_EQ("Hello World!", res->body);
  5333. }
  5334. TEST_F(ServerTest, GetMethod302) {
  5335. auto res = cli_.Get("/");
  5336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5337. EXPECT_EQ(StatusCode::Found_302, res->status);
  5338. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5339. }
  5340. TEST_F(ServerTest, GetMethod302Redirect) {
  5341. cli_.set_follow_location(true);
  5342. auto res = cli_.Get("/");
  5343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5344. EXPECT_EQ(StatusCode::OK_200, res->status);
  5345. EXPECT_EQ("Hello World!", res->body);
  5346. EXPECT_EQ("/hi", res->location);
  5347. }
  5348. TEST_F(ServerTest, GetMethod404) {
  5349. auto res = cli_.Get("/invalid");
  5350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5351. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5352. }
  5353. TEST_F(ServerTest, HeadMethod200) {
  5354. auto res = cli_.Head("/hi");
  5355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5356. EXPECT_EQ(StatusCode::OK_200, res->status);
  5357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5358. EXPECT_TRUE(res->body.empty());
  5359. }
  5360. TEST_F(ServerTest, HeadMethod200Static) {
  5361. auto res = cli_.Head("/mount/dir/index.html");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5365. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5366. EXPECT_TRUE(res->body.empty());
  5367. }
  5368. TEST_F(ServerTest, HeadMethod404) {
  5369. auto res = cli_.Head("/invalid");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5372. EXPECT_TRUE(res->body.empty());
  5373. }
  5374. TEST_F(ServerTest, GetMethodPersonJohn) {
  5375. auto res = cli_.Get("/person/john");
  5376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5377. EXPECT_EQ(StatusCode::OK_200, res->status);
  5378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("programmer", res->body);
  5380. }
  5381. TEST_F(ServerTest, PostMethod1) {
  5382. auto res = cli_.Get("/person/john1");
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5385. res = cli_.Post("/person", "name=john1&note=coder",
  5386. "application/x-www-form-urlencoded");
  5387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5388. ASSERT_EQ(StatusCode::OK_200, res->status);
  5389. res = cli_.Get("/person/john1");
  5390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5391. ASSERT_EQ(StatusCode::OK_200, res->status);
  5392. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5393. ASSERT_EQ("coder", res->body);
  5394. }
  5395. TEST_F(ServerTest, PostMethod2) {
  5396. auto res = cli_.Get("/person/john2");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5399. Params params;
  5400. params.emplace("name", "john2");
  5401. params.emplace("note", "coder");
  5402. res = cli_.Post("/person", params);
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. ASSERT_EQ(StatusCode::OK_200, res->status);
  5405. res = cli_.Get("/person/john2");
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. ASSERT_EQ(StatusCode::OK_200, res->status);
  5408. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5409. ASSERT_EQ("coder", res->body);
  5410. }
  5411. TEST_F(ServerTest, PutMethod3) {
  5412. auto res = cli_.Get("/person/john3");
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5415. Params params;
  5416. params.emplace("name", "john3");
  5417. params.emplace("note", "coder");
  5418. res = cli_.Put("/person", params);
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. ASSERT_EQ(StatusCode::OK_200, res->status);
  5421. res = cli_.Get("/person/john3");
  5422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5423. ASSERT_EQ(StatusCode::OK_200, res->status);
  5424. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5425. ASSERT_EQ("coder", res->body);
  5426. }
  5427. TEST_F(ServerTest, DeleteMethod1) {
  5428. auto res = cli_.Get("/person/john4");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5431. Params params;
  5432. params.emplace("name", "john4");
  5433. params.emplace("note", "coder");
  5434. res = cli_.Post("/person", params);
  5435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5436. ASSERT_EQ(StatusCode::OK_200, res->status);
  5437. res = cli_.Get("/person/john4");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. ASSERT_EQ(StatusCode::OK_200, res->status);
  5440. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5441. ASSERT_EQ("coder", res->body);
  5442. Params delete_params;
  5443. delete_params.emplace("name", "john4");
  5444. res = cli_.Delete("/person", delete_params);
  5445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5446. ASSERT_EQ(StatusCode::OK_200, res->status);
  5447. ASSERT_EQ("DELETED", res->body);
  5448. res = cli_.Get("/person/john4");
  5449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5450. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5451. }
  5452. TEST_F(ServerTest, DeleteMethod2) {
  5453. auto res = cli_.Get("/person/john5");
  5454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5455. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5456. Params params;
  5457. params.emplace("name", "john5");
  5458. params.emplace("note", "developer");
  5459. res = cli_.Post("/person", params);
  5460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5461. ASSERT_EQ(StatusCode::OK_200, res->status);
  5462. res = cli_.Get("/person/john5");
  5463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5464. ASSERT_EQ(StatusCode::OK_200, res->status);
  5465. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5466. ASSERT_EQ("developer", res->body);
  5467. Params delete_params;
  5468. delete_params.emplace("name", "john5");
  5469. Headers headers;
  5470. headers.emplace("Custom-Header", "test-value");
  5471. res = cli_.Delete("/person", headers, delete_params);
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. ASSERT_EQ(StatusCode::OK_200, res->status);
  5474. ASSERT_EQ("DELETED", res->body);
  5475. res = cli_.Get("/person/john5");
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5478. }
  5479. TEST_F(ServerTest, DeleteMethod3) {
  5480. auto res = cli_.Get("/person/john6");
  5481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5482. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5483. Params params;
  5484. params.emplace("name", "john6");
  5485. params.emplace("note", "tester");
  5486. res = cli_.Post("/person", params);
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. ASSERT_EQ(StatusCode::OK_200, res->status);
  5489. res = cli_.Get("/person/john6");
  5490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5491. ASSERT_EQ(StatusCode::OK_200, res->status);
  5492. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5493. ASSERT_EQ("tester", res->body);
  5494. Params delete_params;
  5495. delete_params.emplace("name", "john6");
  5496. Headers headers;
  5497. headers.emplace("Custom-Header", "test-value");
  5498. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5500. ASSERT_EQ(StatusCode::OK_200, res->status);
  5501. ASSERT_EQ("DELETED", res->body);
  5502. res = cli_.Get("/person/john6");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5505. }
  5506. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5507. Params params;
  5508. params.emplace("json", JSON_DATA);
  5509. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5511. ASSERT_EQ(StatusCode::OK_200, res->status);
  5512. ASSERT_EQ(JSON_DATA, res->body);
  5513. }
  5514. TEST_F(ServerTest, PostEmptyContent) {
  5515. auto res = cli_.Post("/empty", "", "text/plain");
  5516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5517. ASSERT_EQ(StatusCode::OK_200, res->status);
  5518. ASSERT_EQ("empty", res->body);
  5519. }
  5520. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5521. auto res = cli_.Post("/empty-no-content-type");
  5522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5523. ASSERT_EQ(StatusCode::OK_200, res->status);
  5524. ASSERT_EQ("empty-no-content-type", res->body);
  5525. }
  5526. TEST_F(ServerTest, PostPathOnly) {
  5527. auto res = cli_.Post("/path-only");
  5528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5529. ASSERT_EQ(StatusCode::OK_200, res->status);
  5530. ASSERT_EQ("path-only", res->body);
  5531. }
  5532. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5533. auto res = cli_.Post("/path-headers-only",
  5534. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5536. ASSERT_EQ(StatusCode::OK_200, res->status);
  5537. ASSERT_EQ("path-headers-only", res->body);
  5538. }
  5539. TEST_F(ServerTest, PostLarge) {
  5540. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. ASSERT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ(LARGE_DATA, res->body);
  5544. }
  5545. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5546. auto res = cli_.Put("/empty-no-content-type");
  5547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5548. ASSERT_EQ(StatusCode::OK_200, res->status);
  5549. ASSERT_EQ("empty-no-content-type", res->body);
  5550. }
  5551. TEST_F(ServerTest, GetMethodDir) {
  5552. auto res = cli_.Get("/dir/");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::OK_200, res->status);
  5555. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5556. auto body = R"(<html>
  5557. <head>
  5558. </head>
  5559. <body>
  5560. <a href="/dir/test.html">Test</a>
  5561. <a href="/hi">hi</a>
  5562. </body>
  5563. </html>
  5564. )";
  5565. EXPECT_EQ(body, res->body);
  5566. }
  5567. TEST_F(ServerTest, GetMethodDirTest) {
  5568. auto res = cli_.Get("/dir/test.html");
  5569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5570. EXPECT_EQ(StatusCode::OK_200, res->status);
  5571. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5572. EXPECT_EQ("test.html", res->body);
  5573. }
  5574. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5575. auto res = cli_.Get("/dir/../dir/test.html");
  5576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5577. EXPECT_EQ(StatusCode::OK_200, res->status);
  5578. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5579. EXPECT_EQ("test.html", res->body);
  5580. }
  5581. TEST_F(ServerTest, GetMethodInvalidPath) {
  5582. auto res = cli_.Get("/dir/../test.html");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5585. }
  5586. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5587. auto res = cli_.Get("/../www/dir/test.html");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5590. }
  5591. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5592. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5595. }
  5596. TEST_F(ServerTest, GetMethodDirMountTest) {
  5597. auto res = cli_.Get("/mount/dir/test.html");
  5598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5599. EXPECT_EQ(StatusCode::OK_200, res->status);
  5600. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5601. EXPECT_EQ("test.html", res->body);
  5602. }
  5603. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5604. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5606. EXPECT_EQ(StatusCode::OK_200, res->status);
  5607. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5608. EXPECT_EQ("test.html", res->body);
  5609. }
  5610. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5611. auto res = cli_.Get("/mount/dir/../test.html");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5614. }
  5615. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5616. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5619. }
  5620. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5621. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5623. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5624. }
  5625. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5626. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5629. }
  5630. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5631. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5633. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5634. }
  5635. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5636. auto res = cli_.Get("/mount/dir");
  5637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5638. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5639. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5640. }
  5641. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5642. auto res = cli_.Get("//dir");
  5643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5644. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5645. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5646. }
  5647. TEST_F(ServerTest, PostMethod303) {
  5648. auto res = cli_.Post("/1", "body", "text/plain");
  5649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5650. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5651. EXPECT_EQ("/2", res->get_header_value("Location"));
  5652. }
  5653. TEST_F(ServerTest, PostMethod303Redirect) {
  5654. cli_.set_follow_location(true);
  5655. auto res = cli_.Post("/1", "body", "text/plain");
  5656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5657. EXPECT_EQ(StatusCode::OK_200, res->status);
  5658. EXPECT_EQ("redirected.", res->body);
  5659. EXPECT_EQ("/2", res->location);
  5660. }
  5661. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5662. auto res = cli_.Get("/dir/test.abcde");
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. EXPECT_EQ(StatusCode::OK_200, res->status);
  5665. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5666. EXPECT_EQ("abcde", res->body);
  5667. }
  5668. TEST_F(ServerTest, StaticFileRange) {
  5669. auto res =
  5670. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5673. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5674. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5675. EXPECT_EQ(true, res->has_header("Content-Range"));
  5676. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5677. EXPECT_EQ(std::string("cd"), res->body);
  5678. }
  5679. TEST_F(ServerTest, StaticFileRanges) {
  5680. auto res = cli_.Get("/dir/test.abcde",
  5681. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5684. EXPECT_TRUE(
  5685. res->get_header_value("Content-Type")
  5686. .find(
  5687. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5688. 0);
  5689. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5690. }
  5691. TEST_F(ServerTest, StaticFileRangeHead) {
  5692. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5695. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5696. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5697. EXPECT_EQ(true, res->has_header("Content-Range"));
  5698. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5699. }
  5700. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5701. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5703. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5705. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5706. EXPECT_EQ(true, res->has_header("Content-Range"));
  5707. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5708. res->get_header_value("Content-Range"));
  5709. EXPECT_EQ("LAST\n", res->body);
  5710. }
  5711. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5712. auto res =
  5713. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5716. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5717. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5718. EXPECT_EQ(true, res->has_header("Content-Range"));
  5719. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5720. }
  5721. TEST_F(ServerTest, StaticFileBigFile) {
  5722. auto res = cli_.Get("/dir/1MB.txt");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::OK_200, res->status);
  5725. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5726. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5727. }
  5728. TEST_F(ServerTest, InvalidBaseDirMount) {
  5729. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5730. }
  5731. TEST_F(ServerTest, Binary) {
  5732. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5733. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5734. "application/octet-stream");
  5735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5736. ASSERT_EQ(StatusCode::OK_200, res->status);
  5737. ASSERT_EQ(4U, res->body.size());
  5738. res = cli_.Put("/binary", binary.data(), binary.size(),
  5739. "application/octet-stream");
  5740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5741. ASSERT_EQ(StatusCode::OK_200, res->status);
  5742. ASSERT_EQ(4U, res->body.size());
  5743. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5744. "application/octet-stream");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. ASSERT_EQ(StatusCode::OK_200, res->status);
  5747. ASSERT_EQ(4U, res->body.size());
  5748. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5749. "application/octet-stream");
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. ASSERT_EQ(StatusCode::OK_200, res->status);
  5752. ASSERT_EQ(4U, res->body.size());
  5753. }
  5754. TEST_F(ServerTest, BinaryString) {
  5755. auto binary = std::string("\x00\x01\x02\x03", 4);
  5756. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. ASSERT_EQ(StatusCode::OK_200, res->status);
  5759. ASSERT_EQ(4U, res->body.size());
  5760. res = cli_.Put("/binary", binary, "application/octet-stream");
  5761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5762. ASSERT_EQ(StatusCode::OK_200, res->status);
  5763. ASSERT_EQ(4U, res->body.size());
  5764. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5766. ASSERT_EQ(StatusCode::OK_200, res->status);
  5767. ASSERT_EQ(4U, res->body.size());
  5768. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5770. ASSERT_EQ(StatusCode::OK_200, res->status);
  5771. ASSERT_EQ(4U, res->body.size());
  5772. }
  5773. TEST_F(ServerTest, EmptyRequest) {
  5774. auto res = cli_.Get("");
  5775. ASSERT_TRUE(!res);
  5776. EXPECT_EQ(Error::Connection, res.error());
  5777. }
  5778. TEST_F(ServerTest, LongRequest) {
  5779. std::string request;
  5780. for (size_t i = 0; i < 545; i++) {
  5781. request += "/TooLongRequest";
  5782. }
  5783. request += "OK";
  5784. auto res = cli_.Get(request.c_str());
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5787. }
  5788. TEST_F(ServerTest, TooLongRequest) {
  5789. std::string request;
  5790. for (size_t i = 0; i < 546; i++) {
  5791. request += "/TooLongRequest";
  5792. }
  5793. request += "_NG";
  5794. auto start = std::chrono::high_resolution_clock::now();
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get(request.c_str());
  5797. auto end = std::chrono::high_resolution_clock::now();
  5798. auto elapsed =
  5799. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5800. .count();
  5801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5802. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5803. EXPECT_LE(elapsed, 1000);
  5804. EXPECT_EQ("close", res->get_header_value("Connection"));
  5805. EXPECT_FALSE(cli_.is_socket_open());
  5806. }
  5807. TEST_F(ServerTest, AlmostTooLongRequest) {
  5808. // test for #2046 - URI length check shouldn't include other content on req
  5809. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5810. // leading /, space, HTTP/1.1)
  5811. std::string request =
  5812. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5813. auto res = cli_.Get(request.c_str());
  5814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5816. }
  5817. TEST_F(ServerTest, LongHeader) {
  5818. Request req;
  5819. req.method = "GET";
  5820. req.path = "/hi";
  5821. std::string host_and_port;
  5822. host_and_port += HOST;
  5823. host_and_port += ":";
  5824. host_and_port += std::to_string(PORT);
  5825. req.headers.emplace("Host", host_and_port.c_str());
  5826. req.headers.emplace("Accept", "*/*");
  5827. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5828. req.headers.emplace(
  5829. "Header-Name",
  5830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5852. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5853. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5854. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5855. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5856. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5857. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5858. "@@@@@@@@@@@@@@@@");
  5859. auto res = std::make_shared<Response>();
  5860. auto error = Error::Success;
  5861. auto ret = cli_.send(req, *res, error);
  5862. ASSERT_TRUE(ret);
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. }
  5865. TEST_F(ServerTest, LongQueryValue) {
  5866. auto start = std::chrono::high_resolution_clock::now();
  5867. cli_.set_keep_alive(true);
  5868. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5869. auto end = std::chrono::high_resolution_clock::now();
  5870. auto elapsed =
  5871. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5872. .count();
  5873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5874. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5875. EXPECT_LE(elapsed, 1000);
  5876. EXPECT_EQ("close", res->get_header_value("Connection"));
  5877. EXPECT_FALSE(cli_.is_socket_open());
  5878. }
  5879. TEST_F(ServerTest, TooLongQueryValue) {
  5880. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5881. ASSERT_FALSE(res);
  5882. EXPECT_EQ(Error::Read, res.error());
  5883. }
  5884. TEST_F(ServerTest, TooLongHeader) {
  5885. Request req;
  5886. req.method = "GET";
  5887. req.path = "/hi";
  5888. std::string host_and_port;
  5889. host_and_port += HOST;
  5890. host_and_port += ":";
  5891. host_and_port += std::to_string(PORT);
  5892. req.headers.emplace("Host", host_and_port.c_str());
  5893. req.headers.emplace("Accept", "*/*");
  5894. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5895. req.headers.emplace(
  5896. "Header-Name",
  5897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5919. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5920. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5921. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5922. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5923. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5924. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5925. "@@@@@@@@@@@@@@@@@");
  5926. auto res = std::make_shared<Response>();
  5927. auto error = Error::Success;
  5928. auto ret = cli_.send(req, *res, error);
  5929. ASSERT_TRUE(ret);
  5930. EXPECT_EQ(StatusCode::OK_200, res->status);
  5931. }
  5932. TEST_F(ServerTest, HeaderCountAtLimit) {
  5933. // Test with headers just under the 100 limit
  5934. httplib::Headers headers;
  5935. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5936. // This should keep us just under the 100 header limit
  5937. for (int i = 0; i < 95; i++) {
  5938. std::string name = "X-Test-Header-" + std::to_string(i);
  5939. std::string value = "value" + std::to_string(i);
  5940. headers.emplace(name, value);
  5941. }
  5942. // This should work fine as we're under the limit
  5943. auto res = cli_.Get("/hi", headers);
  5944. EXPECT_TRUE(res);
  5945. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5946. }
  5947. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5948. // Test with many headers to exceed the 100 limit
  5949. httplib::Headers headers;
  5950. // Add 150 headers to definitely exceed the 100 limit
  5951. for (int i = 0; i < 150; i++) {
  5952. std::string name = "X-Test-Header-" + std::to_string(i);
  5953. std::string value = "value" + std::to_string(i);
  5954. headers.emplace(name, value);
  5955. }
  5956. // This should fail due to exceeding header count limit
  5957. cli_.set_keep_alive(true);
  5958. auto res = cli_.Get("/hi", headers);
  5959. // The server should respond with 400 Bad Request
  5960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5961. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5962. EXPECT_EQ("close", res->get_header_value("Connection"));
  5963. EXPECT_FALSE(cli_.is_socket_open());
  5964. }
  5965. TEST_F(ServerTest, PercentEncoding) {
  5966. auto res = cli_.Get("/e%6edwith%");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. }
  5970. TEST_F(ServerTest, PercentEncodingUnicode) {
  5971. auto res = cli_.Get("/e%u006edwith%");
  5972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5973. EXPECT_EQ(StatusCode::OK_200, res->status);
  5974. }
  5975. TEST_F(ServerTest, InvalidPercentEncoding) {
  5976. auto res = cli_.Get("/%endwith%");
  5977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5978. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5979. }
  5980. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5981. auto res = cli_.Get("/%uendwith%");
  5982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5983. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5984. }
  5985. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5986. auto res = cli_.Get("/hello?aaa=bbb%");
  5987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5989. }
  5990. TEST_F(ServerTest, PlusSignEncoding) {
  5991. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::OK_200, res->status);
  5994. EXPECT_EQ("a +b", res->body);
  5995. }
  5996. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5997. // This test simulates a potential DoS attack using many headers
  5998. // to verify our security fix prevents memory exhaustion
  5999. httplib::Headers attack_headers;
  6000. // Attempt to add many headers like an attacker would (200 headers to far
  6001. // exceed limit)
  6002. for (int i = 0; i < 200; i++) {
  6003. std::string name = "X-Attack-Header-" + std::to_string(i);
  6004. std::string value = "attack_payload_" + std::to_string(i);
  6005. attack_headers.emplace(name, value);
  6006. }
  6007. // Try to POST with excessive headers
  6008. cli_.set_keep_alive(true);
  6009. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6010. // Should either fail or return 400 Bad Request due to security limit
  6011. if (res) {
  6012. // If we get a response, it should be 400 Bad Request
  6013. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6014. EXPECT_EQ("close", res->get_header_value("Connection"));
  6015. }
  6016. EXPECT_FALSE(cli_.is_socket_open());
  6017. }
  6018. TEST_F(ServerTest, MultipartFormData) {
  6019. UploadFormDataItems items = {
  6020. {"text1", "text default", "", ""},
  6021. {"text2", "aωb", "", ""},
  6022. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6023. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6024. {"file3", "", "", "application/octet-stream"},
  6025. {"file4", "", "", " application/json tmp-string "}};
  6026. auto res = cli_.Post("/multipart", items);
  6027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6028. EXPECT_EQ(StatusCode::OK_200, res->status);
  6029. }
  6030. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6031. UploadFormDataItems items = {
  6032. {"text", "default text", "", ""},
  6033. {"multi_text1", "aaaaa", "", ""},
  6034. {"multi_text1", "bbbbb", "", ""},
  6035. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6036. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6037. "application/json"},
  6038. };
  6039. auto res = cli_.Post("/multipart/multi_file_values", items);
  6040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6041. EXPECT_EQ(StatusCode::OK_200, res->status);
  6042. }
  6043. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6044. auto res = cli_.Get("/hi");
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::OK_200, res->status);
  6047. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6048. EXPECT_EQ("Hello World!", res->body);
  6049. }
  6050. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6051. Request req;
  6052. req.method = "POST";
  6053. req.path = "/chunked";
  6054. std::string host_and_port;
  6055. host_and_port += HOST;
  6056. host_and_port += ":";
  6057. host_and_port += std::to_string(PORT);
  6058. req.headers.emplace("Host", host_and_port.c_str());
  6059. req.headers.emplace("Accept", "*/*");
  6060. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6061. req.headers.emplace("Content-Type", "text/plain");
  6062. req.headers.emplace("Content-Length", "0");
  6063. req.headers.emplace(
  6064. "Transfer-Encoding",
  6065. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6066. // Client does not chunk, so make a chunked body manually.
  6067. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6068. auto res = std::make_shared<Response>();
  6069. auto error = Error::Success;
  6070. auto ret = cli_.send(req, *res, error);
  6071. ASSERT_TRUE(ret);
  6072. EXPECT_EQ(StatusCode::OK_200, res->status);
  6073. }
  6074. template <typename ClientT>
  6075. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6076. int expected_status) {
  6077. Request req;
  6078. req.method = "POST";
  6079. req.path = "/chunked";
  6080. std::string host_and_port;
  6081. host_and_port += HOST;
  6082. host_and_port += ":";
  6083. host_and_port += std::to_string(PORT);
  6084. req.headers.emplace("Host", host_and_port.c_str());
  6085. req.headers.emplace("Content-Length", "0");
  6086. req.headers.emplace("Transfer-Encoding", "chunked");
  6087. req.body = body;
  6088. auto res = std::make_shared<Response>();
  6089. auto error = Error::Success;
  6090. ASSERT_TRUE(cli.send(req, *res, error));
  6091. EXPECT_EQ(expected_status, res->status);
  6092. }
  6093. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6094. // rather than treat them as valid lengths.
  6095. template <typename ClientT>
  6096. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6097. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6098. }
  6099. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6100. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6101. }
  6102. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6103. expect_chunked_body_rejected(
  6104. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6105. }
  6106. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6107. // chunk-size line carries no CR, LF or other control character ahead of its
  6108. // terminator. Such a line must be refused rather than read as extension text.
  6109. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6110. expect_chunked_body_rejected(
  6111. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6112. }
  6113. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6114. expect_chunked_body_rejected(
  6115. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6116. }
  6117. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6118. expect_chunked_body_rejected(
  6119. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6120. }
  6121. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6122. // The literal stays split: a hex escape consumes every hex digit that
  6123. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6124. expect_chunked_body_rejected(
  6125. cli_, "4;a\x01"
  6126. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6127. }
  6128. TEST_F(ServerTest, AcceptsChunkExtension) {
  6129. expect_chunked_body_status(cli_,
  6130. "4;name=value\r\ndech\r\n"
  6131. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6132. "0;last\r\n\r\n",
  6133. StatusCode::OK_200);
  6134. }
  6135. TEST_F(ServerTest, GetStreamed2) {
  6136. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6139. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6140. EXPECT_EQ(true, res->has_header("Content-Range"));
  6141. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6142. EXPECT_EQ(std::string("ab"), res->body);
  6143. }
  6144. TEST_F(ServerTest, GetStreamed) {
  6145. auto res = cli_.Get("/streamed");
  6146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6147. EXPECT_EQ(StatusCode::OK_200, res->status);
  6148. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6149. EXPECT_EQ(std::string("aaabbb"), res->body);
  6150. }
  6151. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6152. auto res = cli_.Get("/streamed-without-length",
  6153. Headers{make_range_header({{0, -1}})});
  6154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6155. EXPECT_EQ(StatusCode::OK_200, res->status);
  6156. EXPECT_EQ(false, res->has_header("Content-Length"));
  6157. EXPECT_EQ(false, res->has_header("Content-Range"));
  6158. EXPECT_EQ(std::string("abcdefg"), res->body);
  6159. }
  6160. TEST_F(ServerTest, GetStreamedWithRange1) {
  6161. auto res =
  6162. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6164. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6165. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6166. EXPECT_EQ(true, res->has_header("Content-Range"));
  6167. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6168. EXPECT_EQ(std::string("def"), res->body);
  6169. }
  6170. TEST_F(ServerTest, GetStreamedWithRange2) {
  6171. auto res =
  6172. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6175. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6176. EXPECT_EQ(true, res->has_header("Content-Range"));
  6177. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6178. EXPECT_EQ(std::string("bcdefg"), res->body);
  6179. }
  6180. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6181. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6184. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6185. EXPECT_EQ(true, res->has_header("Content-Range"));
  6186. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6187. EXPECT_EQ(std::string("efg"), res->body);
  6188. }
  6189. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6190. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6191. // the entire representation.
  6192. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6193. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6195. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6196. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6197. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6198. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6199. }
  6200. }
  6201. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6202. auto res =
  6203. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6206. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6207. EXPECT_EQ(false, res->has_header("Content-Range"));
  6208. EXPECT_EQ(0U, res->body.size());
  6209. }
  6210. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6211. // Only a 206 is served as a partial representation. Under any other status
  6212. // `apply_ranges()` reported the full content length, so the body must match
  6213. // that header, and the content provider must never be asked for an offset
  6214. // outside the representation.
  6215. auto check = [&](int status, const char *range) {
  6216. auto path =
  6217. std::string("/streamed-with-range?status=") + std::to_string(status);
  6218. auto ctx = path + " Range: " + range;
  6219. auto res = cli_.Get(path, Headers{{"Range", range}});
  6220. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6221. EXPECT_EQ(status, res->status) << ctx;
  6222. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6223. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6224. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6225. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6226. };
  6227. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6228. check(403, "bytes=3-5");
  6229. // The offset is far past the representation.
  6230. check(403, "bytes=100000-100200");
  6231. // `first_pos` is still -1 here, and the bounds asserts in
  6232. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6233. check(403, "bytes=-3");
  6234. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6235. // multipart branch would have written one that is empty.
  6236. check(403, "bytes=1-2, 4-5");
  6237. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6238. // covers the whole representation.
  6239. check(200, "bytes=3-5");
  6240. check(200, "bytes=1-2, 4-5");
  6241. }
  6242. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6243. auto res =
  6244. cli_.Get("/streamed-with-range",
  6245. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6246. "92233720368547758079223372036854775807"}});
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6249. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6250. EXPECT_EQ(false, res->has_header("Content-Range"));
  6251. EXPECT_EQ(0U, res->body.size());
  6252. }
  6253. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6254. auto res = cli_.Get(
  6255. "/with-range",
  6256. Headers{{"Range",
  6257. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6258. {"Accept-Encoding", ""}});
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6261. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6262. EXPECT_EQ(true, res->has_header("Content-Range"));
  6263. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6264. EXPECT_EQ(std::string("abcdefg"), res->body);
  6265. }
  6266. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6267. auto res = cli_.Get("/with-range", Headers{
  6268. {"Range", "bytes=0-"},
  6269. {"Accept-Encoding", ""},
  6270. });
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6274. EXPECT_EQ(true, res->has_header("Content-Range"));
  6275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6276. EXPECT_EQ(std::string("abcdefg"), res->body);
  6277. }
  6278. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6279. auto res = cli_.Get("/streamed-with-range",
  6280. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6283. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6284. EXPECT_EQ(false, res->has_header("Content-Range"));
  6285. EXPECT_EQ(267U, res->body.size());
  6286. // Check that both range contents are present
  6287. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6288. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6289. // Check that Content-Range headers are present for both ranges
  6290. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6291. std::string::npos);
  6292. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6293. std::string::npos);
  6294. }
  6295. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6296. Ranges ranges;
  6297. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6298. ranges.emplace_back(0, -1);
  6299. }
  6300. auto res = cli_.Get("/streamed-with-range?error",
  6301. Headers{{make_range_header(ranges)}});
  6302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6303. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6304. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6305. EXPECT_EQ(false, res->has_header("Content-Range"));
  6306. EXPECT_EQ(0U, res->body.size());
  6307. }
  6308. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6309. auto res = cli_.Get("/streamed-with-range",
  6310. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6313. EXPECT_EQ(5U, res->body.size());
  6314. // Check that overlapping ranges are coalesced into a single range
  6315. EXPECT_EQ("bcdef", res->body);
  6316. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6317. // Should be single range, not multipart
  6318. EXPECT_TRUE(res->has_header("Content-Range"));
  6319. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6320. }
  6321. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6322. auto res = cli_.Get("/streamed-with-range",
  6323. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6326. EXPECT_EQ(268U, res->body.size());
  6327. // Check that both range contents are present
  6328. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6329. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6330. // Check that Content-Range headers are present for both ranges
  6331. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6332. std::string::npos);
  6333. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6334. std::string::npos);
  6335. }
  6336. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6337. auto res = cli_.Get("/streamed-with-range",
  6338. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6341. EXPECT_EQ(269U, res->body.size());
  6342. // Check that both duplicate range contents are present
  6343. size_t first_abc = res->body.find("abc\r\n");
  6344. EXPECT_TRUE(first_abc != std::string::npos);
  6345. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6346. EXPECT_TRUE(second_abc != std::string::npos);
  6347. // Check that Content-Range headers are present for both ranges
  6348. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6349. EXPECT_TRUE(first_range != std::string::npos);
  6350. size_t second_range =
  6351. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6352. EXPECT_TRUE(second_range != std::string::npos);
  6353. }
  6354. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6355. auto res =
  6356. cli_.Get("/streamed-with-range?error",
  6357. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6360. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6361. EXPECT_EQ(false, res->has_header("Content-Range"));
  6362. EXPECT_EQ(0U, res->body.size());
  6363. }
  6364. TEST_F(ServerTest, GetStreamedEndless) {
  6365. uint64_t offset = 0;
  6366. auto res = cli_.Get("/streamed-cancel",
  6367. [&](const char * /*data*/, uint64_t data_length) {
  6368. if (offset < 100) {
  6369. offset += data_length;
  6370. return true;
  6371. }
  6372. return false;
  6373. });
  6374. ASSERT_TRUE(!res);
  6375. EXPECT_EQ(Error::Canceled, res.error());
  6376. }
  6377. TEST_F(ServerTest, ClientStop) {
  6378. std::atomic_size_t count{4};
  6379. std::vector<std::thread> threads;
  6380. for (auto i = count.load(); i != 0; --i) {
  6381. threads.emplace_back([&]() {
  6382. auto res = cli_.Get("/streamed-cancel",
  6383. [&](const char *, uint64_t) { return true; });
  6384. --count;
  6385. ASSERT_TRUE(!res);
  6386. EXPECT_TRUE(res.error() == Error::Canceled ||
  6387. res.error() == Error::Read || res.error() == Error::Write);
  6388. });
  6389. }
  6390. std::this_thread::sleep_for(std::chrono::seconds(2));
  6391. while (count != 0) {
  6392. cli_.stop();
  6393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6394. }
  6395. for (auto &t : threads) {
  6396. t.join();
  6397. }
  6398. }
  6399. TEST_F(ServerTest, GetWithRange1) {
  6400. auto res = cli_.Get("/with-range", Headers{
  6401. make_range_header({{3, 5}}),
  6402. {"Accept-Encoding", ""},
  6403. });
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6406. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6407. EXPECT_EQ(true, res->has_header("Content-Range"));
  6408. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6409. EXPECT_EQ(std::string("def"), res->body);
  6410. }
  6411. TEST_F(ServerTest, GetWithRange2) {
  6412. auto res = cli_.Get("/with-range", Headers{
  6413. make_range_header({{1, -1}}),
  6414. {"Accept-Encoding", ""},
  6415. });
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6418. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6419. EXPECT_EQ(true, res->has_header("Content-Range"));
  6420. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6421. EXPECT_EQ(std::string("bcdefg"), res->body);
  6422. }
  6423. TEST_F(ServerTest, GetWithRange3) {
  6424. auto res = cli_.Get("/with-range", Headers{
  6425. make_range_header({{0, 0}}),
  6426. {"Accept-Encoding", ""},
  6427. });
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6430. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6431. EXPECT_EQ(true, res->has_header("Content-Range"));
  6432. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6433. EXPECT_EQ(std::string("a"), res->body);
  6434. }
  6435. TEST_F(ServerTest, GetWithRange4) {
  6436. auto res = cli_.Get("/with-range", Headers{
  6437. make_range_header({{-1, 2}}),
  6438. {"Accept-Encoding", ""},
  6439. });
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6442. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6443. EXPECT_EQ(true, res->has_header("Content-Range"));
  6444. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6445. EXPECT_EQ(std::string("fg"), res->body);
  6446. }
  6447. TEST_F(ServerTest, GetWithRange5) {
  6448. auto res = cli_.Get("/with-range", Headers{
  6449. make_range_header({{0, 5}}),
  6450. {"Accept-Encoding", ""},
  6451. });
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6454. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6455. EXPECT_EQ(true, res->has_header("Content-Range"));
  6456. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6457. EXPECT_EQ(std::string("abcdef"), res->body);
  6458. }
  6459. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6460. auto res =
  6461. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6464. }
  6465. TEST_F(ServerTest, GetWithRangeMultipart) {
  6466. auto res =
  6467. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6470. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6471. EXPECT_EQ(false, res->has_header("Content-Range"));
  6472. EXPECT_EQ(267U, res->body.size());
  6473. }
  6474. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6475. auto res = cli_.Get("/with-range",
  6476. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6478. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6479. }
  6480. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6481. auto res = cli_.Get("/with-range-customized-response",
  6482. Headers{{make_range_header({{1, 2}})}});
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6485. EXPECT_EQ(true, res->has_header("Content-Length"));
  6486. EXPECT_EQ(false, res->has_header("Content-Range"));
  6487. EXPECT_EQ(JSON_DATA, res->body);
  6488. }
  6489. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6490. auto res = cli_.Get("/with-range-customized-response",
  6491. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6494. EXPECT_EQ(true, res->has_header("Content-Length"));
  6495. EXPECT_EQ(false, res->has_header("Content-Range"));
  6496. EXPECT_EQ(JSON_DATA, res->body);
  6497. }
  6498. TEST_F(ServerTest, Issue1772) {
  6499. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6502. }
  6503. TEST_F(ServerTest, Issue609) {
  6504. auto res = cli_.Delete("/issue609");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::OK_200, res->status);
  6507. EXPECT_EQ(std::string("ok"), res->body);
  6508. }
  6509. TEST_F(ServerTest, GetStreamedChunked) {
  6510. auto res = cli_.Get("/streamed-chunked");
  6511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6512. EXPECT_EQ(StatusCode::OK_200, res->status);
  6513. EXPECT_EQ(std::string("123456789"), res->body);
  6514. }
  6515. TEST_F(ServerTest, GetStreamedChunked2) {
  6516. auto res = cli_.Get("/streamed-chunked2");
  6517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6518. EXPECT_EQ(StatusCode::OK_200, res->status);
  6519. EXPECT_EQ(std::string("123456789"), res->body);
  6520. }
  6521. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6522. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. EXPECT_EQ(StatusCode::OK_200, res->status);
  6525. EXPECT_EQ(std::string("123456789"), res->body);
  6526. EXPECT_TRUE(res->has_header("Trailer"));
  6527. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6528. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6529. // Trailers are now stored separately from headers (security fix)
  6530. EXPECT_EQ(2U, res->trailers.size());
  6531. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6532. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6533. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6534. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6535. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6536. // Verify trailers are NOT in headers (security verification)
  6537. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6538. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6539. }
  6540. TEST_F(ServerTest, LargeChunkedPost) {
  6541. Request req;
  6542. req.method = "POST";
  6543. req.path = "/large-chunked";
  6544. std::string host_and_port;
  6545. host_and_port += HOST;
  6546. host_and_port += ":";
  6547. host_and_port += std::to_string(PORT);
  6548. req.headers.emplace("Host", host_and_port.c_str());
  6549. req.headers.emplace("Accept", "*/*");
  6550. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6551. req.headers.emplace("Content-Type", "text/plain");
  6552. req.headers.emplace("Content-Length", "0");
  6553. req.headers.emplace("Transfer-Encoding", "chunked");
  6554. std::string long_string(30 * 1024u, 'a');
  6555. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6556. // Attempt to make a large enough post to exceed OS buffers, to test that
  6557. // the server handles short reads if the full chunk data isn't available.
  6558. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6559. auto res = std::make_shared<Response>();
  6560. auto error = Error::Success;
  6561. auto ret = cli_.send(req, *res, error);
  6562. ASSERT_TRUE(ret);
  6563. EXPECT_EQ(StatusCode::OK_200, res->status);
  6564. }
  6565. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6566. auto res = cli_.Get("/remote_addr");
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6570. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6571. }
  6572. TEST_F(ServerTest, GetMethodLocalAddr) {
  6573. auto res = cli_.Get("/local_addr");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::OK_200, res->status);
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6578. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6579. }
  6580. TEST_F(ServerTest, HTTPResponseSplitting) {
  6581. auto res = cli_.Get("/http_response_splitting");
  6582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. }
  6585. TEST_F(ServerTest, SlowRequest) {
  6586. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6587. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6588. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6589. }
  6590. #if 0
  6591. TEST_F(ServerTest, SlowPost) {
  6592. char buffer[64 * 1024];
  6593. memset(buffer, 0x42, sizeof(buffer));
  6594. auto res = cli_.Post(
  6595. "/slowpost", 64 * 1024 * 1024,
  6596. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6597. auto ret = sink.write(buffer, sizeof(buffer));
  6598. EXPECT_TRUE(ret);
  6599. return true;
  6600. },
  6601. "text/plain");
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::OK_200, res->status);
  6604. }
  6605. TEST_F(ServerTest, SlowPostFail) {
  6606. char buffer[64 * 1024];
  6607. memset(buffer, 0x42, sizeof(buffer));
  6608. cli_.set_write_timeout(std::chrono::seconds(0));
  6609. auto res = cli_.Post(
  6610. "/slowpost", 64 * 1024 * 1024,
  6611. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6612. sink.write(buffer, sizeof(buffer));
  6613. return true;
  6614. },
  6615. "text/plain");
  6616. ASSERT_TRUE(!res);
  6617. EXPECT_EQ(Error::Write, res.error());
  6618. }
  6619. #endif
  6620. TEST_F(ServerTest, Put) {
  6621. auto res = cli_.Put("/put", "PUT", "text/plain");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. EXPECT_EQ(StatusCode::OK_200, res->status);
  6624. EXPECT_EQ("PUT", res->body);
  6625. }
  6626. TEST_F(ServerTest, PutWithContentProvider) {
  6627. auto res = cli_.Put(
  6628. "/put", 3,
  6629. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6630. sink.os << "PUT";
  6631. return true;
  6632. },
  6633. "text/plain");
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::OK_200, res->status);
  6636. EXPECT_EQ("PUT", res->body);
  6637. }
  6638. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6639. auto res = cli_.Post(
  6640. "/post", 42,
  6641. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6642. return false;
  6643. },
  6644. "text/plain");
  6645. ASSERT_TRUE(!res);
  6646. EXPECT_EQ(Error::Canceled, res.error());
  6647. }
  6648. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6649. auto res = cli_.Put(
  6650. "/put",
  6651. [](size_t /*offset*/, DataSink &sink) {
  6652. sink.os << "PUT";
  6653. sink.done();
  6654. return true;
  6655. },
  6656. "text/plain");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("PUT", res->body);
  6660. }
  6661. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6662. auto res = cli_.Post(
  6663. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6664. "text/plain");
  6665. ASSERT_TRUE(!res);
  6666. EXPECT_EQ(Error::Canceled, res.error());
  6667. }
  6668. TEST_F(ServerTest, PostLoopBack) {
  6669. std::string body;
  6670. auto res = cli_.Post(
  6671. "/post-loopback", 9,
  6672. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6673. EXPECT_EQ(9u, length);
  6674. sink.write("123", 3);
  6675. sink.write("456", 3);
  6676. sink.write("789", 3);
  6677. return true;
  6678. },
  6679. "text/plain",
  6680. [&body](const char *data, size_t data_length) {
  6681. body.append(data, data_length);
  6682. return true;
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::OK_200, res->status);
  6686. EXPECT_EQ("123456789", body);
  6687. }
  6688. TEST_F(ServerTest, PutLoopBack) {
  6689. std::string body;
  6690. auto res = cli_.Put(
  6691. "/put-loopback", 9,
  6692. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6693. EXPECT_EQ(9u, length);
  6694. sink.write("123", 3);
  6695. sink.write("456", 3);
  6696. sink.write("789", 3);
  6697. return true;
  6698. },
  6699. "text/plain",
  6700. [&body](const char *data, size_t data_length) {
  6701. body.append(data, data_length);
  6702. return true;
  6703. });
  6704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6705. EXPECT_EQ(StatusCode::OK_200, res->status);
  6706. EXPECT_EQ("123456789", body);
  6707. }
  6708. TEST_F(ServerTest, PatchLoopBack) {
  6709. std::string body;
  6710. auto res = cli_.Patch(
  6711. "/patch-loopback", 9,
  6712. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6713. EXPECT_EQ(9u, length);
  6714. sink.write("123", 3);
  6715. sink.write("456", 3);
  6716. sink.write("789", 3);
  6717. return true;
  6718. },
  6719. "text/plain",
  6720. [&body](const char *data, size_t data_length) {
  6721. body.append(data, data_length);
  6722. return true;
  6723. });
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. EXPECT_EQ(StatusCode::OK_200, res->status);
  6726. EXPECT_EQ("123456789", body);
  6727. }
  6728. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6729. std::string body;
  6730. auto res = cli_.Post(
  6731. "/post-loopback",
  6732. [](size_t /*offset*/, DataSink &sink) {
  6733. sink.write("123", 3);
  6734. sink.write("456", 3);
  6735. sink.write("789", 3);
  6736. sink.done();
  6737. return true;
  6738. },
  6739. "text/plain",
  6740. [&body](const char *data, size_t data_length) {
  6741. body.append(data, data_length);
  6742. return true;
  6743. });
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("123456789", body);
  6747. }
  6748. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6749. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6750. cli_.set_compress(true);
  6751. auto res = cli_.Put(
  6752. "/put", 3,
  6753. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6754. sink.os << "PUT";
  6755. return true;
  6756. },
  6757. "text/plain");
  6758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6759. EXPECT_EQ(StatusCode::OK_200, res->status);
  6760. EXPECT_EQ("PUT", res->body);
  6761. }
  6762. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6763. cli_.set_compress(true);
  6764. auto res = cli_.Post(
  6765. "/post", 42,
  6766. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6767. return false;
  6768. },
  6769. "text/plain");
  6770. ASSERT_TRUE(!res);
  6771. EXPECT_EQ(Error::Canceled, res.error());
  6772. }
  6773. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6774. cli_.set_compress(true);
  6775. auto res = cli_.Put(
  6776. "/put",
  6777. [](size_t /*offset*/, DataSink &sink) {
  6778. sink.os << "PUT";
  6779. sink.done();
  6780. return true;
  6781. },
  6782. "text/plain");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("PUT", res->body);
  6786. }
  6787. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6788. cli_.set_compress(true);
  6789. auto res = cli_.Post(
  6790. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6791. "text/plain");
  6792. ASSERT_TRUE(!res);
  6793. EXPECT_EQ(Error::Canceled, res.error());
  6794. }
  6795. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6796. cli_.set_compress(true);
  6797. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. EXPECT_EQ(StatusCode::OK_200, res->status);
  6800. EXPECT_EQ(LARGE_DATA, res->body);
  6801. }
  6802. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6803. #ifdef CPPHTTPLIB_SSL_ENABLED
  6804. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6805. Client cli(s.c_str());
  6806. cli.enable_server_certificate_verification(false);
  6807. #else
  6808. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6809. Client cli(s.c_str());
  6810. #endif
  6811. cli.set_compress(true);
  6812. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ(LARGE_DATA, res->body);
  6816. // The compressed size should be less than a 10th of the original. May vary
  6817. // depending on the zlib library.
  6818. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6819. static_cast<uint64_t>(10 * 1024 * 1024));
  6820. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6821. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6822. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6823. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6824. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6825. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6826. #endif
  6827. }
  6828. TEST_F(ServerTest, PutContentWithDeflate) {
  6829. cli_.set_compress(false);
  6830. Headers headers;
  6831. headers.emplace("Content-Encoding", "deflate");
  6832. // PUT in deflate format:
  6833. auto res = cli_.Put("/put", headers,
  6834. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6836. EXPECT_EQ(StatusCode::OK_200, res->status);
  6837. EXPECT_EQ("PUT", res->body);
  6838. }
  6839. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6840. Headers headers;
  6841. headers.emplace("Accept-Encoding", "gzip, deflate");
  6842. auto res = cli_.Get("/streamed-chunked", headers);
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ(std::string("123456789"), res->body);
  6846. }
  6847. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6848. Headers headers;
  6849. headers.emplace("Accept-Encoding", "gzip, deflate");
  6850. auto res = cli_.Get("/streamed-chunked2", headers);
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ(StatusCode::OK_200, res->status);
  6853. EXPECT_EQ(std::string("123456789"), res->body);
  6854. }
  6855. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6856. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6858. EXPECT_EQ(StatusCode::OK_200, res->status);
  6859. }
  6860. TEST(GzipDecompressor, ChunkedDecompression) {
  6861. std::string data;
  6862. for (size_t i = 0; i < 32 * 1024; ++i) {
  6863. data.push_back(static_cast<char>('a' + i % 26));
  6864. }
  6865. std::string compressed_data;
  6866. {
  6867. httplib::detail::gzip_compressor compressor;
  6868. bool result = compressor.compress(
  6869. data.data(), data.size(),
  6870. /*last=*/true,
  6871. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6872. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6873. compressed_data_size);
  6874. return true;
  6875. });
  6876. ASSERT_TRUE(result);
  6877. }
  6878. std::string decompressed_data;
  6879. {
  6880. httplib::detail::gzip_decompressor decompressor;
  6881. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6882. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6883. size_t chunk_size = 130;
  6884. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6885. chunk_begin += chunk_size) {
  6886. size_t current_chunk_size =
  6887. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6888. bool result = decompressor.decompress(
  6889. compressed_data.data() + chunk_begin, current_chunk_size,
  6890. [&](const char *decompressed_data_chunk,
  6891. size_t decompressed_data_chunk_size) {
  6892. decompressed_data.insert(decompressed_data.size(),
  6893. decompressed_data_chunk,
  6894. decompressed_data_chunk_size);
  6895. return true;
  6896. });
  6897. ASSERT_TRUE(result);
  6898. }
  6899. }
  6900. ASSERT_EQ(data, decompressed_data);
  6901. }
  6902. TEST(GzipDecompressor, DeflateDecompression) {
  6903. std::string original_text = "Raw deflate without gzip";
  6904. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6905. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6906. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6907. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6908. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6909. std::string decompressed_data;
  6910. {
  6911. httplib::detail::gzip_decompressor decompressor;
  6912. bool result = decompressor.decompress(
  6913. compressed_data.data(), compressed_data.size(),
  6914. [&](const char *decompressed_data_chunk,
  6915. size_t decompressed_data_chunk_size) {
  6916. decompressed_data.insert(decompressed_data.size(),
  6917. decompressed_data_chunk,
  6918. decompressed_data_chunk_size);
  6919. return true;
  6920. });
  6921. ASSERT_TRUE(result);
  6922. }
  6923. ASSERT_EQ(original_text, decompressed_data);
  6924. }
  6925. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6926. std::string original_text = "Raw deflate without gzip";
  6927. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6928. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6929. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6930. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6931. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6932. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6933. std::string decompressed_data;
  6934. {
  6935. httplib::detail::gzip_decompressor decompressor;
  6936. bool result = decompressor.decompress(
  6937. compressed_data.data(), compressed_data.size(),
  6938. [&](const char *decompressed_data_chunk,
  6939. size_t decompressed_data_chunk_size) {
  6940. decompressed_data.insert(decompressed_data.size(),
  6941. decompressed_data_chunk,
  6942. decompressed_data_chunk_size);
  6943. return true;
  6944. });
  6945. ASSERT_TRUE(result);
  6946. }
  6947. ASSERT_EQ(original_text, decompressed_data);
  6948. }
  6949. #endif
  6950. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6951. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6952. Headers headers;
  6953. headers.emplace("Accept-Encoding", "br");
  6954. auto res = cli_.Get("/streamed-chunked", headers);
  6955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6956. EXPECT_EQ(StatusCode::OK_200, res->status);
  6957. EXPECT_EQ(std::string("123456789"), res->body);
  6958. }
  6959. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6960. Headers headers;
  6961. headers.emplace("Accept-Encoding", "br");
  6962. auto res = cli_.Get("/streamed-chunked2", headers);
  6963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6964. EXPECT_EQ(StatusCode::OK_200, res->status);
  6965. EXPECT_EQ(std::string("123456789"), res->body);
  6966. }
  6967. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6968. cli_.set_compress(true);
  6969. auto res = cli_.Put(
  6970. "/put", 3,
  6971. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6972. sink.os << "PUT";
  6973. return true;
  6974. },
  6975. "text/plain");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::OK_200, res->status);
  6978. EXPECT_EQ("PUT", res->body);
  6979. }
  6980. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6981. cli_.set_compress(true);
  6982. auto res = cli_.Put(
  6983. "/put",
  6984. [](size_t /*offset*/, DataSink &sink) {
  6985. sink.os << "PUT";
  6986. sink.done();
  6987. return true;
  6988. },
  6989. "text/plain");
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("PUT", res->body);
  6993. }
  6994. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6995. cli_.set_compress(true);
  6996. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ(LARGE_DATA, res->body);
  7000. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7001. }
  7002. #endif
  7003. TEST_F(ServerTest, Patch) {
  7004. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::OK_200, res->status);
  7007. EXPECT_EQ("PATCH", res->body);
  7008. }
  7009. TEST_F(ServerTest, Delete) {
  7010. auto res = cli_.Delete("/delete");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. EXPECT_EQ(StatusCode::OK_200, res->status);
  7013. EXPECT_EQ("DELETE", res->body);
  7014. }
  7015. TEST_F(ServerTest, DeleteContentReceiver) {
  7016. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("content", res->body);
  7020. }
  7021. TEST_F(ServerTest, Options) {
  7022. auto res = cli_.Options("*");
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. EXPECT_EQ(StatusCode::OK_200, res->status);
  7025. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7026. EXPECT_TRUE(res->body.empty());
  7027. }
  7028. TEST_F(ServerTest, URL) {
  7029. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7031. EXPECT_EQ(StatusCode::OK_200, res->status);
  7032. }
  7033. TEST_F(ServerTest, ArrayParam) {
  7034. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7036. EXPECT_EQ(StatusCode::OK_200, res->status);
  7037. }
  7038. TEST_F(ServerTest, ArrayParamValues) {
  7039. auto res =
  7040. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7042. EXPECT_EQ(StatusCode::OK_200, res->status);
  7043. }
  7044. TEST_F(ServerTest, NoMultipleHeaders) {
  7045. Headers headers = {{"Content-Length", "5"}};
  7046. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7047. "text/plain");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. EXPECT_EQ(StatusCode::OK_200, res->status);
  7050. }
  7051. TEST_F(ServerTest, PostContentReceiver) {
  7052. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. ASSERT_EQ(StatusCode::OK_200, res->status);
  7055. ASSERT_EQ("content", res->body);
  7056. }
  7057. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7058. UploadFormDataItems items = {
  7059. {"text1", "text default", "", ""},
  7060. {"text2", "aωb", "", ""},
  7061. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7062. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7063. {"file3", "", "", "application/octet-stream"},
  7064. };
  7065. auto res = cli_.Post("/content_receiver", items);
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::OK_200, res->status);
  7068. }
  7069. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7070. UploadFormDataItems items = {
  7071. {"text1", "text default", "", ""},
  7072. {"text2", "aωb", "", ""},
  7073. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7074. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7075. {"file3", "", "", "application/octet-stream"},
  7076. };
  7077. auto boundary = std::string("+++++");
  7078. std::string body;
  7079. for (const auto &item : items) {
  7080. body += "--" + boundary + "\r\n";
  7081. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7082. if (!item.filename.empty()) {
  7083. body += "; filename=\"" + item.filename + "\"";
  7084. }
  7085. body += "\r\n";
  7086. if (!item.content_type.empty()) {
  7087. body += "Content-Type: " + item.content_type + "\r\n";
  7088. }
  7089. body += "\r\n";
  7090. body += item.content + "\r\n";
  7091. }
  7092. body += "--" + boundary + "--\r\n";
  7093. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7094. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. }
  7098. TEST(MultipartFormDataTest, FieldEscaping) {
  7099. Server svr;
  7100. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7101. const ContentReader &content_reader) {
  7102. ASSERT_TRUE(req.is_multipart_form_data());
  7103. std::vector<FormData> received;
  7104. content_reader(
  7105. [&](const FormData &file) {
  7106. received.push_back(file);
  7107. return true;
  7108. },
  7109. [&](const char *data, size_t data_length) {
  7110. received.back().content.append(data, data_length);
  7111. return true;
  7112. });
  7113. // '"', CR and LF in names and filenames are escaped following the
  7114. // WHATWG HTML standard, so each part still parses as a single part
  7115. // with no injected headers. Content types get CR/LF escaped too,
  7116. // while '"' (legal there, e.g. quoted charset) is preserved.
  7117. ASSERT_EQ(4U, received.size());
  7118. EXPECT_EQ("na%22me", received[0].name);
  7119. EXPECT_EQ("quoted name", received[0].content);
  7120. EXPECT_EQ("file", received[1].name);
  7121. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7122. received[1].filename);
  7123. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7124. EXPECT_EQ("injected", received[1].content);
  7125. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7126. EXPECT_EQ("my%22file.txt", received[2].filename);
  7127. EXPECT_EQ("cr lf name", received[2].content);
  7128. EXPECT_EQ("typed", received[3].name);
  7129. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7130. received[3].content_type);
  7131. EXPECT_EQ("typed content", received[3].content);
  7132. });
  7133. auto port = svr.bind_to_any_port("localhost");
  7134. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7135. auto se = detail::scope_exit([&] {
  7136. svr.stop();
  7137. t.join();
  7138. ASSERT_FALSE(svr.is_running());
  7139. });
  7140. svr.wait_until_ready();
  7141. Client cli("localhost", port);
  7142. UploadFormDataItems items = {
  7143. {"na\"me", "quoted name", "", ""},
  7144. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7145. "application/octet-stream"},
  7146. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7147. {"typed", "typed content", "",
  7148. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7149. };
  7150. auto res = cli.Post("/post", items);
  7151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7152. EXPECT_EQ(StatusCode::OK_200, res->status);
  7153. }
  7154. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7155. const UploadFormDataItems items = {
  7156. {"name1", "Content 1", "", ""},
  7157. {"name2", "Content 2", "file2.txt", "text/plain"},
  7158. };
  7159. Server svr;
  7160. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7161. const ContentReader &content_reader) {
  7162. ASSERT_TRUE(req.is_multipart_form_data());
  7163. std::vector<FormData> received;
  7164. content_reader(
  7165. [&](const FormData &file) {
  7166. received.push_back(file);
  7167. return true;
  7168. },
  7169. [&](const char *data, size_t data_length) {
  7170. received.back().content.append(data, data_length);
  7171. return true;
  7172. });
  7173. ASSERT_EQ(2U, received.size());
  7174. EXPECT_EQ("name1", received[0].name);
  7175. EXPECT_EQ("Content 1", received[0].content);
  7176. EXPECT_EQ("name2", received[1].name);
  7177. EXPECT_EQ("Content 2", received[1].content);
  7178. EXPECT_EQ("file2.txt", received[1].filename);
  7179. EXPECT_EQ("text/plain", received[1].content_type);
  7180. });
  7181. auto port = svr.bind_to_any_port("localhost");
  7182. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7183. auto se = detail::scope_exit([&] {
  7184. svr.stop();
  7185. t.join();
  7186. ASSERT_FALSE(svr.is_running());
  7187. });
  7188. svr.wait_until_ready();
  7189. Client cli("localhost", port);
  7190. // Whole-body serialization with a generated boundary
  7191. {
  7192. MultipartFormDataWriter writer;
  7193. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7194. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7195. writer.content_type());
  7196. auto body = writer.serialize(items);
  7197. EXPECT_EQ(body.size(), writer.content_length(items));
  7198. auto res = cli.Post("/post", body, writer.content_type());
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. }
  7202. // Per-part framing with a custom boundary via a content provider
  7203. {
  7204. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7205. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7206. MultipartFormDataWriter writer("custom-boundary_123");
  7207. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7208. std::string body;
  7209. for (const auto &item : items) {
  7210. body += writer.item_begin(item);
  7211. body += item.content;
  7212. body += MultipartFormDataWriter::item_end();
  7213. }
  7214. body += writer.finish();
  7215. EXPECT_EQ(body.size(), writer.content_length(items));
  7216. auto res = cli.Post(
  7217. "/post", body.size(),
  7218. [&](size_t offset, size_t length, DataSink &sink) {
  7219. sink.write(body.data() + offset, length);
  7220. return true;
  7221. },
  7222. writer.content_type());
  7223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. }
  7226. }
  7227. TEST_F(ServerTest, PostContentReceiverGzip) {
  7228. cli_.set_compress(true);
  7229. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7231. ASSERT_EQ(StatusCode::OK_200, res->status);
  7232. ASSERT_EQ("content", res->body);
  7233. }
  7234. TEST_F(ServerTest, PutContentReceiver) {
  7235. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. ASSERT_EQ(StatusCode::OK_200, res->status);
  7238. ASSERT_EQ("content", res->body);
  7239. }
  7240. TEST_F(ServerTest, PatchContentReceiver) {
  7241. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7243. ASSERT_EQ(StatusCode::OK_200, res->status);
  7244. ASSERT_EQ("content", res->body);
  7245. }
  7246. template <typename ClientType>
  7247. void TestWithHeadersAndContentReceiver(
  7248. ClientType &cli,
  7249. std::function<Result(ClientType &, const std::string &, const Headers &,
  7250. const std::string &, const std::string &,
  7251. ContentReceiver, DownloadProgress)>
  7252. request_func) {
  7253. Headers headers;
  7254. headers.emplace("X-Custom-Header", "test-value");
  7255. std::string received_body;
  7256. auto res = request_func(
  7257. cli, "/content_receiver", headers, "content", "application/json",
  7258. [&](const char *data, size_t data_length) {
  7259. received_body.append(data, data_length);
  7260. return true;
  7261. },
  7262. nullptr);
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("content", received_body);
  7266. }
  7267. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7268. #ifdef CPPHTTPLIB_SSL_ENABLED
  7269. using ClientT = SSLClient;
  7270. #else
  7271. using ClientT = Client;
  7272. #endif
  7273. TestWithHeadersAndContentReceiver<ClientT>(
  7274. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7275. const std::string &body, const std::string &content_type,
  7276. ContentReceiver receiver, DownloadProgress progress) {
  7277. return cli.Post(path, headers, body, content_type, receiver, progress);
  7278. });
  7279. }
  7280. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7281. #ifdef CPPHTTPLIB_SSL_ENABLED
  7282. using ClientT = SSLClient;
  7283. #else
  7284. using ClientT = Client;
  7285. #endif
  7286. TestWithHeadersAndContentReceiver<ClientT>(
  7287. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7288. const std::string &body, const std::string &content_type,
  7289. ContentReceiver receiver, DownloadProgress progress) {
  7290. return cli.Put(path, headers, body, content_type, receiver, progress);
  7291. });
  7292. }
  7293. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7294. #ifdef CPPHTTPLIB_SSL_ENABLED
  7295. using ClientT = SSLClient;
  7296. #else
  7297. using ClientT = Client;
  7298. #endif
  7299. TestWithHeadersAndContentReceiver<ClientT>(
  7300. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7301. const std::string &body, const std::string &content_type,
  7302. ContentReceiver receiver, DownloadProgress progress) {
  7303. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7304. });
  7305. }
  7306. template <typename ClientType>
  7307. void TestWithHeadersAndContentReceiverWithProgress(
  7308. ClientType &cli,
  7309. std::function<Result(ClientType &, const std::string &, const Headers &,
  7310. const std::string &, const std::string &,
  7311. ContentReceiver, DownloadProgress)>
  7312. request_func) {
  7313. Headers headers;
  7314. headers.emplace("X-Test-Header", "progress-test");
  7315. std::string received_body;
  7316. auto progress_called = false;
  7317. auto res = request_func(
  7318. cli, "/content_receiver", headers, "content", "text/plain",
  7319. [&](const char *data, size_t data_length) {
  7320. received_body.append(data, data_length);
  7321. return true;
  7322. },
  7323. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7324. progress_called = true;
  7325. return true;
  7326. });
  7327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7328. EXPECT_EQ(StatusCode::OK_200, res->status);
  7329. EXPECT_EQ("content", received_body);
  7330. EXPECT_TRUE(progress_called);
  7331. }
  7332. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7333. #ifdef CPPHTTPLIB_SSL_ENABLED
  7334. using ClientT = SSLClient;
  7335. #else
  7336. using ClientT = Client;
  7337. #endif
  7338. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7339. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7340. const std::string &body, const std::string &content_type,
  7341. ContentReceiver receiver, DownloadProgress progress) {
  7342. return cli.Post(path, headers, body, content_type, receiver, progress);
  7343. });
  7344. }
  7345. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7346. #ifdef CPPHTTPLIB_SSL_ENABLED
  7347. using ClientT = SSLClient;
  7348. #else
  7349. using ClientT = Client;
  7350. #endif
  7351. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7352. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7353. const std::string &body, const std::string &content_type,
  7354. ContentReceiver receiver, DownloadProgress progress) {
  7355. return cli.Put(path, headers, body, content_type, receiver, progress);
  7356. });
  7357. }
  7358. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7359. #ifdef CPPHTTPLIB_SSL_ENABLED
  7360. using ClientT = SSLClient;
  7361. #else
  7362. using ClientT = Client;
  7363. #endif
  7364. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7365. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7366. const std::string &body, const std::string &content_type,
  7367. ContentReceiver receiver, DownloadProgress progress) {
  7368. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7369. });
  7370. }
  7371. template <typename ClientType>
  7372. void TestWithHeadersAndContentReceiverError(
  7373. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7374. const Headers &, const std::string &,
  7375. const std::string &, ContentReceiver)>
  7376. request_func) {
  7377. Headers headers;
  7378. headers.emplace("X-Error-Test", "true");
  7379. std::string received_body;
  7380. auto receiver_failed = false;
  7381. auto res =
  7382. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7383. [&](const char *data, size_t data_length) {
  7384. received_body.append(data, data_length);
  7385. receiver_failed = true;
  7386. return false;
  7387. });
  7388. ASSERT_FALSE(res);
  7389. EXPECT_TRUE(receiver_failed);
  7390. }
  7391. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7392. #ifdef CPPHTTPLIB_SSL_ENABLED
  7393. using ClientT = SSLClient;
  7394. #else
  7395. using ClientT = Client;
  7396. #endif
  7397. TestWithHeadersAndContentReceiverError<ClientT>(
  7398. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7399. const std::string &body, const std::string &content_type,
  7400. ContentReceiver receiver) {
  7401. return cli.Post(path, headers, body, content_type, receiver);
  7402. });
  7403. }
  7404. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7405. #ifdef CPPHTTPLIB_SSL_ENABLED
  7406. using ClientT = SSLClient;
  7407. #else
  7408. using ClientT = Client;
  7409. #endif
  7410. TestWithHeadersAndContentReceiverError<ClientT>(
  7411. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7412. const std::string &body, const std::string &content_type,
  7413. ContentReceiver receiver) {
  7414. return cli.Put(path, headers, body, content_type, receiver);
  7415. });
  7416. }
  7417. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7418. #ifdef CPPHTTPLIB_SSL_ENABLED
  7419. using ClientT = SSLClient;
  7420. #else
  7421. using ClientT = Client;
  7422. #endif
  7423. TestWithHeadersAndContentReceiverError<ClientT>(
  7424. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7425. const std::string &body, const std::string &content_type,
  7426. ContentReceiver receiver) {
  7427. return cli.Patch(path, headers, body, content_type, receiver);
  7428. });
  7429. }
  7430. TEST_F(ServerTest, PostQueryStringAndBody) {
  7431. auto res =
  7432. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. ASSERT_EQ(StatusCode::OK_200, res->status);
  7435. }
  7436. TEST_F(ServerTest, HTTP2Magic) {
  7437. Request req;
  7438. req.method = "PRI";
  7439. req.path = "*";
  7440. req.body = "SM";
  7441. auto res = std::make_shared<Response>();
  7442. auto error = Error::Success;
  7443. auto ret = cli_.send(req, *res, error);
  7444. ASSERT_TRUE(ret);
  7445. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7446. }
  7447. TEST_F(ServerTest, KeepAlive) {
  7448. auto res = cli_.Get("/hi");
  7449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7452. EXPECT_EQ("Hello World!", res->body);
  7453. res = cli_.Get("/hi");
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::OK_200, res->status);
  7456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7457. EXPECT_EQ("Hello World!", res->body);
  7458. res = cli_.Get("/hi");
  7459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7460. EXPECT_EQ(StatusCode::OK_200, res->status);
  7461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7462. EXPECT_EQ("Hello World!", res->body);
  7463. res = cli_.Get("/not-exist");
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7466. res = cli_.Post("/empty", "", "text/plain");
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7470. EXPECT_EQ("empty", res->body);
  7471. EXPECT_EQ("close", res->get_header_value("Connection"));
  7472. res = cli_.Post(
  7473. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7474. "text/plain");
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7478. EXPECT_EQ("empty", res->body);
  7479. cli_.set_keep_alive(false);
  7480. res = cli_.Get("/last-request");
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::OK_200, res->status);
  7483. EXPECT_EQ("close", res->get_header_value("Connection"));
  7484. }
  7485. TEST_F(ServerTest, TooManyRedirect) {
  7486. cli_.set_follow_location(true);
  7487. auto res = cli_.Get("/redirect/0");
  7488. ASSERT_TRUE(!res);
  7489. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7490. }
  7491. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7492. Request req;
  7493. req.method = "FOOBAR";
  7494. req.path = "/hi";
  7495. cli_.set_keep_alive(true);
  7496. auto res = cli_.send(req);
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7499. EXPECT_EQ("close", res->get_header_value("Connection"));
  7500. EXPECT_FALSE(cli_.is_socket_open());
  7501. }
  7502. TEST_F(ServerTest, CustomRouteReadsBody) {
  7503. const std::string xml =
  7504. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7505. Request req;
  7506. req.method = "PROPFIND";
  7507. req.path = "/dav/dir";
  7508. req.set_header("Depth", "1");
  7509. req.body = xml;
  7510. auto res = cli_.send(req);
  7511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7512. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7513. EXPECT_EQ(xml, res->body);
  7514. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7515. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7516. }
  7517. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7518. Request req;
  7519. req.method = "PROPFIND";
  7520. req.path = "/dav/42";
  7521. auto res = cli_.send(req);
  7522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7523. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7524. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7525. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7526. }
  7527. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7528. Request req;
  7529. req.method = "PROPFIND";
  7530. req.path = "/dav-re/123";
  7531. auto res = cli_.send(req);
  7532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7533. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7534. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7535. }
  7536. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7537. Request req;
  7538. req.method = "MKCOL";
  7539. req.path = "/dav-mkcol";
  7540. auto res = cli_.send(req);
  7541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7542. EXPECT_EQ(StatusCode::Created_201, res->status);
  7543. }
  7544. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7545. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7546. Request req;
  7547. req.method = "REPORT";
  7548. req.path = "/dav-report";
  7549. req.body = xml;
  7550. auto res = cli_.send(req);
  7551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7552. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7553. EXPECT_EQ(xml, res->body);
  7554. }
  7555. // A content reader route must fire even when the request carries no body,
  7556. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7557. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7558. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7559. Request req;
  7560. req.method = "REPORT";
  7561. req.path = "/dav-report";
  7562. auto res = cli_.send(req);
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7565. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7566. }
  7567. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7568. Request req;
  7569. req.method = "PROPFIND";
  7570. req.path = "/not-dav";
  7571. auto res = cli_.send(req);
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7574. }
  7575. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7576. Request req;
  7577. req.method = "UNLOCK";
  7578. req.path = "/dav/dir";
  7579. cli_.set_keep_alive(true);
  7580. auto res = cli_.send(req);
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7583. EXPECT_EQ("close", res->get_header_value("Connection"));
  7584. EXPECT_FALSE(cli_.is_socket_open());
  7585. }
  7586. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7587. // The mount point serves this path, but only for GET and HEAD.
  7588. auto get_res = cli_.Get("/dir/index.html");
  7589. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7590. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7591. Request req;
  7592. req.method = "PROPFIND";
  7593. req.path = "/dir/index.html";
  7594. auto res = cli_.send(req);
  7595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7596. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7597. }
  7598. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7599. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7600. cli_.set_keep_alive(true);
  7601. for (auto i = 0; i < 2; i++) {
  7602. Request req;
  7603. req.method = "PROPFIND";
  7604. req.path = "/dav/dir";
  7605. req.body = xml;
  7606. auto res = cli_.send(req);
  7607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7608. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7609. EXPECT_EQ(xml, res->body);
  7610. EXPECT_TRUE(cli_.is_socket_open());
  7611. }
  7612. // A built-in method must still be served on the same connection.
  7613. cli_.set_keep_alive(false);
  7614. auto res = cli_.Get("/hi");
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::OK_200, res->status);
  7617. EXPECT_EQ("close", res->get_header_value("Connection"));
  7618. }
  7619. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7620. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7621. Request req;
  7622. req.method = "PROPFIND";
  7623. req.path = "/dav/dir";
  7624. req.set_header("Expect", "100-continue");
  7625. req.body = xml;
  7626. auto res = cli_.send(req);
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7629. EXPECT_EQ(xml, res->body);
  7630. }
  7631. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7633. TEST_F(ServerTest, Gzip) {
  7634. Headers headers;
  7635. headers.emplace("Accept-Encoding", "gzip, deflate");
  7636. auto res = cli_.Get("/compress", headers);
  7637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7638. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7640. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7642. "7890123456789012345678901234567890",
  7643. res->body);
  7644. EXPECT_EQ(StatusCode::OK_200, res->status);
  7645. }
  7646. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7647. Headers headers;
  7648. headers.emplace("Accept-Encoding", "gzip, deflate");
  7649. auto res = cli_.Get("/compress-with-charset", headers);
  7650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7651. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7652. EXPECT_EQ("application/json; charset=utf-8",
  7653. res->get_header_value("Content-Type"));
  7654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7655. "7890123456789012345678901234567890",
  7656. res->body);
  7657. EXPECT_EQ(StatusCode::OK_200, res->status);
  7658. }
  7659. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7660. Headers headers;
  7661. headers.emplace("Accept-Encoding", "");
  7662. auto res = cli_.Get("/compress", headers);
  7663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7664. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7665. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7666. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7667. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7668. "7890123456789012345678901234567890",
  7669. res->body);
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. }
  7672. TEST_F(ServerTest, GzipWithContentReceiver) {
  7673. Headers headers;
  7674. headers.emplace("Accept-Encoding", "gzip, deflate");
  7675. std::string body;
  7676. auto res = cli_.Get("/compress", headers,
  7677. [&](const char *data, uint64_t data_length) {
  7678. EXPECT_EQ(100U, data_length);
  7679. body.append(data, data_length);
  7680. return true;
  7681. });
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7684. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7685. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7686. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7687. "7890123456789012345678901234567890",
  7688. body);
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. }
  7691. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7692. Headers headers;
  7693. headers.emplace("Accept-Encoding", "gzip, deflate");
  7694. cli_.set_decompress(false);
  7695. auto res = cli_.Get("/compress", headers);
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7699. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7700. EXPECT_EQ(33U, res->body.size());
  7701. EXPECT_EQ(StatusCode::OK_200, res->status);
  7702. }
  7703. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7704. Headers headers;
  7705. headers.emplace("Accept-Encoding", "");
  7706. std::string body;
  7707. auto res = cli_.Get("/compress", headers,
  7708. [&](const char *data, uint64_t data_length) {
  7709. EXPECT_EQ(100U, data_length);
  7710. body.append(data, data_length);
  7711. return true;
  7712. });
  7713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7714. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7715. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7716. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7717. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7718. "7890123456789012345678901234567890",
  7719. body);
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. }
  7722. TEST_F(ServerTest, NoGzip) {
  7723. Headers headers;
  7724. headers.emplace("Accept-Encoding", "gzip, deflate");
  7725. auto res = cli_.Get("/nocompress", headers);
  7726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7727. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7728. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7729. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7730. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7731. "7890123456789012345678901234567890",
  7732. res->body);
  7733. EXPECT_EQ(StatusCode::OK_200, res->status);
  7734. }
  7735. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7736. Headers headers;
  7737. headers.emplace("Accept-Encoding", "gzip, deflate");
  7738. std::string body;
  7739. auto res = cli_.Get("/nocompress", headers,
  7740. [&](const char *data, uint64_t data_length) {
  7741. EXPECT_EQ(100U, data_length);
  7742. body.append(data, data_length);
  7743. return true;
  7744. });
  7745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7746. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7747. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7748. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7749. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7750. "7890123456789012345678901234567890",
  7751. body);
  7752. EXPECT_EQ(StatusCode::OK_200, res->status);
  7753. }
  7754. TEST_F(ServerTest, MultipartFormDataGzip) {
  7755. UploadFormDataItems items = {
  7756. {"key1", "test", "", ""},
  7757. {"key2", "--abcdefg123", "", ""},
  7758. };
  7759. cli_.set_compress(true);
  7760. auto res = cli_.Post("/compress-multipart", items);
  7761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7762. EXPECT_EQ(StatusCode::OK_200, res->status);
  7763. }
  7764. #endif
  7765. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7766. // Static file compression is opt-in, so these run their own server rather than
  7767. // flipping it on for the shared ServerTest fixture, which would silently
  7768. // rewrite what every other static file test is asserting.
  7769. class StaticFileCompressionTest : public ::testing::Test {
  7770. protected:
  7771. void TearDown() override {
  7772. if (t_.joinable()) {
  7773. svr_.stop();
  7774. t_.join();
  7775. }
  7776. }
  7777. int start(const std::function<void(Server &)> &configure = nullptr) {
  7778. // Serves the same tree as a directory of build-time compressed assets
  7779. // would be served: the mount point names the coding the files are already
  7780. // stored in. Registered before "/" so it is the one that matches.
  7781. svr_.set_mount_point("/pre-encoded", "./www",
  7782. {{"Content-Encoding", "gzip"}});
  7783. svr_.set_mount_point("/", "./www");
  7784. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7785. res.set_file_content("./www/dir/index.html", "text/html");
  7786. });
  7787. svr_.Get("/pre-encoded-file-content",
  7788. [](const Request & /*req*/, Response &res) {
  7789. res.set_header("Content-Encoding", "gzip");
  7790. res.set_file_content("./www/dir/index.html", "text/html");
  7791. });
  7792. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7793. res.set_content_provider(
  7794. 6, "text/plain",
  7795. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7796. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7797. return true;
  7798. });
  7799. });
  7800. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7801. res.set_content_provider(
  7802. 1000, "text/plain",
  7803. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7804. if (offset < 100) {
  7805. std::string data(100, 'A');
  7806. sink.write(data.data(), data.size());
  7807. return true;
  7808. }
  7809. std::this_thread::sleep_for(std::chrono::seconds(2));
  7810. std::string data(900, 'B');
  7811. sink.write(data.data(), data.size());
  7812. return true;
  7813. });
  7814. });
  7815. if (configure) { configure(svr_); }
  7816. auto port = svr_.bind_to_any_port(HOST);
  7817. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7818. svr_.wait_until_ready();
  7819. return port;
  7820. }
  7821. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7822. // Every file under ./www except 1MB.txt is smaller than the default
  7823. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7824. // it out of the way.
  7825. static void enable_without_floor(Server &svr) {
  7826. svr.set_static_file_compression(true);
  7827. svr.set_static_file_compression_min_length(0);
  7828. }
  7829. Server svr_;
  7830. std::thread t_;
  7831. };
  7832. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7833. auto port = start();
  7834. Client cli(HOST, port);
  7835. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::OK_200, res->status);
  7838. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7839. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7840. EXPECT_EQ(1048576U, res->body.size());
  7841. }
  7842. TEST_F(StaticFileCompressionTest, MountPoint) {
  7843. auto port = start(enable);
  7844. Client cli(HOST, port);
  7845. cli.set_decompress(false);
  7846. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7850. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7851. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7852. // The response stays self-delimiting: a length, not a chunked body.
  7853. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7854. EXPECT_EQ(std::to_string(res->body.size()),
  7855. res->get_header_value("Content-Length"));
  7856. EXPECT_LT(res->body.size(), 1048576U);
  7857. EXPECT_FALSE(res->body.empty());
  7858. }
  7859. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7860. auto port = start(enable);
  7861. Client cli(HOST, port);
  7862. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7866. EXPECT_EQ(1048576U, res->body.size());
  7867. }
  7868. TEST_F(StaticFileCompressionTest, FileContent) {
  7869. auto port = start(enable_without_floor);
  7870. Client cli(HOST, port);
  7871. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7875. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7876. EXPECT_EQ(104U, res->body.size());
  7877. }
  7878. // A handler that serves an already-encoded file names the coding itself. The
  7879. // file-backed path decided its coding from Accept-Encoding and the content
  7880. // type alone, so it compressed the stored bytes a second time and appended a
  7881. // second Content-Encoding field line.
  7882. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7883. auto port = start(enable_without_floor);
  7884. Client cli(HOST, port);
  7885. cli.set_decompress(false);
  7886. auto res = cli.Get("/pre-encoded-file-content",
  7887. Headers{{"Accept-Encoding", "gzip"}});
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7891. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7892. // Vary belongs to a coding the server chose, and it chose none here.
  7893. EXPECT_FALSE(res->has_header("Vary"));
  7894. // The file travels exactly as it is stored on disk.
  7895. EXPECT_EQ(104U, res->body.size());
  7896. }
  7897. // The 1MB file clears the default floor, so this one runs the configuration a
  7898. // deployment would actually have.
  7899. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7900. auto port = start(enable);
  7901. Client cli(HOST, port);
  7902. cli.set_decompress(false);
  7903. auto res =
  7904. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7906. EXPECT_EQ(StatusCode::OK_200, res->status);
  7907. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7908. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7909. EXPECT_FALSE(res->has_header("Vary"));
  7910. EXPECT_EQ(1048576U, res->body.size());
  7911. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7912. }
  7913. TEST_F(StaticFileCompressionTest, Head) {
  7914. auto port = start(enable);
  7915. Client cli(HOST, port);
  7916. cli.set_decompress(false);
  7917. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7918. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7919. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7923. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7924. // HEAD still reports the size a GET would return.
  7925. EXPECT_EQ(get->get_header_value("Content-Length"),
  7926. res->get_header_value("Content-Length"));
  7927. EXPECT_TRUE(res->body.empty());
  7928. }
  7929. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7930. auto port = start(enable);
  7931. Client cli(HOST, port);
  7932. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7933. {"Accept-Encoding", "gzip"}});
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7936. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7937. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7938. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7939. EXPECT_EQ("cd", res->body);
  7940. }
  7941. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7942. auto port = start(enable);
  7943. Client cli(HOST, port);
  7944. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7946. EXPECT_EQ(StatusCode::OK_200, res->status);
  7947. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7948. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7949. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7950. }
  7951. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7952. auto port = start(enable);
  7953. Client cli(HOST, port);
  7954. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7958. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7959. EXPECT_TRUE(res->body.empty());
  7960. }
  7961. TEST_F(StaticFileCompressionTest, MinLength) {
  7962. auto port = start(enable);
  7963. Client cli(HOST, port);
  7964. // 104 bytes, well under the default floor. Compressing it would add the
  7965. // gzip header and trailer to a body that already fits in one packet.
  7966. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::OK_200, res->status);
  7969. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7970. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7971. }
  7972. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7973. auto port = start([](Server &svr) {
  7974. svr.set_static_file_compression(true);
  7975. svr.set_static_file_compression_min_length(1);
  7976. });
  7977. Client cli(HOST, port);
  7978. cli.set_decompress(false);
  7979. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7982. // A 9-byte file comes back larger than it went in, because gzip's header and
  7983. // trailer outweigh anything deflate can save. That is the end of the range
  7984. // the floor exists to keep out.
  7985. EXPECT_GT(res->body.size(), 9U);
  7986. }
  7987. TEST_F(StaticFileCompressionTest, MaxLength) {
  7988. auto port = start([](Server &svr) {
  7989. svr.set_static_file_compression(true);
  7990. svr.set_static_file_compression_min_length(0);
  7991. svr.set_static_file_compression_max_length(1024);
  7992. });
  7993. Client cli(HOST, port);
  7994. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7995. // defines `small` as a macro on Windows.
  7996. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7997. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7998. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7999. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8000. // Under it: compressed.
  8001. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8002. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8003. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8004. }
  8005. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8006. auto port = start(enable_without_floor);
  8007. Client cli(HOST, port);
  8008. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8009. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8010. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8011. auto identity_etag = identity->get_header_value("ETag");
  8012. ASSERT_FALSE(identity_etag.empty());
  8013. auto gzipped =
  8014. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8015. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8016. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8017. auto gzip_etag = gzipped->get_header_value("ETag");
  8018. ASSERT_FALSE(gzip_etag.empty());
  8019. // Two representations, two validators.
  8020. EXPECT_NE(identity_etag, gzip_etag);
  8021. // Each one revalidates against the request that would produce it...
  8022. auto fresh =
  8023. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8024. {"If-None-Match", gzip_etag}});
  8025. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8026. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8027. auto fresh_identity =
  8028. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8029. {"If-None-Match", identity_etag}});
  8030. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8031. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8032. // ...and not against the other representation.
  8033. auto crossed =
  8034. cli.Get("/dir/index.html",
  8035. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8036. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8037. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8038. }
  8039. // The opt-in covers responses the server reads off disk itself. A caller's own
  8040. // known-length provider keeps its Content-Length and, more importantly, keeps
  8041. // delivering incrementally: routing it through a compressor would hold every
  8042. // write back until zlib's window filled.
  8043. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8044. auto port = start(enable);
  8045. Client cli(HOST, port);
  8046. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8050. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8051. EXPECT_EQ("aaabbb", res->body);
  8052. }
  8053. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8054. auto port = start(enable);
  8055. Client cli(HOST, port);
  8056. cli.set_read_timeout(1, 0);
  8057. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8058. Headers{{"Accept-Encoding", "gzip"}});
  8059. ASSERT_TRUE(handle.is_valid());
  8060. // The provider writes 100 bytes and then stalls for longer than the read
  8061. // timeout. Those first bytes have to arrive anyway: run the response through
  8062. // a compressor and zlib holds them until its window fills, so the read would
  8063. // come back empty instead.
  8064. char buf[256];
  8065. auto n = handle.read(buf, sizeof(buf));
  8066. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8067. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8068. }
  8069. #endif
  8070. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8071. TEST_F(ServerTest, Brotli) {
  8072. Headers headers;
  8073. headers.emplace("Accept-Encoding", "br");
  8074. auto res = cli_.Get("/compress", headers);
  8075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8076. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8077. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8078. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8079. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8080. "7890123456789012345678901234567890",
  8081. res->body);
  8082. EXPECT_EQ(StatusCode::OK_200, res->status);
  8083. }
  8084. #endif
  8085. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8086. TEST_F(ServerTest, Zstd) {
  8087. Headers headers;
  8088. headers.emplace("Accept-Encoding", "zstd");
  8089. auto res = cli_.Get("/compress", headers);
  8090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8091. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8092. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8093. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8094. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8095. "7890123456789012345678901234567890",
  8096. res->body);
  8097. EXPECT_EQ(StatusCode::OK_200, res->status);
  8098. }
  8099. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8100. Headers headers;
  8101. headers.emplace("Accept-Encoding", "");
  8102. auto res = cli_.Get("/compress", headers);
  8103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8104. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8106. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8107. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8108. "7890123456789012345678901234567890",
  8109. res->body);
  8110. EXPECT_EQ(StatusCode::OK_200, res->status);
  8111. }
  8112. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8113. Headers headers;
  8114. headers.emplace("Accept-Encoding", "zstd");
  8115. std::string body;
  8116. auto res = cli_.Get("/compress", headers,
  8117. [&](const char *data, uint64_t data_length) {
  8118. EXPECT_EQ(100U, data_length);
  8119. body.append(data, data_length);
  8120. return true;
  8121. });
  8122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8123. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8125. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8126. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8127. "7890123456789012345678901234567890",
  8128. body);
  8129. EXPECT_EQ(StatusCode::OK_200, res->status);
  8130. }
  8131. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8132. Headers headers;
  8133. headers.emplace("Accept-Encoding", "zstd");
  8134. cli_.set_decompress(false);
  8135. auto res = cli_.Get("/compress", headers);
  8136. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8137. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8138. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8139. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8143. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. ASSERT_EQ(26U, res->body.size());
  8146. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8147. 0);
  8148. }
  8149. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8150. Headers headers;
  8151. headers.emplace("Accept-Encoding", "");
  8152. std::string body;
  8153. auto res = cli_.Get("/compress", headers,
  8154. [&](const char *data, uint64_t data_length) {
  8155. EXPECT_EQ(100U, data_length);
  8156. body.append(data, data_length);
  8157. return true;
  8158. });
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8162. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8164. "7890123456789012345678901234567890",
  8165. body);
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. }
  8168. TEST_F(ServerTest, NoZstd) {
  8169. Headers headers;
  8170. headers.emplace("Accept-Encoding", "zstd");
  8171. auto res = cli_.Get("/nocompress", headers);
  8172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8173. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8174. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8175. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8177. "7890123456789012345678901234567890",
  8178. res->body);
  8179. EXPECT_EQ(StatusCode::OK_200, res->status);
  8180. }
  8181. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8182. Headers headers;
  8183. headers.emplace("Accept-Encoding", "zstd");
  8184. std::string body;
  8185. auto res = cli_.Get("/nocompress", headers,
  8186. [&](const char *data, uint64_t data_length) {
  8187. EXPECT_EQ(100U, data_length);
  8188. body.append(data, data_length);
  8189. return true;
  8190. });
  8191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8192. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8193. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8196. "7890123456789012345678901234567890",
  8197. body);
  8198. EXPECT_EQ(StatusCode::OK_200, res->status);
  8199. }
  8200. // TODO: How to enable zstd ??
  8201. TEST_F(ServerTest, MultipartFormDataZstd) {
  8202. UploadFormDataItems items = {
  8203. {"key1", "test", "", ""},
  8204. {"key2", "--abcdefg123", "", ""},
  8205. };
  8206. Headers headers;
  8207. headers.emplace("Accept-Encoding", "zstd");
  8208. cli_.set_compress(true);
  8209. auto res = cli_.Post("/compress-multipart", headers, items);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. }
  8213. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8214. Headers headers;
  8215. headers.emplace("Accept-Encoding", "zstd");
  8216. cli_.set_compress(true);
  8217. auto res = cli_.Put(
  8218. "/put", headers, 3,
  8219. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8220. sink.os << "PUT";
  8221. return true;
  8222. },
  8223. "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. EXPECT_EQ("PUT", res->body);
  8227. }
  8228. // Pre-compression logging tests
  8229. TEST_F(ServerTest, PreCompressionLogging) {
  8230. // Test data for compression (matches the actual /compress endpoint content)
  8231. const std::string test_content =
  8232. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8233. "3456789012345678901234567890";
  8234. // Variables to capture logging data
  8235. std::string pre_compression_body;
  8236. std::string pre_compression_content_type;
  8237. std::string pre_compression_content_encoding;
  8238. std::string post_compression_body;
  8239. std::string post_compression_content_type;
  8240. std::string post_compression_content_encoding;
  8241. // Set up pre-compression logger
  8242. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8243. const Response &res) {
  8244. pre_compression_body = res.body;
  8245. pre_compression_content_type = res.get_header_value("Content-Type");
  8246. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8247. });
  8248. // Set up post-compression logger
  8249. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8250. post_compression_body = res.body;
  8251. post_compression_content_type = res.get_header_value("Content-Type");
  8252. post_compression_content_encoding =
  8253. res.get_header_value("Content-Encoding");
  8254. });
  8255. // Test with gzip compression
  8256. Headers headers;
  8257. headers.emplace("Accept-Encoding", "gzip");
  8258. auto res = cli_.Get("/compress", headers);
  8259. // Verify response was compressed
  8260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8261. EXPECT_EQ(StatusCode::OK_200, res->status);
  8262. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8263. // Verify pre-compression logger captured uncompressed content
  8264. EXPECT_EQ(test_content, pre_compression_body);
  8265. EXPECT_EQ("text/plain", pre_compression_content_type);
  8266. EXPECT_TRUE(pre_compression_content_encoding
  8267. .empty()); // No encoding header before compression
  8268. // Verify post-compression logger captured compressed content
  8269. EXPECT_NE(test_content,
  8270. post_compression_body); // Should be different after compression
  8271. EXPECT_EQ("text/plain", post_compression_content_type);
  8272. EXPECT_EQ("gzip", post_compression_content_encoding);
  8273. // Verify compressed content is smaller
  8274. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8275. }
  8276. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8277. const std::string test_content =
  8278. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8279. "3456789012345678901234567890";
  8280. std::string pre_compression_body;
  8281. std::string post_compression_body;
  8282. svr_.set_pre_compression_logger(
  8283. [&](const Request & /*req*/, const Response &res) {
  8284. pre_compression_body = res.body;
  8285. });
  8286. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8287. post_compression_body = res.body;
  8288. });
  8289. Headers headers;
  8290. headers.emplace("Accept-Encoding", "br");
  8291. auto res = cli_.Get("/compress", headers);
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8295. // Verify pre-compression content is uncompressed
  8296. EXPECT_EQ(test_content, pre_compression_body);
  8297. // Verify post-compression content is compressed
  8298. EXPECT_NE(test_content, post_compression_body);
  8299. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8300. }
  8301. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8302. const std::string test_content =
  8303. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8304. "3456789012345678901234567890";
  8305. std::string pre_compression_body;
  8306. std::string post_compression_body;
  8307. svr_.set_pre_compression_logger(
  8308. [&](const Request & /*req*/, const Response &res) {
  8309. pre_compression_body = res.body;
  8310. });
  8311. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8312. post_compression_body = res.body;
  8313. });
  8314. // Request without compression (use /nocompress endpoint)
  8315. Headers headers;
  8316. auto res = cli_.Get("/nocompress", headers);
  8317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8318. EXPECT_EQ(StatusCode::OK_200, res->status);
  8319. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8320. // Pre-compression logger should not be called when no compression is applied
  8321. EXPECT_TRUE(
  8322. pre_compression_body.empty()); // Pre-compression logger not called
  8323. EXPECT_EQ(
  8324. test_content,
  8325. post_compression_body); // Post-compression logger captures final content
  8326. }
  8327. TEST_F(ServerTest, LoggerSeesContentLength) {
  8328. size_t logged_content_length = 0;
  8329. std::string logged_content_length_header;
  8330. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8331. logged_content_length = res.content_length_;
  8332. logged_content_length_header = res.get_header_value("Content-Length");
  8333. });
  8334. auto res = cli_.Get("/nocompress");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. EXPECT_EQ(res->body.size(), logged_content_length);
  8338. EXPECT_EQ(std::to_string(logged_content_length),
  8339. logged_content_length_header);
  8340. }
  8341. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8342. const std::string test_content =
  8343. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8344. "3456789012345678901234567890";
  8345. std::string pre_compression_body;
  8346. bool pre_logger_called = false;
  8347. // Set only pre-compression logger
  8348. svr_.set_pre_compression_logger(
  8349. [&](const Request & /*req*/, const Response &res) {
  8350. pre_compression_body = res.body;
  8351. pre_logger_called = true;
  8352. });
  8353. Headers headers;
  8354. headers.emplace("Accept-Encoding", "gzip");
  8355. auto res = cli_.Get("/compress", headers);
  8356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8357. EXPECT_EQ(StatusCode::OK_200, res->status);
  8358. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8359. // Verify pre-compression logger was called
  8360. EXPECT_TRUE(pre_logger_called);
  8361. EXPECT_EQ(test_content, pre_compression_body);
  8362. }
  8363. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8364. {
  8365. // Test with Expect: 100-continue header - success case
  8366. // Server returns 100 Continue, client sends body, server returns 200 OK
  8367. Request req;
  8368. req.method = "POST";
  8369. req.path = "/post-large";
  8370. req.set_header("Expect", "100-continue");
  8371. req.body = LARGE_DATA;
  8372. Response res;
  8373. auto error = Error::Success;
  8374. cli_.set_keep_alive(true);
  8375. auto ret = cli_.send(req, res, error);
  8376. EXPECT_TRUE(ret);
  8377. EXPECT_EQ(StatusCode::OK_200, res.status);
  8378. EXPECT_EQ(LARGE_DATA, res.body);
  8379. }
  8380. {
  8381. // Test with Expect: 100-continue header - error case
  8382. // Client should not send the body when server returns an error
  8383. Request req;
  8384. req.method = "POST";
  8385. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8386. req.set_header("Expect", "100-continue");
  8387. req.body = LARGE_DATA;
  8388. Response res;
  8389. auto error = Error::Success;
  8390. auto start = std::chrono::high_resolution_clock::now();
  8391. cli_.set_keep_alive(true);
  8392. auto ret = cli_.send(req, res, error);
  8393. auto end = std::chrono::high_resolution_clock::now();
  8394. auto elapsed =
  8395. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8396. .count();
  8397. // With Expect: 100-continue, request completes successfully but with error
  8398. EXPECT_TRUE(ret);
  8399. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8400. EXPECT_EQ("close", res.get_header_value("Connection"));
  8401. EXPECT_FALSE(cli_.is_socket_open());
  8402. EXPECT_LE(elapsed, 2000);
  8403. }
  8404. {
  8405. // Send an extra GET request to ensure error recovery without hanging
  8406. Request req;
  8407. req.method = "GET";
  8408. req.path = "/hi";
  8409. auto start = std::chrono::high_resolution_clock::now();
  8410. auto res = cli_.send(req);
  8411. auto end = std::chrono::high_resolution_clock::now();
  8412. auto elapsed =
  8413. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8414. .count();
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. EXPECT_EQ("Hello World!", res->body);
  8418. EXPECT_LE(elapsed, 500);
  8419. }
  8420. }
  8421. TEST(ZstdDecompressor, ChunkedDecompression) {
  8422. std::string data;
  8423. for (size_t i = 0; i < 32 * 1024; ++i) {
  8424. data.push_back(static_cast<char>('a' + i % 26));
  8425. }
  8426. std::string compressed_data;
  8427. {
  8428. httplib::detail::zstd_compressor compressor;
  8429. bool result = compressor.compress(
  8430. data.data(), data.size(),
  8431. /*last=*/true,
  8432. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8433. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8434. compressed_data_size);
  8435. return true;
  8436. });
  8437. ASSERT_TRUE(result);
  8438. }
  8439. std::string decompressed_data;
  8440. {
  8441. httplib::detail::zstd_decompressor decompressor;
  8442. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8443. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8444. size_t chunk_size = 130;
  8445. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8446. chunk_begin += chunk_size) {
  8447. size_t current_chunk_size =
  8448. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8449. bool result = decompressor.decompress(
  8450. compressed_data.data() + chunk_begin, current_chunk_size,
  8451. [&](const char *decompressed_data_chunk,
  8452. size_t decompressed_data_chunk_size) {
  8453. decompressed_data.insert(decompressed_data.size(),
  8454. decompressed_data_chunk,
  8455. decompressed_data_chunk_size);
  8456. return true;
  8457. });
  8458. ASSERT_TRUE(result);
  8459. }
  8460. }
  8461. ASSERT_EQ(data, decompressed_data);
  8462. }
  8463. TEST(ZstdDecompressor, Decompress) {
  8464. std::string original_text = "Compressed with ZSTD";
  8465. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8466. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8467. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8468. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8469. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8470. std::string decompressed_data;
  8471. {
  8472. httplib::detail::zstd_decompressor decompressor;
  8473. bool result = decompressor.decompress(
  8474. compressed_data.data(), compressed_data.size(),
  8475. [&](const char *decompressed_data_chunk,
  8476. size_t decompressed_data_chunk_size) {
  8477. decompressed_data.insert(decompressed_data.size(),
  8478. decompressed_data_chunk,
  8479. decompressed_data_chunk_size);
  8480. return true;
  8481. });
  8482. ASSERT_TRUE(result);
  8483. }
  8484. ASSERT_EQ(original_text, decompressed_data);
  8485. }
  8486. #endif
  8487. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8488. // separate chunks so that the server sees each part in its own read(). Used to
  8489. // place a read boundary at a specific offset of a request body.
  8490. static bool send_request_in_parts(time_t read_timeout_sec,
  8491. const std::vector<std::string> &parts,
  8492. std::string *resp = nullptr,
  8493. int port = PORT) {
  8494. auto error = Error::Success;
  8495. auto client_sock = detail::create_client_socket(
  8496. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8497. /*connection_timeout_sec=*/5, 0,
  8498. /*read_timeout_sec=*/5, 0,
  8499. /*write_timeout_sec=*/5, 0, std::string(), error);
  8500. if (client_sock == INVALID_SOCKET) { return false; }
  8501. auto ret = detail::process_client_socket(
  8502. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8503. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8504. for (size_t i = 0; i < parts.size(); i++) {
  8505. const auto &part = parts[i];
  8506. if (part.size() !=
  8507. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8508. return false;
  8509. }
  8510. if (i + 1 < parts.size()) {
  8511. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8512. }
  8513. }
  8514. char buf[512];
  8515. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8516. while (line_reader.getline()) {
  8517. if (resp) { *resp += line_reader.ptr(); }
  8518. }
  8519. return true;
  8520. });
  8521. detail::close_socket(client_sock);
  8522. return ret;
  8523. }
  8524. // Sends a raw request to a server listening at HOST:PORT.
  8525. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8526. std::string *resp = nullptr, int port = PORT) {
  8527. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8528. }
  8529. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8530. Server svr;
  8531. std::string header_value;
  8532. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8533. header_value = req.get_header_value("foo");
  8534. res.set_content("ok", "text/plain");
  8535. });
  8536. thread t = thread([&] { svr.listen(HOST, PORT); });
  8537. auto se = detail::scope_exit([&] {
  8538. svr.stop();
  8539. t.join();
  8540. ASSERT_FALSE(svr.is_running());
  8541. });
  8542. svr.wait_until_ready();
  8543. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8544. // like characters are not treated the same - use vertical tab and escape.
  8545. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8546. "foo: \t \v bar \x1B\t \r\n"
  8547. "Connection: close\r\n"
  8548. "\r\n";
  8549. std::string res;
  8550. ASSERT_TRUE(send_request(5, req, &res));
  8551. EXPECT_EQ(header_value, "");
  8552. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8553. }
  8554. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8555. Server svr;
  8556. std::string received;
  8557. svr.Get("/order", [&](const Request &req, Response &res) {
  8558. received = entries_to_string(req.headers);
  8559. res.set_content("ok", "text/plain");
  8560. });
  8561. auto port = svr.bind_to_any_port(HOST);
  8562. thread t = thread([&] { svr.listen_after_bind(); });
  8563. auto se = detail::scope_exit([&] {
  8564. svr.stop();
  8565. t.join();
  8566. ASSERT_FALSE(svr.is_running());
  8567. });
  8568. svr.wait_until_ready();
  8569. const std::string req = "GET /order HTTP/1.1\r\n"
  8570. "X-First: 1\r\n"
  8571. "X-Dup: a\r\n"
  8572. "X-Second: 2\r\n"
  8573. "X-Dup: b\r\n"
  8574. "Connection: close\r\n"
  8575. "\r\n";
  8576. std::string res;
  8577. ASSERT_TRUE(send_request(5, req, &res, port));
  8578. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8579. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8580. }
  8581. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8582. Server svr;
  8583. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8584. res.set_header("Set-Cookie", "first=1");
  8585. res.set_header("X-Between", "y");
  8586. res.set_header("Set-Cookie", "second=2");
  8587. res.set_content("ok", "text/plain");
  8588. });
  8589. auto port = svr.bind_to_any_port(HOST);
  8590. thread t = thread([&] { svr.listen_after_bind(); });
  8591. auto se = detail::scope_exit([&] {
  8592. svr.stop();
  8593. t.join();
  8594. ASSERT_FALSE(svr.is_running());
  8595. });
  8596. svr.wait_until_ready();
  8597. Client cli(HOST, port);
  8598. auto res = cli.Get("/cookies");
  8599. ASSERT_TRUE(res);
  8600. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8601. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8602. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8603. }
  8604. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8605. Server svr;
  8606. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8607. auto i = new int(0);
  8608. res.set_header("Trailer", "X-Safe, X-Reflected");
  8609. res.set_chunked_content_provider(
  8610. "text/plain",
  8611. [i](size_t /*offset*/, DataSink &sink) {
  8612. if (*i == 0) {
  8613. sink.os << "body";
  8614. } else {
  8615. Headers trailer;
  8616. // A valid trailer that must survive.
  8617. trailer.emplace("X-Safe", "safe");
  8618. // Attacker-controlled value carrying CR/LF (response splitting).
  8619. trailer.emplace("X-Reflected",
  8620. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8621. // Attacker-controlled name carrying CR/LF.
  8622. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8623. sink.done_with_trailer(trailer);
  8624. }
  8625. (*i)++;
  8626. return true;
  8627. },
  8628. [i](bool /*success*/) { delete i; });
  8629. });
  8630. thread t = thread([&] { svr.listen(HOST, PORT); });
  8631. auto se = detail::scope_exit([&] {
  8632. svr.stop();
  8633. t.join();
  8634. ASSERT_FALSE(svr.is_running());
  8635. });
  8636. svr.wait_until_ready();
  8637. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8638. "Host: " + HOST +
  8639. "\r\n"
  8640. "Connection: close\r\n"
  8641. "\r\n";
  8642. std::string res;
  8643. ASSERT_TRUE(send_request(5, req, &res));
  8644. // The injected fields must not appear anywhere in the raw response.
  8645. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8646. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8647. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8648. // Invalid trailers are dropped entirely, matching set_header().
  8649. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8650. // The valid trailer still passes through.
  8651. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8652. }
  8653. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8654. Server svr;
  8655. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8656. // res.headers is a public field an application can populate directly,
  8657. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8658. // A valid header that must survive.
  8659. res.headers.emplace("X-Safe", "safe");
  8660. // Attacker-controlled value carrying CR/LF (response splitting).
  8661. res.headers.emplace("X-Reflected",
  8662. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8663. // Attacker-controlled name carrying CR/LF.
  8664. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8665. res.set_content("body", "text/plain");
  8666. });
  8667. thread t = thread([&] { svr.listen(HOST, PORT); });
  8668. auto se = detail::scope_exit([&] {
  8669. svr.stop();
  8670. t.join();
  8671. ASSERT_FALSE(svr.is_running());
  8672. });
  8673. svr.wait_until_ready();
  8674. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8675. "Host: " + HOST +
  8676. "\r\n"
  8677. "Connection: close\r\n"
  8678. "\r\n";
  8679. std::string res;
  8680. ASSERT_TRUE(send_request(5, req, &res));
  8681. // The injected fields must not appear anywhere in the raw response.
  8682. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8683. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8684. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8685. // Invalid headers are dropped entirely, matching set_header().
  8686. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8687. // The valid header still passes through.
  8688. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8689. }
  8690. // Forward declaration: in split builds split.py strips `inline` and moves the
  8691. // definition into httplib.cc, so detail::write_request_line is not visible from
  8692. // the public httplib.h. Re-declaring it here lets the tests link against the
  8693. // symbol in both header-only and split builds.
  8694. namespace httplib {
  8695. namespace detail {
  8696. ssize_t write_request_line(Stream &strm, const std::string &method,
  8697. const std::string &path);
  8698. } // namespace detail
  8699. } // namespace httplib
  8700. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8701. // A well-formed target is written verbatim.
  8702. {
  8703. detail::BufferStream strm;
  8704. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8705. EXPECT_GT(n, 0);
  8706. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8707. }
  8708. // A target carrying CR/LF, SP or other control octets must be rejected
  8709. // before anything reaches the wire, otherwise it splits the request line and
  8710. // injects a header or a whole request.
  8711. const std::string evil_targets[] = {
  8712. "/a\r\nInjected: pwned",
  8713. "/a\rInjected",
  8714. "/a\nInjected",
  8715. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8716. "/a b",
  8717. "/a\tb",
  8718. "/a\x7f",
  8719. };
  8720. for (const auto &evil : evil_targets) {
  8721. detail::BufferStream strm;
  8722. auto n = detail::write_request_line(strm, "GET", evil);
  8723. EXPECT_LT(n, 0);
  8724. EXPECT_TRUE(strm.get_buffer().empty());
  8725. }
  8726. }
  8727. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8728. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8729. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8730. // target reaches write_request. The client must fail cleanly with
  8731. // Error::Write instead of putting a request-line-less, header-injecting
  8732. // request on the wire.
  8733. Server svr;
  8734. svr.Get("/a", [](const Request &, Response &res) {
  8735. res.set_content("ok", "text/plain");
  8736. });
  8737. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8738. auto se = detail::scope_exit([&] {
  8739. svr.stop();
  8740. thread.join();
  8741. ASSERT_FALSE(svr.is_running());
  8742. });
  8743. svr.wait_until_ready();
  8744. {
  8745. Client cli(HOST, PORT);
  8746. cli.set_path_encode(false);
  8747. // The request is rejected before anything is written, so the connection
  8748. // stays silent and the subsequent response read would otherwise block for
  8749. // the full default read timeout. Shorten it -- the assertion is on the
  8750. // error, not the timeout.
  8751. cli.set_read_timeout(1, 0);
  8752. auto res = cli.Get("/a\r\nInjected: pwned");
  8753. EXPECT_FALSE(res);
  8754. EXPECT_EQ(Error::Write, res.error());
  8755. }
  8756. }
  8757. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8758. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8759. // including extension methods.
  8760. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8761. for (const auto &method : good_methods) {
  8762. detail::BufferStream strm;
  8763. auto n = detail::write_request_line(strm, method, "/");
  8764. EXPECT_GT(n, 0);
  8765. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8766. }
  8767. // A method carrying CR/LF would split the request line and smuggle a whole
  8768. // request ahead of the real one. A space or an empty method corrupts the
  8769. // request line. All must be rejected before anything reaches the wire.
  8770. const std::string evil_methods[] = {
  8771. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8772. "GET\r\nInjected: pwned",
  8773. "GET\r",
  8774. "GET\n",
  8775. "GE T",
  8776. "",
  8777. };
  8778. for (const auto &evil : evil_methods) {
  8779. detail::BufferStream strm;
  8780. auto n = detail::write_request_line(strm, evil, "/");
  8781. EXPECT_LT(n, 0);
  8782. EXPECT_TRUE(strm.get_buffer().empty());
  8783. }
  8784. }
  8785. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8786. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8787. // through Client::send must fail with Error::Write and no request, neither
  8788. // the smuggled one nor the real one, may reach the server.
  8789. Server svr;
  8790. std::atomic<int> request_count(0);
  8791. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8792. request_count++;
  8793. res.status = StatusCode::OK_200;
  8794. return Server::HandlerResponse::Handled;
  8795. });
  8796. auto port = svr.bind_to_any_port(HOST);
  8797. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8798. auto se = detail::scope_exit([&] {
  8799. svr.stop();
  8800. thread.join();
  8801. ASSERT_FALSE(svr.is_running());
  8802. });
  8803. svr.wait_until_ready();
  8804. {
  8805. Client cli(HOST, port);
  8806. const std::string evil_methods[] = {
  8807. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8808. "GE T",
  8809. "",
  8810. };
  8811. for (const auto &evil : evil_methods) {
  8812. Request req;
  8813. req.method = evil;
  8814. req.path = "/";
  8815. auto res = cli.send(req);
  8816. EXPECT_FALSE(res);
  8817. EXPECT_EQ(Error::Write, res.error());
  8818. }
  8819. auto handle =
  8820. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8821. EXPECT_FALSE(handle.is_valid());
  8822. EXPECT_EQ(Error::Write, handle.error);
  8823. // A valid request on the same client still goes through.
  8824. auto res = cli.Get("/");
  8825. ASSERT_TRUE(res);
  8826. EXPECT_EQ(StatusCode::OK_200, res->status);
  8827. }
  8828. EXPECT_EQ(1, request_count.load());
  8829. }
  8830. // Sends a raw request and verifies that there isn't a crash or exception.
  8831. static void test_raw_request(const std::string &req,
  8832. std::string *out = nullptr) {
  8833. Server svr;
  8834. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8835. res.set_content("ok", "text/plain");
  8836. });
  8837. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8838. res.set_content("ok", "text/plain");
  8839. });
  8840. svr.Get("/header_field_value_check",
  8841. [&](const Request & /*req*/, Response &res) {
  8842. res.set_content("ok", "text/plain");
  8843. });
  8844. svr.CustomRoute("PROPFIND", "/dav",
  8845. [&](const Request & /*req*/, Response &res) {
  8846. res.status = StatusCode::MultiStatus_207;
  8847. });
  8848. // Server read timeout must be longer than the client read timeout for the
  8849. // bug to reproduce, probably to force the server to process a request
  8850. // without a trailing blank line.
  8851. const time_t client_read_timeout_sec = 1;
  8852. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8853. bool listen_thread_ok = false;
  8854. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8855. auto se = detail::scope_exit([&] {
  8856. svr.stop();
  8857. t.join();
  8858. ASSERT_FALSE(svr.is_running());
  8859. EXPECT_TRUE(listen_thread_ok);
  8860. });
  8861. svr.wait_until_ready();
  8862. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8863. }
  8864. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8865. // A certain header line causes an exception if the header property is parsed
  8866. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8867. test_raw_request(
  8868. "GET /hi HTTP/1.1\r\n"
  8869. " : "
  8870. " "
  8871. " ");
  8872. }
  8873. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8874. // A certain header line causes an exception if the header property *name* is
  8875. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8876. // greedy matcher and requires backtracking when there are a lot of ":"
  8877. // characters.
  8878. // This occurs with libc++ but not libstdc++.
  8879. test_raw_request(
  8880. "GET /hi HTTP/1.1\r\n"
  8881. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8882. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8883. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8884. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8885. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8886. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8887. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8888. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8889. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8890. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8891. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8892. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8893. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8894. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8895. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8896. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8897. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8898. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8899. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8900. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8901. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8902. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8903. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8904. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8905. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8906. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8907. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8908. "&&&%%%");
  8909. }
  8910. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8911. // Make sure this doesn't crash the server.
  8912. // In a previous version of the header line regex, the "\r" rendered the line
  8913. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8914. // a new position where the leading white space ended and the field value
  8915. // began.
  8916. // The crash occurs with libc++ but not libstdc++.
  8917. test_raw_request("GET /hi HTTP/1.1\r\n"
  8918. "a:" +
  8919. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8920. "\r\n"
  8921. "\r\n");
  8922. }
  8923. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8924. std::string out;
  8925. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8926. "Content-Type: text/plain\r\n"
  8927. "Transfer-Encoding: chunked\r\n"
  8928. "\r\n"
  8929. "nothex\r\n",
  8930. &out);
  8931. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8932. }
  8933. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8934. std::string out;
  8935. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8936. "Content-Type: text/plain\r\n"
  8937. "Transfer-Encoding: chunked\r\n"
  8938. "\r\n"
  8939. "3\r\n"
  8940. "xyz\r\n"
  8941. "NaN\r\n",
  8942. &out);
  8943. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8944. }
  8945. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8946. std::string out;
  8947. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8948. "Content-Type: text/plain\r\n"
  8949. "Transfer-Encoding: chunked\r\n"
  8950. "\r\n"
  8951. // Length is too large for 64 bits.
  8952. "1ffffffffffffffff\r\n"
  8953. "xyz\r\n",
  8954. &out);
  8955. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8956. }
  8957. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8958. test_raw_request("GET /hi HTTP/1.1\r\n"
  8959. "Content-Type: text/plain\r\n\r");
  8960. }
  8961. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8962. std::string out;
  8963. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8964. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8965. }
  8966. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8967. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8968. std::string out;
  8969. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8970. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8971. }
  8972. }
  8973. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8974. std::string out;
  8975. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8976. "Connection: close\r\n\r\n",
  8977. &out);
  8978. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8979. }
  8980. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8981. Server svr;
  8982. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8983. EXPECT_TRUE(!req.remote_addr.empty());
  8984. });
  8985. thread t = thread([&] { svr.listen(HOST, PORT); });
  8986. auto se = detail::scope_exit([&] {
  8987. svr.stop();
  8988. t.join();
  8989. ASSERT_FALSE(svr.is_running());
  8990. });
  8991. svr.wait_until_ready();
  8992. // Send an invalid request line to trigger Bad Request
  8993. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8994. std::string out;
  8995. ASSERT_TRUE(send_request(5, bad_req, &out));
  8996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8997. }
  8998. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8999. // answered right away rather than blocking on a read that waits for EOF.
  9000. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9001. std::string out;
  9002. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9003. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9004. }
  9005. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9006. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9007. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9008. for (const auto *method : methods) {
  9009. Server svr;
  9010. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9011. EXPECT_FALSE(svr.is_valid()) << method;
  9012. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9013. }
  9014. }
  9015. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9016. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9017. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9018. for (const auto *method : methods) {
  9019. Server svr;
  9020. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9021. EXPECT_FALSE(svr.is_valid()) << method;
  9022. }
  9023. }
  9024. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9025. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9026. "COPY", "MOVE", "LOCK",
  9027. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9028. Server svr;
  9029. for (const auto *method : methods) {
  9030. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9031. }
  9032. EXPECT_TRUE(svr.is_valid());
  9033. }
  9034. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9035. Server svr;
  9036. svr.CustomRoute("POST", "/x",
  9037. [](const Request &, Response &, const ContentReader &) {});
  9038. EXPECT_FALSE(svr.is_valid());
  9039. }
  9040. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9041. Server svr;
  9042. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9043. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9044. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9045. EXPECT_FALSE(svr.is_valid());
  9046. }
  9047. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9048. Server svr;
  9049. auto captured = Error::Success;
  9050. svr.set_error_logger(
  9051. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9052. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9053. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9054. }
  9055. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9056. std::string out;
  9057. std::string request(
  9058. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9059. test_raw_request(request, &out);
  9060. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9061. }
  9062. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9063. std::string out;
  9064. std::string request(
  9065. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9066. test_raw_request(request, &out);
  9067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9068. }
  9069. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9070. std::string out;
  9071. std::string request(
  9072. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9073. test_raw_request(request, &out);
  9074. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9075. }
  9076. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9077. std::string out;
  9078. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9079. "Test: \r\n\r\n",
  9080. &out);
  9081. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9082. }
  9083. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9084. Server svr;
  9085. std::string x_custom;
  9086. std::string cookie;
  9087. std::string xff;
  9088. std::string x_unicode;
  9089. std::string x_iis;
  9090. svr.Get("/check", [&](const Request &req, Response &res) {
  9091. x_custom = req.get_header_value("X-Custom");
  9092. cookie = req.get_header_value("Cookie");
  9093. xff = req.get_header_value("X-Forwarded-For");
  9094. x_unicode = req.get_header_value("X-Unicode");
  9095. x_iis = req.get_header_value("X-IIS");
  9096. res.set_content("ok", "text/plain");
  9097. });
  9098. thread t = thread([&] { svr.listen(HOST, PORT); });
  9099. auto se = detail::scope_exit([&] {
  9100. svr.stop();
  9101. t.join();
  9102. ASSERT_FALSE(svr.is_running());
  9103. });
  9104. svr.wait_until_ready();
  9105. const std::string req = "GET /check HTTP/1.1\r\n"
  9106. "Host: localhost\r\n"
  9107. "X-Custom: a%0D%0AInjected: b\r\n"
  9108. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9109. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9110. "X-Unicode: %E3%81%82\r\n"
  9111. "X-IIS: %u00E9\r\n"
  9112. "Connection: close\r\n"
  9113. "\r\n";
  9114. std::string res;
  9115. ASSERT_TRUE(send_request(5, req, &res));
  9116. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9117. // Every value must be returned verbatim (wire form), with no decoding.
  9118. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9119. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9120. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9121. EXPECT_EQ("%E3%81%82", x_unicode);
  9122. EXPECT_EQ("%u00E9", x_iis);
  9123. }
  9124. // Applications that previously relied on automatic percent-decoding can
  9125. // reproduce the old behavior by explicitly calling decode_path_component()
  9126. // or, for RFC 3986 conformance, decode_uri_component().
  9127. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9128. Server svr;
  9129. std::string decoded;
  9130. svr.Get("/check", [&](const Request &req, Response &res) {
  9131. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9132. res.set_content("ok", "text/plain");
  9133. });
  9134. thread t = thread([&] { svr.listen(HOST, PORT); });
  9135. auto se = detail::scope_exit([&] {
  9136. svr.stop();
  9137. t.join();
  9138. ASSERT_FALSE(svr.is_running());
  9139. });
  9140. svr.wait_until_ready();
  9141. const std::string req = "GET /check HTTP/1.1\r\n"
  9142. "Host: localhost\r\n"
  9143. "X-Custom: hello%20world\r\n"
  9144. "Connection: close\r\n"
  9145. "\r\n";
  9146. std::string res;
  9147. ASSERT_TRUE(send_request(5, req, &res));
  9148. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9149. EXPECT_EQ("hello world", decoded);
  9150. }
  9151. // Regression test for #2033. Browsers send Referer values that include
  9152. // percent-encoded characters such as %0A inside the URL. Decoding the
  9153. // header value would either trip the post-decode CR/LF/NUL guard (the
  9154. // original bug, returning 400) or, after that guard was relaxed, silently
  9155. // store a literal LF — both unacceptable. The wire form must round-trip.
  9156. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9157. Server svr;
  9158. std::string referer;
  9159. svr.Get("/check", [&](const Request &req, Response &res) {
  9160. referer = req.get_header_value("Referer");
  9161. res.set_content("ok", "text/plain");
  9162. });
  9163. thread t = thread([&] { svr.listen(HOST, PORT); });
  9164. auto se = detail::scope_exit([&] {
  9165. svr.stop();
  9166. t.join();
  9167. ASSERT_FALSE(svr.is_running());
  9168. });
  9169. svr.wait_until_ready();
  9170. const std::string req = "GET /check HTTP/1.1\r\n"
  9171. "Host: localhost\r\n"
  9172. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9173. "Connection: close\r\n"
  9174. "\r\n";
  9175. std::string res;
  9176. ASSERT_TRUE(send_request(5, req, &res));
  9177. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9178. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9179. }
  9180. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9181. Server svr;
  9182. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9183. res.set_header("Cache-Control", "no-cache");
  9184. res.set_chunked_content_provider(
  9185. "text/event-stream", [](size_t offset, DataSink &sink) {
  9186. std::string s = "data:";
  9187. s += std::to_string(offset);
  9188. s += "\n\n";
  9189. auto ret = sink.write(s.data(), s.size());
  9190. EXPECT_TRUE(ret);
  9191. std::this_thread::sleep_for(std::chrono::seconds(1));
  9192. return true;
  9193. });
  9194. });
  9195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9196. svr.wait_until_ready();
  9197. Client client(HOST, PORT);
  9198. const Headers headers = {{"Accept", "text/event-stream"}};
  9199. auto get_thread = std::thread([&client, &headers]() {
  9200. auto res = client.Get(
  9201. "/events", headers,
  9202. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9203. });
  9204. auto se = detail::scope_exit([&] {
  9205. svr.stop();
  9206. get_thread.join();
  9207. listen_thread.join();
  9208. ASSERT_FALSE(svr.is_running());
  9209. });
  9210. // Give GET time to get a few messages.
  9211. std::this_thread::sleep_for(std::chrono::seconds(2));
  9212. }
  9213. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9214. httplib::Server svr;
  9215. svr.Post("/hi",
  9216. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9217. res.status = StatusCode::OK_200;
  9218. });
  9219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9220. svr.wait_until_ready();
  9221. Client cli(HOST, PORT);
  9222. auto res = cli.Post("/hi", "data", "text/plain");
  9223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9224. EXPECT_EQ(StatusCode::OK_200, res->status);
  9225. svr.stop();
  9226. thread.join();
  9227. ASSERT_FALSE(svr.is_running());
  9228. res = cli.Post("/hi", "data", "text/plain");
  9229. ASSERT_FALSE(res);
  9230. }
  9231. TEST(ServerStopTest, ListenFailure) {
  9232. Server svr;
  9233. auto t = thread([&]() {
  9234. auto ret = svr.listen("????", PORT);
  9235. EXPECT_FALSE(ret);
  9236. });
  9237. svr.wait_until_ready();
  9238. svr.stop();
  9239. t.join();
  9240. }
  9241. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9242. TEST(ServerStopTest, Decommision) {
  9243. Server svr;
  9244. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9245. for (int i = 0; i < 4; i++) {
  9246. auto is_even = !(i % 2);
  9247. std::thread t{[&] {
  9248. try {
  9249. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9250. if (is_even) {
  9251. throw std::runtime_error("Some thing that happens to go wrong.");
  9252. }
  9253. svr.listen(HOST, PORT);
  9254. } catch (...) { svr.decommission(); }
  9255. }};
  9256. svr.wait_until_ready();
  9257. // Server is up
  9258. {
  9259. Client cli(HOST, PORT);
  9260. auto res = cli.Get("/hi");
  9261. if (is_even) {
  9262. EXPECT_FALSE(res);
  9263. } else {
  9264. EXPECT_TRUE(res);
  9265. EXPECT_EQ("hi...", res->body);
  9266. }
  9267. }
  9268. svr.stop();
  9269. t.join();
  9270. // Server is down...
  9271. {
  9272. Client cli(HOST, PORT);
  9273. auto res = cli.Get("/hi");
  9274. EXPECT_FALSE(res);
  9275. }
  9276. }
  9277. }
  9278. #endif
  9279. // Helper function for string body upload progress tests
  9280. template <typename SetupHandler, typename ClientCall>
  9281. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9282. ClientCall &&client_call,
  9283. const string &body) {
  9284. Server svr;
  9285. setup_handler(svr);
  9286. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9287. auto se = detail::scope_exit([&] {
  9288. svr.stop();
  9289. t.join();
  9290. });
  9291. svr.wait_until_ready();
  9292. Client cli(HOST, PORT);
  9293. vector<uint64_t> progress_values;
  9294. bool progress_called = false;
  9295. auto res =
  9296. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9297. progress_values.push_back(current);
  9298. progress_called = true;
  9299. return true;
  9300. });
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(200, res->status);
  9303. EXPECT_TRUE(progress_called);
  9304. }
  9305. TEST(UploadProgressTest, PostStringBodyBasic) {
  9306. TestStringBodyUploadProgress(
  9307. [](Server &svr) {
  9308. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9309. res.set_content("received", "text/plain");
  9310. });
  9311. },
  9312. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9313. return cli.Post("/test", body, "text/plain", progress_callback);
  9314. },
  9315. "test data for upload progress");
  9316. }
  9317. TEST(UploadProgressTest, PutStringBodyBasic) {
  9318. TestStringBodyUploadProgress(
  9319. [](Server &svr) {
  9320. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9321. res.set_content("put received", "text/plain");
  9322. });
  9323. },
  9324. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9325. return cli.Put("/test", body, "text/plain", progress_callback);
  9326. },
  9327. "put test data for upload progress");
  9328. }
  9329. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9330. TestStringBodyUploadProgress(
  9331. [](Server &svr) {
  9332. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9333. res.set_content("patch received", "text/plain");
  9334. });
  9335. },
  9336. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9337. return cli.Patch("/test", body, "text/plain", progress_callback);
  9338. },
  9339. "patch test data for upload progress");
  9340. }
  9341. // Helper function for content provider upload progress tests
  9342. template <typename SetupHandler, typename ClientCall>
  9343. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9344. ClientCall &&client_call) {
  9345. Server svr;
  9346. setup_handler(svr);
  9347. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9348. auto se = detail::scope_exit([&] {
  9349. svr.stop();
  9350. t.join();
  9351. });
  9352. svr.wait_until_ready();
  9353. Client cli(HOST, PORT);
  9354. vector<uint64_t> progress_values;
  9355. auto res =
  9356. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9357. progress_values.push_back(current);
  9358. return true;
  9359. });
  9360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9361. EXPECT_EQ(200, res->status);
  9362. EXPECT_FALSE(progress_values.empty());
  9363. }
  9364. TEST(UploadProgressTest, PostContentProviderProgress) {
  9365. TestContentProviderUploadProgress(
  9366. [](Server &svr) {
  9367. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9368. res.set_content("provider received", "text/plain");
  9369. });
  9370. },
  9371. [](Client &cli, UploadProgress progress_callback) {
  9372. return cli.Post(
  9373. "/test", 10,
  9374. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9375. sink.os << "test data";
  9376. return true;
  9377. },
  9378. "text/plain", progress_callback);
  9379. });
  9380. }
  9381. // Helper function for multipart upload progress tests
  9382. template <typename SetupHandler, typename ClientCall>
  9383. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9384. ClientCall &&client_call,
  9385. const string &endpoint) {
  9386. Server svr;
  9387. setup_handler(svr);
  9388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9389. auto se = detail::scope_exit([&] {
  9390. svr.stop();
  9391. t.join();
  9392. });
  9393. svr.wait_until_ready();
  9394. Client cli(HOST, PORT);
  9395. vector<uint64_t> progress_values;
  9396. UploadFormDataItems items = {
  9397. {"field1", "value1", "", ""},
  9398. {"field2", "longer value for progress tracking test", "", ""},
  9399. {"file1", "file content data for upload progress", "test.txt",
  9400. "text/plain"}};
  9401. auto res = client_call(cli, endpoint, items,
  9402. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9403. progress_values.push_back(current);
  9404. return true;
  9405. });
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ(200, res->status);
  9408. EXPECT_FALSE(progress_values.empty());
  9409. }
  9410. TEST(UploadProgressTest, PostMultipartProgress) {
  9411. TestMultipartUploadProgress(
  9412. [](Server &svr) {
  9413. svr.Post("/multipart", [](const Request &req, Response &res) {
  9414. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9415. res.set_content("multipart received", "text/plain");
  9416. });
  9417. },
  9418. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9419. UploadProgress progress_callback) {
  9420. return cli.Post(endpoint, items, progress_callback);
  9421. },
  9422. "/multipart");
  9423. }
  9424. // Helper function for basic download progress tests
  9425. template <typename SetupHandler, typename ClientCall>
  9426. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9427. ClientCall &&client_call, const string &endpoint,
  9428. size_t expected_content_size) {
  9429. Server svr;
  9430. setup_handler(svr);
  9431. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9432. auto se = detail::scope_exit([&] {
  9433. svr.stop();
  9434. t.join();
  9435. });
  9436. svr.wait_until_ready();
  9437. Client cli(HOST, PORT);
  9438. vector<uint64_t> progress_values;
  9439. auto res = client_call(cli, endpoint,
  9440. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9441. progress_values.push_back(current);
  9442. return true;
  9443. });
  9444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9445. EXPECT_EQ(200, res->status);
  9446. EXPECT_FALSE(progress_values.empty());
  9447. EXPECT_EQ(expected_content_size, res->body.size());
  9448. }
  9449. TEST(DownloadProgressTest, GetBasic) {
  9450. TestBasicDownloadProgress(
  9451. [](Server &svr) {
  9452. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9453. string content(1000, 'D');
  9454. res.set_content(content, "text/plain");
  9455. });
  9456. },
  9457. [](Client &cli, const string &endpoint,
  9458. DownloadProgress progress_callback) {
  9459. return cli.Get(endpoint, progress_callback);
  9460. },
  9461. "/download", 1000u);
  9462. }
  9463. // Helper function for content receiver download progress tests
  9464. template <typename SetupHandler, typename ClientCall>
  9465. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9466. ClientCall &&client_call,
  9467. const string &endpoint,
  9468. size_t expected_content_size) {
  9469. Server svr;
  9470. setup_handler(svr);
  9471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9472. auto se = detail::scope_exit([&] {
  9473. svr.stop();
  9474. t.join();
  9475. });
  9476. svr.wait_until_ready();
  9477. Client cli(HOST, PORT);
  9478. vector<uint64_t> progress_values;
  9479. string received_body;
  9480. auto res = client_call(
  9481. cli, endpoint,
  9482. [&](const char *data, size_t data_length) -> bool {
  9483. received_body.append(data, data_length);
  9484. return true;
  9485. },
  9486. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9487. progress_values.push_back(current);
  9488. return true;
  9489. });
  9490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9491. EXPECT_EQ(200, res->status);
  9492. EXPECT_FALSE(progress_values.empty());
  9493. EXPECT_EQ(expected_content_size, received_body.size());
  9494. EXPECT_TRUE(res->body.empty());
  9495. }
  9496. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9497. TestContentReceiverDownloadProgress(
  9498. [](Server &svr) {
  9499. svr.Get("/download-receiver",
  9500. [](const Request & /*req*/, Response &res) {
  9501. string content(2000, 'R');
  9502. res.set_content(content, "text/plain");
  9503. });
  9504. },
  9505. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9506. DownloadProgress progress_callback) {
  9507. return cli.Get(endpoint, content_receiver, progress_callback);
  9508. },
  9509. "/download-receiver", 2000u);
  9510. }
  9511. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9512. // A provider reaching a pass with nothing to hand over - an empty buffer
  9513. // popped off a queue, say - must not be taken to mean the body is finished.
  9514. // It used to end the loop with the terminating chunk unwritten while the
  9515. // server still considered the response complete, so the peer waited for an
  9516. // end that never arrived.
  9517. Server svr;
  9518. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9519. auto step = std::make_shared<int>(0);
  9520. res.set_chunked_content_provider("text/plain",
  9521. [step](size_t /*offset*/, DataSink &sink) {
  9522. switch ((*step)++) {
  9523. case 0: sink.write("", 0); break;
  9524. case 1: sink.write("hello", 5); break;
  9525. default: sink.done(); break;
  9526. }
  9527. return true;
  9528. });
  9529. });
  9530. auto port = svr.bind_to_any_port(HOST);
  9531. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9532. auto listen_se = detail::scope_exit([&] {
  9533. svr.stop();
  9534. listen_thread.join();
  9535. ASSERT_FALSE(svr.is_running());
  9536. });
  9537. svr.wait_until_ready();
  9538. Client cli(HOST, port);
  9539. // Without the fix the body is never terminated, so bound the wait rather
  9540. // than letting the test hang on the default read timeout.
  9541. cli.set_read_timeout(5, 0);
  9542. auto res = cli.Get("/stream");
  9543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9544. EXPECT_EQ(StatusCode::OK_200, res->status);
  9545. EXPECT_EQ("hello", res->body);
  9546. }
  9547. TEST(StreamingTest, NoContentLengthStreaming) {
  9548. Server svr;
  9549. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9550. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9551. if (offset < 6) {
  9552. sink.os << (offset < 3 ? "a" : "b");
  9553. } else {
  9554. sink.done();
  9555. }
  9556. return true;
  9557. });
  9558. });
  9559. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9560. auto listen_se = detail::scope_exit([&] {
  9561. svr.stop();
  9562. listen_thread.join();
  9563. ASSERT_FALSE(svr.is_running());
  9564. });
  9565. svr.wait_until_ready();
  9566. Client client(HOST, PORT);
  9567. auto get_thread = std::thread([&client]() {
  9568. std::string s;
  9569. auto res =
  9570. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9571. s += std::string(data, len);
  9572. return true;
  9573. });
  9574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. EXPECT_EQ("aaabbb", s);
  9577. });
  9578. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9579. // Give GET time to get a few messages.
  9580. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9581. }
  9582. TEST(MountTest, Unmount) {
  9583. Server svr;
  9584. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9585. auto se = detail::scope_exit([&] {
  9586. svr.stop();
  9587. listen_thread.join();
  9588. ASSERT_FALSE(svr.is_running());
  9589. });
  9590. svr.wait_until_ready();
  9591. Client cli("localhost", PORT);
  9592. svr.set_mount_point("/mount2", "./www2");
  9593. auto res = cli.Get("/");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9596. res = cli.Get("/mount2/dir/test.html");
  9597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9598. EXPECT_EQ(StatusCode::OK_200, res->status);
  9599. svr.set_mount_point("/", "./www");
  9600. res = cli.Get("/dir/");
  9601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9602. EXPECT_EQ(StatusCode::OK_200, res->status);
  9603. svr.remove_mount_point("/");
  9604. res = cli.Get("/dir/");
  9605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9606. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9607. svr.remove_mount_point("/mount2");
  9608. res = cli.Get("/mount2/dir/test.html");
  9609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9610. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9611. }
  9612. TEST(MountTest, PathSegmentBoundary) {
  9613. Server svr;
  9614. svr.set_mount_point("/mount2", "./www2");
  9615. svr.set_mount_point("/", "./www");
  9616. auto port = svr.bind_to_any_port(HOST);
  9617. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9618. auto se = detail::scope_exit([&] {
  9619. svr.stop();
  9620. listen_thread.join();
  9621. ASSERT_FALSE(svr.is_running());
  9622. });
  9623. svr.wait_until_ready();
  9624. Client cli(HOST, port);
  9625. auto res = cli.Get("/mount2/dir/test.html");
  9626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9627. EXPECT_EQ(StatusCode::OK_200, res->status);
  9628. // "/mount2" must not match part-way through a path segment.
  9629. res = cli.Get("/mount2dir/test.html");
  9630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9631. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9632. // A mount point ending in '/' keeps matching every path below it.
  9633. res = cli.Get("/dir/test.html");
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_EQ(StatusCode::OK_200, res->status);
  9636. }
  9637. TEST(MountTest, Redicect) {
  9638. Server svr;
  9639. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9640. auto se = detail::scope_exit([&] {
  9641. svr.stop();
  9642. listen_thread.join();
  9643. ASSERT_FALSE(svr.is_running());
  9644. });
  9645. svr.set_mount_point("/", "./www");
  9646. svr.wait_until_ready();
  9647. Client cli("localhost", PORT);
  9648. auto res = cli.Get("/dir/");
  9649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9650. EXPECT_EQ(StatusCode::OK_200, res->status);
  9651. res = cli.Get("/dir");
  9652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9653. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9654. res = cli.Get("/file");
  9655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9656. EXPECT_EQ(StatusCode::OK_200, res->status);
  9657. res = cli.Get("/file/");
  9658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9659. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9660. cli.set_follow_location(true);
  9661. res = cli.Get("/dir");
  9662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9663. EXPECT_EQ(StatusCode::OK_200, res->status);
  9664. }
  9665. TEST(MountTest, MultibytesPathName) {
  9666. Server svr;
  9667. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9668. auto se = detail::scope_exit([&] {
  9669. svr.stop();
  9670. listen_thread.join();
  9671. ASSERT_FALSE(svr.is_running());
  9672. });
  9673. svr.set_mount_point("/", "./www");
  9674. svr.wait_until_ready();
  9675. Client cli("localhost", PORT);
  9676. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9678. EXPECT_EQ(StatusCode::OK_200, res->status);
  9679. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9680. }
  9681. #ifdef _WIN32
  9682. // Issue #2435: mmap::open() must succeed even when another handle holds
  9683. // the file open for writing (e.g. an active log file).
  9684. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9685. const char *path = "mmap_concurrent_writer_test.txt";
  9686. const char *content = "hello";
  9687. {
  9688. std::ofstream f(path, std::ios::binary);
  9689. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9690. }
  9691. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9692. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9693. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9694. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9695. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9696. detail::mmap m(path);
  9697. ASSERT_TRUE(m.is_open());
  9698. EXPECT_EQ(strlen(content), m.size());
  9699. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9700. }
  9701. #endif
  9702. #ifndef _WIN32
  9703. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9704. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9705. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9706. TEST(MmapTest, FailedMappingIsNotOpen) {
  9707. const char *path = "./mmap_failed_mapping_test_dir";
  9708. ASSERT_EQ(0, ::mkdir(path, 0755));
  9709. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9710. detail::mmap m(path);
  9711. EXPECT_FALSE(m.is_open());
  9712. EXPECT_EQ(0U, m.size());
  9713. EXPECT_NE(static_cast<const void *>(m.data()),
  9714. static_cast<const void *>(MAP_FAILED));
  9715. }
  9716. #endif
  9717. TEST(KeepAliveTest, ReadTimeout) {
  9718. Server svr;
  9719. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9720. std::this_thread::sleep_for(std::chrono::seconds(2));
  9721. res.set_content("a", "text/plain");
  9722. });
  9723. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9724. res.set_content("b", "text/plain");
  9725. });
  9726. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9727. auto se = detail::scope_exit([&] {
  9728. svr.stop();
  9729. listen_thread.join();
  9730. ASSERT_FALSE(svr.is_running());
  9731. });
  9732. svr.wait_until_ready();
  9733. Client cli("localhost", PORT);
  9734. cli.set_keep_alive(true);
  9735. cli.set_read_timeout(std::chrono::seconds(1));
  9736. auto resa = cli.Get("/a");
  9737. ASSERT_FALSE(resa);
  9738. EXPECT_EQ(Error::Read, resa.error());
  9739. auto resb = cli.Get("/b");
  9740. ASSERT_TRUE(resb);
  9741. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9742. EXPECT_EQ("b", resb->body);
  9743. }
  9744. TEST(KeepAliveTest, MaxCount) {
  9745. size_t keep_alive_max_count = 3;
  9746. Server svr;
  9747. svr.set_keep_alive_max_count(keep_alive_max_count);
  9748. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9749. res.set_content("Hello World!", "text/plain");
  9750. });
  9751. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9752. auto se = detail::scope_exit([&] {
  9753. svr.stop();
  9754. listen_thread.join();
  9755. ASSERT_FALSE(svr.is_running());
  9756. });
  9757. svr.wait_until_ready();
  9758. Client cli(HOST, PORT);
  9759. cli.set_keep_alive(true);
  9760. for (size_t i = 0; i < 5; i++) {
  9761. auto result = cli.Get("/hi");
  9762. ASSERT_TRUE(result);
  9763. EXPECT_EQ(StatusCode::OK_200, result->status);
  9764. if (i == keep_alive_max_count - 1) {
  9765. EXPECT_EQ("close", result->get_header_value("Connection"));
  9766. } else {
  9767. EXPECT_FALSE(result->has_header("Connection"));
  9768. }
  9769. }
  9770. }
  9771. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9772. // can pull the next one into the server's buffer. The server must serve it
  9773. // without waiting for the socket to become readable again. The keep-alive
  9774. // timeout outlasts the client's read timeout, so a request left waiting for it
  9775. // shows up as a missing response.
  9776. static void serve_pipelining_routes(Server &svr,
  9777. const std::function<void(int)> &client) {
  9778. svr.set_keep_alive_timeout(5);
  9779. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9780. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9781. });
  9782. svr.Post("/echo", [](const Request &req, Response &res) {
  9783. res.set_content("echo " + req.body, "text/plain");
  9784. });
  9785. auto port = svr.bind_to_any_port(HOST);
  9786. thread t = thread([&] { svr.listen_after_bind(); });
  9787. auto se = detail::scope_exit([&] {
  9788. svr.stop();
  9789. t.join();
  9790. });
  9791. svr.wait_until_ready();
  9792. client(port);
  9793. }
  9794. static std::string
  9795. send_pipelined_requests(const std::vector<std::string> &parts) {
  9796. Server svr;
  9797. std::string res;
  9798. serve_pipelining_routes(svr, [&](int port) {
  9799. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9800. });
  9801. return res;
  9802. }
  9803. static void expect_in_order(const std::string &res,
  9804. const std::vector<std::string> &bodies) {
  9805. size_t pos = 0;
  9806. for (const auto &body : bodies) {
  9807. pos = res.find(body, pos);
  9808. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9809. pos += body.size();
  9810. }
  9811. }
  9812. TEST(KeepAliveTest, PipelinedRequests) {
  9813. auto res = send_pipelined_requests(
  9814. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9815. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9816. "Content-Length: 4\r\n\r\nbody"
  9817. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9818. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9819. }
  9820. // The second request starts in the server's buffer and ends on the socket.
  9821. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9822. auto res =
  9823. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9824. "GET /hi/2 HTTP/1.1\r\nHo",
  9825. "st: localhost\r\nConnection: close\r\n\r\n"});
  9826. expect_in_order(res, {"hi 1", "hi 2"});
  9827. }
  9828. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9829. // CRLF after a body does not turn into a 400 for the next request.
  9830. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9831. auto res = send_pipelined_requests(
  9832. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9833. "Content-Length: 4\r\n\r\nbody\r\n"
  9834. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9835. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9836. expect_in_order(res, {"echo body", "hi 2"});
  9837. }
  9838. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9839. // must not be served as the next request.
  9840. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9841. auto res = send_pipelined_requests(
  9842. {"INVALID REQUEST LINE\r\n\r\n"
  9843. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9844. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9845. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9846. }
  9847. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9848. // Over TLS, the next request is held by the TLS library as already decrypted
  9849. // data rather than on the socket.
  9850. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9852. std::string res;
  9853. serve_pipelining_routes(svr, [&](int port) {
  9854. auto error = Error::Success;
  9855. auto sock = detail::create_client_socket(
  9856. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9857. /*connection_timeout_sec=*/5, 0,
  9858. /*read_timeout_sec=*/2, 0,
  9859. /*write_timeout_sec=*/5, 0, std::string(), error);
  9860. ASSERT_NE(INVALID_SOCKET, sock);
  9861. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9862. auto ctx = SSL_CTX_new(TLS_client_method());
  9863. auto ssl = SSL_new(ctx);
  9864. auto ssl_se = detail::scope_exit([&] {
  9865. SSL_free(ssl);
  9866. SSL_CTX_free(ctx);
  9867. });
  9868. SSL_set_fd(ssl, static_cast<int>(sock));
  9869. ASSERT_EQ(1, SSL_connect(ssl));
  9870. // One write, so all three requests arrive in one TLS record
  9871. const std::string req =
  9872. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9873. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9874. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9875. ASSERT_EQ(static_cast<int>(req.size()),
  9876. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9877. char buf[512];
  9878. int n;
  9879. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9880. res.append(buf, static_cast<size_t>(n));
  9881. }
  9882. });
  9883. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9884. }
  9885. #endif
  9886. TEST(KeepAliveTest, Issue1041) {
  9887. Server svr;
  9888. svr.set_keep_alive_timeout(3);
  9889. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9890. res.set_content("Hello World!", "text/plain");
  9891. });
  9892. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9893. auto se = detail::scope_exit([&] {
  9894. svr.stop();
  9895. listen_thread.join();
  9896. ASSERT_FALSE(svr.is_running());
  9897. });
  9898. svr.wait_until_ready();
  9899. Client cli(HOST, PORT);
  9900. cli.set_keep_alive(true);
  9901. auto result = cli.Get("/hi");
  9902. ASSERT_TRUE(result);
  9903. EXPECT_EQ(StatusCode::OK_200, result->status);
  9904. std::this_thread::sleep_for(std::chrono::seconds(5));
  9905. result = cli.Get("/hi");
  9906. ASSERT_TRUE(result);
  9907. EXPECT_EQ(StatusCode::OK_200, result->status);
  9908. }
  9909. TEST(KeepAliveTest, Issue1959) {
  9910. Server svr;
  9911. svr.set_keep_alive_timeout(5);
  9912. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9913. res.set_content("a", "text/plain");
  9914. });
  9915. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9916. auto se = detail::scope_exit([&] {
  9917. if (!svr.is_running()) return;
  9918. svr.stop();
  9919. listen_thread.join();
  9920. ASSERT_FALSE(svr.is_running());
  9921. });
  9922. svr.wait_until_ready();
  9923. Client cli("localhost", PORT);
  9924. cli.set_keep_alive(true);
  9925. using namespace std::chrono;
  9926. auto start = steady_clock::now();
  9927. cli.Get("/a");
  9928. svr.stop();
  9929. listen_thread.join();
  9930. auto end = steady_clock::now();
  9931. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9932. EXPECT_LT(elapsed, 5000);
  9933. }
  9934. #ifdef CPPHTTPLIB_SSL_ENABLED
  9935. TEST(KeepAliveTest, SSLClientReconnection) {
  9936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9937. ASSERT_TRUE(svr.is_valid());
  9938. svr.set_keep_alive_timeout(1);
  9939. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9940. res.set_content("Hello World!", "text/plain");
  9941. });
  9942. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9943. auto se = detail::scope_exit([&] {
  9944. svr.stop();
  9945. listen_thread.join();
  9946. ASSERT_FALSE(svr.is_running());
  9947. });
  9948. svr.wait_until_ready();
  9949. SSLClient cli(HOST, PORT);
  9950. cli.enable_server_certificate_verification(false);
  9951. cli.set_keep_alive(true);
  9952. auto result = cli.Get("/hi");
  9953. ASSERT_TRUE(result);
  9954. EXPECT_EQ(StatusCode::OK_200, result->status);
  9955. result = cli.Get("/hi");
  9956. ASSERT_TRUE(result);
  9957. EXPECT_EQ(StatusCode::OK_200, result->status);
  9958. std::this_thread::sleep_for(std::chrono::seconds(2));
  9959. // Recoonect
  9960. result = cli.Get("/hi");
  9961. ASSERT_TRUE(result);
  9962. EXPECT_EQ(StatusCode::OK_200, result->status);
  9963. result = cli.Get("/hi");
  9964. ASSERT_TRUE(result);
  9965. EXPECT_EQ(StatusCode::OK_200, result->status);
  9966. }
  9967. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9969. ASSERT_TRUE(svr.is_valid());
  9970. svr.set_keep_alive_timeout(1);
  9971. std::string content = "reconnect";
  9972. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9973. res.set_content("Hello World!", "text/plain");
  9974. });
  9975. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9976. auto se = detail::scope_exit([&] {
  9977. svr.stop();
  9978. listen_thread.join();
  9979. ASSERT_FALSE(svr.is_running());
  9980. });
  9981. svr.wait_until_ready();
  9982. SSLClient cli(HOST, PORT);
  9983. cli.enable_server_certificate_verification(false);
  9984. cli.set_keep_alive(true);
  9985. auto result = cli.Post(
  9986. "/hi", content.size(),
  9987. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9988. sink.write(content.c_str(), content.size());
  9989. return true;
  9990. },
  9991. "text/plain");
  9992. ASSERT_TRUE(result);
  9993. EXPECT_EQ(200, result->status);
  9994. std::this_thread::sleep_for(std::chrono::seconds(2));
  9995. // Recoonect
  9996. result = cli.Post(
  9997. "/hi", content.size(),
  9998. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9999. sink.write(content.c_str(), content.size());
  10000. return true;
  10001. },
  10002. "text/plain");
  10003. ASSERT_TRUE(result);
  10004. EXPECT_EQ(200, result->status);
  10005. result = cli.Post(
  10006. "/hi", content.size(),
  10007. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10008. sink.write(content.c_str(), content.size());
  10009. return true;
  10010. },
  10011. "text/plain");
  10012. ASSERT_TRUE(result);
  10013. EXPECT_EQ(200, result->status);
  10014. }
  10015. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10016. using namespace httplib::tls;
  10017. {
  10018. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10019. ASSERT_TRUE(svr.is_valid());
  10020. svr.Get("/sni", [&](const Request &req, Response &res) {
  10021. std::string expected = req.sni();
  10022. EXPECT_EQ(expected, req.get_param_value("expected"));
  10023. res.set_content("ok", "text/plain");
  10024. });
  10025. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10026. auto se = detail::scope_exit([&] {
  10027. svr.stop();
  10028. listen_thread.join();
  10029. ASSERT_FALSE(svr.is_running());
  10030. });
  10031. svr.wait_until_ready();
  10032. {
  10033. SSLClient cli("localhost", PORT);
  10034. cli.enable_server_certificate_verification(false);
  10035. auto res = cli.Get("/sni?expected=localhost");
  10036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10037. }
  10038. {
  10039. SSLClient cli("::1", PORT);
  10040. cli.enable_server_certificate_verification(false);
  10041. auto res = cli.Get("/sni?expected=");
  10042. // NOTE: This may fail if the server is listening on IPv4 only
  10043. // (e.g., when localhost resolves to 127.0.0.1 only)
  10044. if (res) {
  10045. EXPECT_EQ(StatusCode::OK_200, res->status);
  10046. } else {
  10047. EXPECT_EQ(Error::Connection, res.error());
  10048. }
  10049. }
  10050. }
  10051. }
  10052. #endif
  10053. TEST(ClientProblemDetectionTest, ContentProvider) {
  10054. Server svr;
  10055. size_t content_length = 1024 * 1024;
  10056. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10057. res.set_content_provider(
  10058. content_length, "text/plain",
  10059. [&](size_t offset, size_t length, DataSink &sink) {
  10060. auto out_len = std::min(length, static_cast<size_t>(1024));
  10061. std::string out(out_len, '@');
  10062. sink.write(out.data(), out_len);
  10063. return offset < 4096;
  10064. },
  10065. [](bool success) { ASSERT_FALSE(success); });
  10066. });
  10067. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10068. res.set_content_provider(
  10069. 0, "text/plain",
  10070. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10071. EXPECT_TRUE(false);
  10072. return true;
  10073. },
  10074. [](bool success) { ASSERT_FALSE(success); });
  10075. });
  10076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10077. auto se = detail::scope_exit([&] {
  10078. svr.stop();
  10079. listen_thread.join();
  10080. ASSERT_FALSE(svr.is_running());
  10081. });
  10082. svr.wait_until_ready();
  10083. Client cli("localhost", PORT);
  10084. {
  10085. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10086. size_t /*data_length*/) { return false; });
  10087. ASSERT_FALSE(res);
  10088. }
  10089. {
  10090. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10091. size_t /*data_length*/) { return false; });
  10092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10093. }
  10094. }
  10095. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10096. // A provider that reports success without writing anything and without
  10097. // calling done() used to be handed the same offset and length again on every
  10098. // pass, so it spun for as long as the peer stayed connected.
  10099. Server svr;
  10100. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10101. res.set_content("ok", "text/plain");
  10102. });
  10103. auto port = svr.bind_to_any_port(HOST);
  10104. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10105. auto se = detail::scope_exit([&] {
  10106. svr.stop();
  10107. listen_thread.join();
  10108. ASSERT_FALSE(svr.is_running());
  10109. });
  10110. svr.wait_until_ready();
  10111. std::atomic<int> call_count{0};
  10112. Client cli(HOST, port);
  10113. auto res = cli.Post(
  10114. "/", 1024,
  10115. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10116. // Give up after enough passes to show the spin, so that losing the
  10117. // check below fails this test instead of hanging it.
  10118. return ++call_count < 100;
  10119. },
  10120. "text/plain");
  10121. ASSERT_FALSE(res);
  10122. EXPECT_EQ(Error::Write, res.error());
  10123. EXPECT_EQ(1, call_count.load());
  10124. }
  10125. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10126. // A writer only has to assign `write`. The other three used to be left as
  10127. // empty std::functions, so a provider calling one threw
  10128. // std::bad_function_call out of the thread running it and took the whole
  10129. // process down.
  10130. DataSink sink;
  10131. std::string written;
  10132. sink.write = [&](const char *data, size_t data_len) {
  10133. written.append(data, data_len);
  10134. return true;
  10135. };
  10136. EXPECT_TRUE(sink.is_writable());
  10137. sink.done();
  10138. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10139. EXPECT_TRUE(written.empty());
  10140. }
  10141. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10142. // A sink that cannot carry trailers still has to finish.
  10143. DataSink sink;
  10144. auto done_count = 0;
  10145. sink.done = [&]() { done_count++; };
  10146. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10147. EXPECT_EQ(1, done_count);
  10148. }
  10149. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10150. Server svr;
  10151. const std::string body(4096, 'x');
  10152. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10153. res.set_content_provider(body.size(), "text/plain",
  10154. [&](size_t offset, size_t length, DataSink &sink) {
  10155. sink.write(body.data() + offset, length);
  10156. sink.done();
  10157. return true;
  10158. });
  10159. });
  10160. auto port = svr.bind_to_any_port(HOST);
  10161. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10162. auto se = detail::scope_exit([&] {
  10163. svr.stop();
  10164. listen_thread.join();
  10165. ASSERT_FALSE(svr.is_running());
  10166. });
  10167. svr.wait_until_ready();
  10168. Client cli(HOST, port);
  10169. auto res = cli.Get("/");
  10170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10171. EXPECT_EQ(StatusCode::OK_200, res->status);
  10172. EXPECT_EQ(body, res->body);
  10173. }
  10174. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10175. Server svr;
  10176. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10177. res.set_content_provider(
  10178. 1024, "text/plain",
  10179. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10180. sink.write("hello", 5);
  10181. sink.done(); // short of the 1024 bytes the response promised
  10182. return true;
  10183. });
  10184. });
  10185. auto port = svr.bind_to_any_port(HOST);
  10186. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10187. auto se = detail::scope_exit([&] {
  10188. svr.stop();
  10189. listen_thread.join();
  10190. ASSERT_FALSE(svr.is_running());
  10191. });
  10192. svr.wait_until_ready();
  10193. Client cli(HOST, port);
  10194. cli.set_read_timeout(5, 0);
  10195. // The response is short of its Content-Length, so the client cannot read a
  10196. // complete body. What matters is that this returns at all: a no-op done()
  10197. // would leave the writer looping over a provider that never makes progress.
  10198. auto res = cli.Get("/");
  10199. EXPECT_FALSE(res);
  10200. }
  10201. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10202. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10203. // The compressed path builds the whole body before connecting, so this
  10204. // fails client-side and never reaches a server.
  10205. Client cli(HOST, PORT);
  10206. cli.set_compress(true);
  10207. auto res = cli.Post(
  10208. "/", 1024,
  10209. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10210. sink.write("hello", 5);
  10211. sink.done(); // short of the 1024 bytes the request announced
  10212. return true;
  10213. },
  10214. "text/plain");
  10215. ASSERT_FALSE(res);
  10216. EXPECT_EQ(Error::Write, res.error());
  10217. }
  10218. #endif
  10219. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10220. Server svr;
  10221. svr.set_error_handler([](Request const &, Response &res) -> void {
  10222. res.set_chunked_content_provider(
  10223. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10224. sink.os << "hello";
  10225. sink.os << "world";
  10226. sink.done();
  10227. return true;
  10228. });
  10229. });
  10230. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10231. auto se = detail::scope_exit([&] {
  10232. svr.stop();
  10233. listen_thread.join();
  10234. ASSERT_FALSE(svr.is_running());
  10235. });
  10236. svr.wait_until_ready();
  10237. Client cli("localhost", PORT);
  10238. auto res = cli.Get("/");
  10239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10240. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10241. EXPECT_EQ("helloworld", res->body);
  10242. }
  10243. TEST(LongPollingTest, ClientCloseDetection) {
  10244. Server svr;
  10245. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10246. res.set_chunked_content_provider(
  10247. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10248. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10249. sink.os << "hello";
  10250. auto count = 10;
  10251. while (count > 0 && sink.is_writable()) {
  10252. this_thread::sleep_for(chrono::milliseconds(10));
  10253. count--;
  10254. }
  10255. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10256. return true;
  10257. });
  10258. });
  10259. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10260. auto se = detail::scope_exit([&] {
  10261. svr.stop();
  10262. listen_thread.join();
  10263. ASSERT_FALSE(svr.is_running());
  10264. });
  10265. svr.wait_until_ready();
  10266. Client cli("localhost", PORT);
  10267. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10268. EXPECT_EQ("hello", string(data, data_length));
  10269. return false; // close the socket immediately.
  10270. });
  10271. ASSERT_FALSE(res);
  10272. }
  10273. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10274. Server svr;
  10275. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10276. res.set_chunked_content_provider(
  10277. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10278. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10279. sink.os << "hello";
  10280. EXPECT_TRUE(sink.os.good());
  10281. // Wait for the client to close the connection
  10282. auto count = 10;
  10283. while (count > 0 && sink.is_writable()) {
  10284. this_thread::sleep_for(chrono::milliseconds(10));
  10285. count--;
  10286. }
  10287. // After client disconnect, write repeatedly until the socket
  10288. // write actually fails (small writes may be absorbed by the
  10289. // kernel buffer)
  10290. std::string chunk(1024, 'x');
  10291. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10292. sink.os << chunk;
  10293. }
  10294. EXPECT_TRUE(sink.os.fail());
  10295. return true;
  10296. });
  10297. });
  10298. auto port = svr.bind_to_any_port("localhost");
  10299. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. listen_thread.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. Client cli("localhost", port);
  10307. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10308. EXPECT_EQ("hello", string(data, data_length));
  10309. return false; // close the socket immediately.
  10310. });
  10311. ASSERT_FALSE(res);
  10312. }
  10313. TEST(GetWithParametersTest, GetWithParameters) {
  10314. Server svr;
  10315. svr.Get("/", [&](const Request &req, Response &) {
  10316. EXPECT_EQ("world", req.get_param_value("hello"));
  10317. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10318. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10319. });
  10320. svr.Get("/params", [&](const Request &req, Response &) {
  10321. EXPECT_EQ("world", req.get_param_value("hello"));
  10322. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10323. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10324. });
  10325. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10326. EXPECT_EQ("resource-id", req.matches[1]);
  10327. EXPECT_EQ("foo", req.get_param_value("param1"));
  10328. EXPECT_EQ("bar", req.get_param_value("param2"));
  10329. });
  10330. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10331. EXPECT_EQ("user-id", req.path_params.at("id"));
  10332. EXPECT_EQ("foo", req.get_param_value("param1"));
  10333. EXPECT_EQ("bar", req.get_param_value("param2"));
  10334. });
  10335. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10336. auto se = detail::scope_exit([&] {
  10337. svr.stop();
  10338. listen_thread.join();
  10339. ASSERT_FALSE(svr.is_running());
  10340. });
  10341. svr.wait_until_ready();
  10342. {
  10343. Client cli(HOST, PORT);
  10344. Params params;
  10345. params.emplace("hello", "world");
  10346. params.emplace("hello2", "world2");
  10347. params.emplace("hello3", "world3");
  10348. auto res = cli.Get("/", params, Headers{});
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(StatusCode::OK_200, res->status);
  10351. }
  10352. {
  10353. Client cli(HOST, PORT);
  10354. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10356. EXPECT_EQ(StatusCode::OK_200, res->status);
  10357. }
  10358. {
  10359. Client cli(HOST, PORT);
  10360. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10362. EXPECT_EQ(StatusCode::OK_200, res->status);
  10363. }
  10364. {
  10365. Client cli(HOST, PORT);
  10366. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10368. EXPECT_EQ(StatusCode::OK_200, res->status);
  10369. }
  10370. }
  10371. TEST(GetWithParametersTest, GetWithParameters2) {
  10372. Server svr;
  10373. svr.Get("/", [&](const Request &req, Response &res) {
  10374. auto text = req.get_param_value("hello");
  10375. res.set_content(text, "text/plain");
  10376. });
  10377. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. listen_thread.join();
  10381. ASSERT_FALSE(svr.is_running());
  10382. });
  10383. svr.wait_until_ready();
  10384. Client cli("localhost", PORT);
  10385. Params params;
  10386. params.emplace("hello", "world");
  10387. std::string body;
  10388. auto res = cli.Get("/", params, Headers{},
  10389. [&](const char *data, size_t data_length) {
  10390. body.append(data, data_length);
  10391. return true;
  10392. });
  10393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10394. EXPECT_EQ(StatusCode::OK_200, res->status);
  10395. EXPECT_EQ("world", body);
  10396. }
  10397. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10398. Server svr;
  10399. svr.Get("/search", [&](const Request &req, Response &res) {
  10400. auto q = req.get_param_value("q");
  10401. res.set_content(q, "text/plain");
  10402. });
  10403. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10404. auto se = detail::scope_exit([&] {
  10405. svr.stop();
  10406. listen_thread.join();
  10407. ASSERT_FALSE(svr.is_running());
  10408. });
  10409. svr.wait_until_ready();
  10410. Client cli("localhost", PORT);
  10411. // Verify that Get(path, params) works without requiring Headers argument
  10412. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10414. EXPECT_EQ(StatusCode::OK_200, res->status);
  10415. EXPECT_EQ("cpp-httplib", res->body);
  10416. }
  10417. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10418. auto host = "httpbingo.org";
  10419. auto path = std::string{"/range/32"};
  10420. #ifdef CPPHTTPLIB_SSL_ENABLED
  10421. SSLClient cli(host);
  10422. #else
  10423. Client cli(host);
  10424. #endif
  10425. cli.set_default_headers({make_range_header({{1, 10}})});
  10426. cli.set_connection_timeout(5);
  10427. {
  10428. auto res = cli.Get(path);
  10429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10430. EXPECT_EQ("bcdefghijk", res->body);
  10431. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10432. }
  10433. {
  10434. auto res = cli.Get(path);
  10435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10436. EXPECT_EQ("bcdefghijk", res->body);
  10437. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10438. }
  10439. }
  10440. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10441. Server svr;
  10442. svr.set_default_headers({{"Hello", "World"}});
  10443. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10444. res.set_content("ok", "text/plain");
  10445. });
  10446. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10447. auto se = detail::scope_exit([&] {
  10448. svr.stop();
  10449. listen_thread.join();
  10450. ASSERT_FALSE(svr.is_running());
  10451. });
  10452. svr.wait_until_ready();
  10453. Client cli("localhost", PORT);
  10454. auto res = cli.Get("/");
  10455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10456. EXPECT_EQ(StatusCode::OK_200, res->status);
  10457. EXPECT_EQ("ok", res->body);
  10458. EXPECT_EQ("World", res->get_header_value("Hello"));
  10459. }
  10460. #ifdef CPPHTTPLIB_SSL_ENABLED
  10461. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10462. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10463. ASSERT_TRUE(svr.is_valid());
  10464. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10465. std::this_thread::sleep_for(std::chrono::seconds(2));
  10466. res.set_content("a", "text/plain");
  10467. });
  10468. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10469. res.set_content("b", "text/plain");
  10470. });
  10471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10472. auto se = detail::scope_exit([&] {
  10473. svr.stop();
  10474. listen_thread.join();
  10475. ASSERT_FALSE(svr.is_running());
  10476. });
  10477. svr.wait_until_ready();
  10478. SSLClient cli("localhost", PORT);
  10479. cli.enable_server_certificate_verification(false);
  10480. cli.set_keep_alive(true);
  10481. cli.set_read_timeout(std::chrono::seconds(1));
  10482. auto resa = cli.Get("/a");
  10483. ASSERT_TRUE(!resa);
  10484. EXPECT_EQ(Error::Read, resa.error());
  10485. auto resb = cli.Get("/b");
  10486. ASSERT_TRUE(resb);
  10487. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10488. EXPECT_EQ("b", resb->body);
  10489. }
  10490. // Closing an idle keep-alive connection sends close_notify and returns. The
  10491. // server must not wait for the client's close_notify: an idle client never
  10492. // sends one, so the worker would be held until the read timeout expires, and
  10493. // stop() would wait for it.
  10494. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10496. ASSERT_TRUE(svr.is_valid());
  10497. svr.set_keep_alive_timeout(1);
  10498. svr.set_read_timeout(10, 0);
  10499. svr.Get("/", [](const Request &, Response &res) {
  10500. res.set_content("ok", "text/plain");
  10501. });
  10502. auto port = svr.bind_to_any_port(HOST);
  10503. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10504. auto se = detail::scope_exit([&] {
  10505. if (listen_thread.joinable()) {
  10506. svr.stop();
  10507. listen_thread.join();
  10508. }
  10509. });
  10510. svr.wait_until_ready();
  10511. SSLClient cli(HOST, port);
  10512. cli.enable_server_certificate_verification(false);
  10513. cli.set_keep_alive(true);
  10514. auto res = cli.Get("/");
  10515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10516. EXPECT_EQ(StatusCode::OK_200, res->status);
  10517. // Stay idle past the keep-alive timeout so the server closes the connection.
  10518. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10519. auto start = std::chrono::steady_clock::now();
  10520. svr.stop();
  10521. listen_thread.join();
  10522. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10523. std::chrono::steady_clock::now() - start)
  10524. .count();
  10525. EXPECT_LT(elapsed, 3000);
  10526. }
  10527. #endif
  10528. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10529. protected:
  10530. ServerTestWithAI_PASSIVE()
  10531. : cli_(HOST, PORT)
  10532. #ifdef CPPHTTPLIB_SSL_ENABLED
  10533. ,
  10534. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10535. #endif
  10536. {
  10537. #ifdef CPPHTTPLIB_SSL_ENABLED
  10538. cli_.enable_server_certificate_verification(false);
  10539. #endif
  10540. }
  10541. virtual void SetUp() {
  10542. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10543. res.set_content("Hello World!", "text/plain");
  10544. });
  10545. t_ = thread(
  10546. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10547. svr_.wait_until_ready();
  10548. }
  10549. virtual void TearDown() {
  10550. svr_.stop();
  10551. t_.join();
  10552. }
  10553. #ifdef CPPHTTPLIB_SSL_ENABLED
  10554. SSLClient cli_;
  10555. SSLServer svr_;
  10556. #else
  10557. Client cli_;
  10558. Server svr_;
  10559. #endif
  10560. thread t_;
  10561. };
  10562. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10563. auto res = cli_.Get("/hi");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::OK_200, res->status);
  10566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10567. EXPECT_EQ("Hello World!", res->body);
  10568. }
  10569. class ServerUpDownTest : public ::testing::Test {
  10570. protected:
  10571. ServerUpDownTest() : cli_(HOST, PORT) {}
  10572. virtual void SetUp() {
  10573. t_ = thread([&]() {
  10574. svr_.bind_to_any_port(HOST);
  10575. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10576. ASSERT_TRUE(svr_.listen_after_bind());
  10577. });
  10578. svr_.wait_until_ready();
  10579. }
  10580. virtual void TearDown() {
  10581. svr_.stop();
  10582. t_.join();
  10583. }
  10584. Client cli_;
  10585. Server svr_;
  10586. thread t_;
  10587. };
  10588. TEST_F(ServerUpDownTest, QuickStartStop) {
  10589. // Should not crash, especially when run with
  10590. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10591. }
  10592. class PayloadMaxLengthTest : public ::testing::Test {
  10593. protected:
  10594. PayloadMaxLengthTest()
  10595. : cli_(HOST, PORT)
  10596. #ifdef CPPHTTPLIB_SSL_ENABLED
  10597. ,
  10598. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10599. #endif
  10600. {
  10601. #ifdef CPPHTTPLIB_SSL_ENABLED
  10602. cli_.enable_server_certificate_verification(false);
  10603. #endif
  10604. }
  10605. virtual void SetUp() {
  10606. svr_.set_payload_max_length(8);
  10607. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10608. res.set_content("test", "text/plain");
  10609. });
  10610. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10611. svr_.wait_until_ready();
  10612. }
  10613. virtual void TearDown() {
  10614. svr_.stop();
  10615. t_.join();
  10616. }
  10617. #ifdef CPPHTTPLIB_SSL_ENABLED
  10618. SSLClient cli_;
  10619. SSLServer svr_;
  10620. #else
  10621. Client cli_;
  10622. Server svr_;
  10623. #endif
  10624. thread t_;
  10625. };
  10626. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10627. auto res = cli_.Post("/test", "123456789", "text/plain");
  10628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10629. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10630. res = cli_.Post("/test", "12345678", "text/plain");
  10631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10632. EXPECT_EQ(StatusCode::OK_200, res->status);
  10633. }
  10634. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10635. // Test chunked encoding with payload exceeding the 8-byte limit
  10636. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10637. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10639. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10640. }
  10641. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10642. // Test chunked encoding with payload within the 8-byte limit
  10643. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10644. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. EXPECT_EQ(StatusCode::OK_200, res->status);
  10647. }
  10648. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10649. // Test using send_request to send chunked data exceeding payload limit
  10650. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10651. "Host: " +
  10652. std::string(HOST) + ":" + std::to_string(PORT) +
  10653. "\r\n"
  10654. "Transfer-Encoding: chunked\r\n"
  10655. "Connection: close\r\n"
  10656. "\r\n"
  10657. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10658. "0123456789\r\n"
  10659. "0\r\n" // End chunk
  10660. "\r\n";
  10661. std::string response;
  10662. bool result = send_request(1, chunked_request, &response);
  10663. if (!result) {
  10664. // If send_request fails, it might be because the server closed the
  10665. // connection due to payload limit enforcement, which is acceptable
  10666. SUCCEED()
  10667. << "Server rejected oversized chunked request (connection closed)";
  10668. } else {
  10669. // If we got a response, check if it's an error response or connection was
  10670. // closed early Short response length indicates connection was closed due to
  10671. // payload limit
  10672. if (response.length() <= 10) {
  10673. SUCCEED() << "Server closed connection for oversized chunked request";
  10674. } else {
  10675. // Check for error status codes
  10676. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10677. response.find("Payload Too Large") != std::string::npos ||
  10678. response.find("400") != std::string::npos);
  10679. }
  10680. }
  10681. }
  10682. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10683. // Test request without Content-Length header exceeding payload limit
  10684. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10685. "Host: " +
  10686. std::string(HOST) + ":" +
  10687. std::to_string(PORT) +
  10688. "\r\n"
  10689. "Connection: close\r\n"
  10690. "\r\n";
  10691. // Add payload exceeding the 8-byte limit
  10692. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10693. request_without_content_length += large_payload;
  10694. std::string response;
  10695. bool result = send_request(1, request_without_content_length, &response);
  10696. if (!result) {
  10697. // If send_request fails, server likely closed connection due to payload
  10698. // limit
  10699. SUCCEED() << "Server rejected oversized request without Content-Length "
  10700. "(connection closed)";
  10701. } else {
  10702. // Check if server responded with error or closed connection early
  10703. if (response.length() <= 10) {
  10704. SUCCEED() << "Server closed connection for oversized request without "
  10705. "Content-Length";
  10706. } else {
  10707. // Check for error status codes
  10708. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10709. response.find("Payload Too Large") != std::string::npos ||
  10710. response.find("400") != std::string::npos);
  10711. }
  10712. }
  10713. }
  10714. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10715. // Test request without Content-Length header within payload limit
  10716. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10717. "Host: " +
  10718. std::string(HOST) + ":" +
  10719. std::to_string(PORT) +
  10720. "\r\n"
  10721. "Connection: close\r\n"
  10722. "\r\n";
  10723. // Add payload within the 8-byte limit
  10724. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10725. request_without_content_length += small_payload;
  10726. std::string response;
  10727. bool result = send_request(1, request_without_content_length, &response);
  10728. // For requests without Content-Length, the server may have different behavior
  10729. // The key is that it should not reject due to payload limit for small
  10730. // payloads
  10731. if (result) {
  10732. // Check for any HTTP response (success or error, but not connection closed)
  10733. if (response.length() > 10) {
  10734. SUCCEED()
  10735. << "Server processed request without Content-Length within limit";
  10736. } else {
  10737. // Short response might indicate connection closed, which is acceptable
  10738. SUCCEED() << "Server closed connection for request without "
  10739. "Content-Length (acceptable behavior)";
  10740. }
  10741. } else {
  10742. // Connection failure might be due to protocol requirements
  10743. SUCCEED() << "Connection issue with request without Content-Length "
  10744. "(environment-specific)";
  10745. }
  10746. }
  10747. class LargePayloadMaxLengthTest : public ::testing::Test {
  10748. protected:
  10749. LargePayloadMaxLengthTest()
  10750. : cli_(HOST, PORT)
  10751. #ifdef CPPHTTPLIB_SSL_ENABLED
  10752. ,
  10753. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10754. #endif
  10755. {
  10756. #ifdef CPPHTTPLIB_SSL_ENABLED
  10757. cli_.enable_server_certificate_verification(false);
  10758. #endif
  10759. }
  10760. virtual void SetUp() {
  10761. // Set 10MB payload limit
  10762. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10763. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10764. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10765. res.set_content("Large payload test", "text/plain");
  10766. });
  10767. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10768. svr_.wait_until_ready();
  10769. }
  10770. virtual void TearDown() {
  10771. svr_.stop();
  10772. t_.join();
  10773. }
  10774. #ifdef CPPHTTPLIB_SSL_ENABLED
  10775. SSLClient cli_;
  10776. SSLServer svr_;
  10777. #else
  10778. Client cli_;
  10779. Server svr_;
  10780. #endif
  10781. thread t_;
  10782. };
  10783. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10784. // Test chunked encoding with payload within 10MB limit
  10785. std::string medium_payload(5 * 1024 * 1024,
  10786. 'A'); // 5MB payload, within 10MB limit
  10787. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10789. EXPECT_EQ(StatusCode::OK_200, res->status);
  10790. }
  10791. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10792. // Test chunked encoding with payload exceeding 10MB limit
  10793. std::string large_payload(12 * 1024 * 1024,
  10794. 'B'); // 12MB payload, exceeds 10MB limit
  10795. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10796. // Server may either return 413 or close the connection
  10797. if (res) {
  10798. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10799. } else {
  10800. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10801. }
  10802. }
  10803. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10804. // Test request without Content-Length header within 10MB limit
  10805. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10806. "Host: " +
  10807. std::string(HOST) + ":" +
  10808. std::to_string(PORT) +
  10809. "\r\n"
  10810. "Connection: close\r\n"
  10811. "\r\n";
  10812. // Add 1MB payload (within 10MB limit)
  10813. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10814. request_without_content_length += medium_payload;
  10815. std::string response;
  10816. bool result = send_request(5, request_without_content_length, &response);
  10817. if (result) {
  10818. // Should get a proper HTTP response for payloads within limit
  10819. if (response.length() > 10) {
  10820. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10821. "10MB limit";
  10822. } else {
  10823. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10824. "Content-Length)";
  10825. }
  10826. } else {
  10827. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10828. }
  10829. }
  10830. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10831. // Test request without Content-Length header exceeding 10MB limit
  10832. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10833. "Host: " +
  10834. std::string(HOST) + ":" +
  10835. std::to_string(PORT) +
  10836. "\r\n"
  10837. "Connection: close\r\n"
  10838. "\r\n";
  10839. // Add 12MB payload (exceeds 10MB limit)
  10840. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10841. request_without_content_length += large_payload;
  10842. std::string response;
  10843. bool result = send_request(10, request_without_content_length, &response);
  10844. if (!result) {
  10845. // Server should close connection due to payload limit
  10846. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10847. "(connection closed)";
  10848. } else {
  10849. // Check for error response
  10850. if (response.length() <= 10) {
  10851. SUCCEED()
  10852. << "Server closed connection for 12MB request exceeding 10MB limit";
  10853. } else {
  10854. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10855. response.find("Payload Too Large") != std::string::npos ||
  10856. response.find("400") != std::string::npos);
  10857. }
  10858. }
  10859. }
  10860. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10861. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10862. // path.
  10863. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10864. Server svr;
  10865. const size_t LIMIT = 64 * 1024; // 64KB
  10866. svr.set_payload_max_length(LIMIT);
  10867. size_t total = 0;
  10868. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10869. const ContentReader &content_reader) {
  10870. content_reader([&](const char * /*data*/, size_t len) {
  10871. total += len;
  10872. return true;
  10873. });
  10874. res.status = 200;
  10875. res.set_content("stream_ok", "text/plain");
  10876. });
  10877. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10878. auto se = detail::scope_exit([&] {
  10879. svr.stop();
  10880. thread.join();
  10881. ASSERT_FALSE(svr.is_running());
  10882. });
  10883. svr.wait_until_ready();
  10884. // Prepare 256KB raw data and gzip-compress it
  10885. std::string raw(256 * 1024, 'A');
  10886. std::string gz;
  10887. {
  10888. z_stream zs{};
  10889. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10890. Z_DEFAULT_STRATEGY);
  10891. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10892. zs.avail_in = static_cast<uInt>(raw.size());
  10893. char outbuf[4096];
  10894. int ret;
  10895. do {
  10896. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10897. zs.avail_out = sizeof(outbuf);
  10898. ret = deflate(&zs, Z_FINISH);
  10899. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10900. } while (ret != Z_STREAM_END);
  10901. deflateEnd(&zs);
  10902. }
  10903. Client cli(HOST, PORT);
  10904. cli.set_connection_timeout(std::chrono::seconds(5));
  10905. Headers headers = {{"Content-Encoding", "gzip"}};
  10906. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10907. "application/octet-stream");
  10908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10909. // Server must reject oversized decompressed payloads with 413.
  10910. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10911. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10912. EXPECT_LE(total, LIMIT);
  10913. }
  10914. #ifndef CPPHTTPLIB_SSL_ENABLED
  10915. // For a request with neither Content-Length nor Transfer-Encoding, the
  10916. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10917. // compressed wire bytes straight to the ContentReader without ever routing
  10918. // them through the decompressor, so payload_max_length_ only bounded the
  10919. // compressed size on the wire, not the decompressed size.
  10920. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10921. Server svr;
  10922. const size_t LIMIT = 64 * 1024; // 64KB
  10923. svr.set_payload_max_length(LIMIT);
  10924. size_t total = 0;
  10925. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10926. const ContentReader &content_reader) {
  10927. content_reader([&](const char * /*data*/, size_t len) {
  10928. total += len;
  10929. return true;
  10930. });
  10931. res.status = 200;
  10932. res.set_content("stream_ok", "text/plain");
  10933. });
  10934. auto port = svr.bind_to_any_port(HOST);
  10935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10936. auto se = detail::scope_exit([&] {
  10937. svr.stop();
  10938. thread.join();
  10939. ASSERT_FALSE(svr.is_running());
  10940. });
  10941. svr.wait_until_ready();
  10942. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10943. // StreamingGzipDecompression test above.
  10944. std::string raw(256 * 1024, 'A');
  10945. std::string gz;
  10946. {
  10947. httplib::detail::gzip_compressor compressor;
  10948. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10949. [&](const char *chunk, size_t len) {
  10950. gz.append(chunk, len);
  10951. return true;
  10952. });
  10953. ASSERT_TRUE(result);
  10954. }
  10955. // Send the gzip body over raw TCP with neither Content-Length nor
  10956. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10957. // kicks in.
  10958. std::string req = "POST /stream HTTP/1.1\r\n"
  10959. "Host: " +
  10960. std::string(HOST) + ":" + std::to_string(port) +
  10961. "\r\n"
  10962. "Content-Encoding: gzip\r\n"
  10963. "Connection: close\r\n"
  10964. "\r\n" +
  10965. gz;
  10966. std::string response;
  10967. ASSERT_TRUE(send_request(5, req, &response, port));
  10968. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10969. EXPECT_LE(total, LIMIT);
  10970. }
  10971. #endif
  10972. #endif
  10973. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10974. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10975. // the payload must be passed through untouched instead of being rejected.
  10976. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10977. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10978. Server svr;
  10979. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10980. res.set_content(body, "image/jpeg");
  10981. res.set_header("Content-Encoding", "UTF-8");
  10982. });
  10983. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10984. res.set_content(body, "image/jpeg");
  10985. res.set_header("Content-Encoding", "identity");
  10986. });
  10987. svr.Post("/echo", [](const Request &req, Response &res) {
  10988. res.set_content(req.body, "image/jpeg");
  10989. });
  10990. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10991. auto se = detail::scope_exit([&] {
  10992. svr.stop();
  10993. t.join();
  10994. ASSERT_FALSE(svr.is_running());
  10995. });
  10996. svr.wait_until_ready();
  10997. Client cli(HOST, PORT);
  10998. {
  10999. auto res = cli.Get("/image");
  11000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11001. EXPECT_EQ(StatusCode::OK_200, res->status);
  11002. EXPECT_EQ(body, res->body);
  11003. }
  11004. {
  11005. auto res = cli.Get("/identity");
  11006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11007. EXPECT_EQ(StatusCode::OK_200, res->status);
  11008. EXPECT_EQ(body, res->body);
  11009. }
  11010. {
  11011. // The same applies to a request body reaching the server.
  11012. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11013. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11015. EXPECT_EQ(StatusCode::OK_200, res->status);
  11016. EXPECT_EQ(body, res->body);
  11017. }
  11018. }
  11019. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11020. // gzip-encoded response even when the build has no zlib support.
  11021. static const char GZIPPED_HELLO_WORLD[] = {
  11022. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11023. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11024. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11025. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11026. // A content coding is a whole token, not something the field value merely
  11027. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11028. // as "fibre" look like Brotli, and turned a multi-coding value like
  11029. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11030. // it was never meant to see.
  11031. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11032. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11033. Server svr;
  11034. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11035. res.set_content(body, "image/jpeg");
  11036. res.set_header("Content-Encoding", "fibre");
  11037. });
  11038. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11039. res.set_content(body, "image/jpeg");
  11040. res.set_header("Content-Encoding", "gzip, br");
  11041. });
  11042. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11043. res.set_content(body, "image/jpeg");
  11044. res.set_header("Content-Encoding", "x-zstd-ish");
  11045. });
  11046. auto port = svr.bind_to_any_port(HOST);
  11047. thread t = thread([&]() { svr.listen_after_bind(); });
  11048. auto se = detail::scope_exit([&] {
  11049. svr.stop();
  11050. t.join();
  11051. ASSERT_FALSE(svr.is_running());
  11052. });
  11053. svr.wait_until_ready();
  11054. Client cli(HOST, port);
  11055. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11056. auto res = cli.Get(path);
  11057. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11058. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11059. // Not a coding we recognize, so the payload comes back untouched
  11060. EXPECT_EQ(body, res->body) << path;
  11061. }
  11062. }
  11063. // A content coding cpp-httplib recognizes but was not built with must be
  11064. // reported as such. Handing the still-compressed payload back to the caller
  11065. // would silently corrupt it.
  11066. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11067. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11068. Server svr;
  11069. // "image/jpeg" keeps the server from applying a content coding of its own,
  11070. // so the hand-crafted Content-Encoding below survives.
  11071. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11072. res.set_content(gzipped, "image/jpeg");
  11073. res.set_header("Content-Encoding", "gzip");
  11074. });
  11075. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11076. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11077. res.set_content(gzipped, "image/jpeg");
  11078. res.set_header("Content-Encoding", "GZIP");
  11079. });
  11080. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11081. auto se = detail::scope_exit([&] {
  11082. svr.stop();
  11083. t.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli(HOST, PORT);
  11088. {
  11089. auto res = cli.Get("/gzipped");
  11090. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ("Hello World!", res->body);
  11093. #else
  11094. ASSERT_FALSE(res);
  11095. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11096. #endif
  11097. }
  11098. {
  11099. // open_stream() must behave the same way.
  11100. auto handle = cli.open_stream("GET", "/gzipped");
  11101. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11102. ASSERT_TRUE(handle.is_valid());
  11103. std::string received;
  11104. char buf[256];
  11105. ssize_t n;
  11106. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11107. received.append(buf, static_cast<size_t>(n));
  11108. }
  11109. EXPECT_EQ("Hello World!", received);
  11110. #else
  11111. EXPECT_FALSE(handle.is_valid());
  11112. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11113. #endif
  11114. }
  11115. {
  11116. // A differently-cased coding must not be mistaken for an unknown one, or
  11117. // the body would be handed back still compressed.
  11118. auto res = cli.Get("/gzipped-uppercase");
  11119. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11121. EXPECT_EQ("Hello World!", res->body);
  11122. #else
  11123. ASSERT_FALSE(res);
  11124. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11125. #endif
  11126. }
  11127. }
  11128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11129. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11130. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11131. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11132. // body a second time and appending a second Content-Encoding field line, so
  11133. // clients that decode one coding per listed value handed back raw gzip bytes.
  11134. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11135. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11136. Server svr;
  11137. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11138. // keeps the server from applying a coding of its own.
  11139. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11140. res.set_content(gzipped, "text/plain");
  11141. res.set_header("Content-Encoding", "gzip");
  11142. });
  11143. auto port = svr.bind_to_any_port(HOST);
  11144. thread t = thread([&]() { svr.listen_after_bind(); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. ASSERT_FALSE(svr.is_running());
  11149. });
  11150. svr.wait_until_ready();
  11151. Client cli(HOST, port);
  11152. Headers headers = {{"Accept-Encoding", "gzip"}};
  11153. auto res = cli.Get("/pre-gzipped", headers);
  11154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11155. EXPECT_EQ(StatusCode::OK_200, res->status);
  11156. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11157. EXPECT_EQ("Hello World!", res->body);
  11158. }
  11159. // A chunked provider settles its coding where the headers are written and
  11160. // reuses it at write time. Both ends of that have to hold: a handler's own
  11161. // Content-Encoding suppresses the coding, and a response without one is still
  11162. // compressed as it always was.
  11163. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11164. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11165. const std::string plain = "Hello World! Hello World! Hello World!";
  11166. Server svr;
  11167. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11168. res.set_header("Content-Encoding", "gzip");
  11169. res.set_chunked_content_provider(
  11170. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11171. sink.write(gzipped.data(), gzipped.size());
  11172. sink.done();
  11173. return true;
  11174. });
  11175. });
  11176. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11177. res.set_chunked_content_provider(
  11178. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11179. sink.write(plain.data(), plain.size());
  11180. sink.done();
  11181. return true;
  11182. });
  11183. });
  11184. auto port = svr.bind_to_any_port(HOST);
  11185. thread t = thread([&]() { svr.listen_after_bind(); });
  11186. auto se = detail::scope_exit([&] {
  11187. svr.stop();
  11188. t.join();
  11189. ASSERT_FALSE(svr.is_running());
  11190. });
  11191. svr.wait_until_ready();
  11192. Client cli(HOST, port);
  11193. Headers headers = {{"Accept-Encoding", "gzip"}};
  11194. {
  11195. auto res = cli.Get("/pre-gzipped", headers);
  11196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11197. EXPECT_EQ(StatusCode::OK_200, res->status);
  11198. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11199. EXPECT_EQ("Hello World!", res->body);
  11200. }
  11201. {
  11202. auto res = cli.Get("/negotiated", headers);
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. EXPECT_EQ(StatusCode::OK_200, res->status);
  11205. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11206. EXPECT_EQ(plain, res->body);
  11207. }
  11208. }
  11209. #endif
  11210. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11211. // the same message as the comma-joined one, so both have to be read the same
  11212. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11213. // single gzip coding, and a body the sender says was encoded twice was handed
  11214. // back after one pass, still compressed but presented as decoded.
  11215. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11216. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11217. Server svr;
  11218. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11219. res.set_content(body, "image/jpeg");
  11220. res.headers.emplace("Content-Encoding", "gzip");
  11221. res.headers.emplace("Content-Encoding", "gzip");
  11222. });
  11223. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11224. res.set_content(body, "image/jpeg");
  11225. res.set_header("Content-Encoding", "gzip, gzip");
  11226. });
  11227. auto port = svr.bind_to_any_port(HOST);
  11228. thread t = thread([&]() { svr.listen_after_bind(); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. t.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. Client cli(HOST, port);
  11236. // Two codings is not something cpp-httplib decodes, so both representations
  11237. // take the pass-through path rather than one of them being gunzipped once.
  11238. for (const char *path : {"/split", "/joined"}) {
  11239. auto res = cli.Get(path);
  11240. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11241. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11242. EXPECT_EQ(body, res->body) << path;
  11243. }
  11244. }
  11245. // Regression test for DoS vulnerability: a malicious server sending a response
  11246. // without Content-Length header must not cause unbounded memory consumption on
  11247. // the client side. The client should stop reading after a reasonable limit,
  11248. // similar to the server-side set_payload_max_length protection.
  11249. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11250. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11251. #ifndef _WIN32
  11252. signal(SIGPIPE, SIG_IGN);
  11253. #endif
  11254. auto server_thread = std::thread([] {
  11255. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11256. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11257. default_socket_options(srv);
  11258. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11259. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11260. sockaddr_in addr{};
  11261. addr.sin_family = AF_INET;
  11262. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11263. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11264. int opt = 1;
  11265. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11266. #ifdef _WIN32
  11267. reinterpret_cast<const char *>(&opt),
  11268. #else
  11269. &opt,
  11270. #endif
  11271. sizeof(opt));
  11272. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11273. ::listen(srv, 1);
  11274. sockaddr_in cli_addr{};
  11275. socklen_t cli_len = sizeof(cli_addr);
  11276. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11277. if (cli != INVALID_SOCKET) {
  11278. char buf[4096];
  11279. ::recv(cli, buf, sizeof(buf), 0);
  11280. // Malicious response: no Content-Length, no chunked encoding
  11281. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11282. "Connection: close\r\n"
  11283. "\r\n";
  11284. ::send(cli,
  11285. #ifdef _WIN32
  11286. static_cast<const char *>(response_header.c_str()),
  11287. static_cast<int>(response_header.size()),
  11288. #else
  11289. response_header.c_str(), response_header.size(),
  11290. #endif
  11291. 0);
  11292. // Send 10MB of data
  11293. std::string chunk(64 * 1024, 'A');
  11294. size_t total_sent = 0;
  11295. while (total_sent < MALICIOUS_DATA_SIZE) {
  11296. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11297. auto sent = ::send(cli,
  11298. #ifdef _WIN32
  11299. static_cast<const char *>(chunk.c_str()),
  11300. static_cast<int>(to_send),
  11301. #else
  11302. chunk.c_str(), to_send,
  11303. #endif
  11304. 0);
  11305. if (sent <= 0) break;
  11306. total_sent += static_cast<size_t>(sent);
  11307. }
  11308. detail::close_socket(cli);
  11309. }
  11310. detail::close_socket(srv);
  11311. });
  11312. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11313. size_t total_read = 0;
  11314. {
  11315. Client cli("127.0.0.1", PORT + 2);
  11316. cli.set_read_timeout(5, 0);
  11317. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11318. auto stream = cli.open_stream("GET", "/malicious");
  11319. ASSERT_TRUE(stream.is_valid());
  11320. char buffer[64 * 1024];
  11321. ssize_t n;
  11322. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11323. total_read += static_cast<size_t>(n);
  11324. }
  11325. } // StreamHandle and Client destroyed here, closing the socket
  11326. server_thread.join();
  11327. // With set_payload_max_length, the client must stop reading before consuming
  11328. // all 10MB. The read loop should be cut off at or near the configured limit.
  11329. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11330. << "Client read " << total_read << " bytes, exceeding the configured "
  11331. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11332. }
  11333. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11334. // the entire response body without truncation.
  11335. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11336. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11337. #ifndef _WIN32
  11338. signal(SIGPIPE, SIG_IGN);
  11339. #endif
  11340. auto server_thread = std::thread([] {
  11341. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11342. default_socket_options(srv);
  11343. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11344. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11345. sockaddr_in addr{};
  11346. addr.sin_family = AF_INET;
  11347. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11348. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11349. int opt = 1;
  11350. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11351. #ifdef _WIN32
  11352. reinterpret_cast<const char *>(&opt),
  11353. #else
  11354. &opt,
  11355. #endif
  11356. sizeof(opt));
  11357. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11358. ::listen(srv, 1);
  11359. sockaddr_in cli_addr{};
  11360. socklen_t cli_len = sizeof(cli_addr);
  11361. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11362. if (cli != INVALID_SOCKET) {
  11363. char buf[4096];
  11364. ::recv(cli, buf, sizeof(buf), 0);
  11365. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11366. "Connection: close\r\n"
  11367. "\r\n";
  11368. ::send(cli,
  11369. #ifdef _WIN32
  11370. static_cast<const char *>(response_header.c_str()),
  11371. static_cast<int>(response_header.size()),
  11372. #else
  11373. response_header.c_str(), response_header.size(),
  11374. #endif
  11375. 0);
  11376. std::string chunk(64 * 1024, 'A');
  11377. size_t total_sent = 0;
  11378. while (total_sent < DATA_SIZE) {
  11379. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11380. auto sent = ::send(cli,
  11381. #ifdef _WIN32
  11382. static_cast<const char *>(chunk.c_str()),
  11383. static_cast<int>(to_send),
  11384. #else
  11385. chunk.c_str(), to_send,
  11386. #endif
  11387. 0);
  11388. if (sent <= 0) break;
  11389. total_sent += static_cast<size_t>(sent);
  11390. }
  11391. #ifdef _WIN32
  11392. ::shutdown(cli, SD_SEND);
  11393. #else
  11394. ::shutdown(cli, SHUT_WR);
  11395. #endif
  11396. // Drain until the client closes its end, ensuring all data is delivered
  11397. char drain[1024];
  11398. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11399. detail::close_socket(cli);
  11400. }
  11401. detail::close_socket(srv);
  11402. });
  11403. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11404. size_t total_read = 0;
  11405. {
  11406. Client cli("127.0.0.1", PORT + 2);
  11407. cli.set_read_timeout(5, 0);
  11408. cli.set_payload_max_length(0); // 0 means no limit
  11409. auto stream = cli.open_stream("GET", "/data");
  11410. ASSERT_TRUE(stream.is_valid());
  11411. char buffer[64 * 1024];
  11412. ssize_t n;
  11413. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11414. total_read += static_cast<size_t>(n);
  11415. }
  11416. }
  11417. server_thread.join();
  11418. EXPECT_EQ(total_read, DATA_SIZE)
  11419. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11420. << " bytes without truncation, but only read " << total_read << " bytes.";
  11421. }
  11422. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11423. // enormous Content-Length must not cause the client to pre-allocate a huge
  11424. // response body buffer. The reservation is capped at payload_max_length_, and
  11425. // the read itself fails when the body exceeds the limit.
  11426. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11427. #ifndef _WIN32
  11428. signal(SIGPIPE, SIG_IGN);
  11429. #endif
  11430. auto server_thread = std::thread([] {
  11431. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11432. default_socket_options(srv);
  11433. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11434. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11435. sockaddr_in addr{};
  11436. addr.sin_family = AF_INET;
  11437. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11438. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11439. int opt = 1;
  11440. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11441. #ifdef _WIN32
  11442. reinterpret_cast<const char *>(&opt),
  11443. #else
  11444. &opt,
  11445. #endif
  11446. sizeof(opt));
  11447. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11448. ::listen(srv, 1);
  11449. sockaddr_in cli_addr{};
  11450. socklen_t cli_len = sizeof(cli_addr);
  11451. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11452. if (cli != INVALID_SOCKET) {
  11453. char buf[4096];
  11454. ::recv(cli, buf, sizeof(buf), 0);
  11455. // Malicious response: claim a 20GB body but send only a tiny payload.
  11456. std::string response = "HTTP/1.1 200 OK\r\n"
  11457. "Content-Length: 20000000000\r\n"
  11458. "\r\n"
  11459. "abc";
  11460. ::send(cli,
  11461. #ifdef _WIN32
  11462. static_cast<const char *>(response.c_str()),
  11463. static_cast<int>(response.size()),
  11464. #else
  11465. response.c_str(), response.size(),
  11466. #endif
  11467. 0);
  11468. detail::close_socket(cli);
  11469. }
  11470. detail::close_socket(srv);
  11471. });
  11472. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11473. {
  11474. Client cli("127.0.0.1", PORT + 2);
  11475. cli.set_read_timeout(5, 0);
  11476. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11477. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11478. // (server claims more bytes than payload_max_length permits), but it must
  11479. // not exhaust memory before getting there.
  11480. auto res = cli.Get("/malicious");
  11481. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11482. }
  11483. server_thread.join();
  11484. }
  11485. // Verify that content_receiver bypasses the default payload_max_length,
  11486. // allowing streaming downloads larger than 100MB without requiring an explicit
  11487. // set_payload_max_length call.
  11488. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11489. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11490. #ifndef _WIN32
  11491. signal(SIGPIPE, SIG_IGN);
  11492. #endif
  11493. auto server_thread = std::thread([] {
  11494. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11495. default_socket_options(srv);
  11496. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11497. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11498. sockaddr_in addr{};
  11499. addr.sin_family = AF_INET;
  11500. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11501. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11502. int opt = 1;
  11503. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11504. #ifdef _WIN32
  11505. reinterpret_cast<const char *>(&opt),
  11506. #else
  11507. &opt,
  11508. #endif
  11509. sizeof(opt));
  11510. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11511. ::listen(srv, 1);
  11512. sockaddr_in cli_addr{};
  11513. socklen_t cli_len = sizeof(cli_addr);
  11514. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11515. if (cli != INVALID_SOCKET) {
  11516. char buf[4096];
  11517. ::recv(cli, buf, sizeof(buf), 0);
  11518. // Response with Content-Length larger than default 100MB limit
  11519. auto content_length = std::to_string(DATA_SIZE);
  11520. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11521. "Content-Length: " +
  11522. content_length +
  11523. "\r\n"
  11524. "Connection: close\r\n"
  11525. "\r\n";
  11526. ::send(cli,
  11527. #ifdef _WIN32
  11528. static_cast<const char *>(response_header.c_str()),
  11529. static_cast<int>(response_header.size()),
  11530. #else
  11531. response_header.c_str(), response_header.size(),
  11532. #endif
  11533. 0);
  11534. std::string chunk(64 * 1024, 'A');
  11535. size_t total_sent = 0;
  11536. while (total_sent < DATA_SIZE) {
  11537. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11538. auto sent = ::send(cli,
  11539. #ifdef _WIN32
  11540. static_cast<const char *>(chunk.c_str()),
  11541. static_cast<int>(to_send),
  11542. #else
  11543. chunk.c_str(), to_send,
  11544. #endif
  11545. 0);
  11546. if (sent <= 0) break;
  11547. total_sent += static_cast<size_t>(sent);
  11548. }
  11549. detail::close_socket(cli);
  11550. }
  11551. detail::close_socket(srv);
  11552. });
  11553. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11554. size_t total_received = 0;
  11555. {
  11556. Client cli("127.0.0.1", PORT + 2);
  11557. cli.set_read_timeout(10, 0);
  11558. // Do NOT call set_payload_max_length — use the default 100MB limit
  11559. auto res =
  11560. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11561. total_received += data_length;
  11562. return true;
  11563. });
  11564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11565. EXPECT_EQ(StatusCode::OK_200, res->status);
  11566. }
  11567. server_thread.join();
  11568. EXPECT_EQ(total_received, DATA_SIZE)
  11569. << "With content_receiver, the client should read all " << DATA_SIZE
  11570. << " bytes despite the default 100MB payload_max_length, but only read "
  11571. << total_received << " bytes.";
  11572. }
  11573. // Verify that an explicit set_payload_max_length smaller than the response is
  11574. // enforced even when a content_receiver is used.
  11575. TEST(ClientVulnerabilityTest,
  11576. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11577. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11578. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11579. #ifndef _WIN32
  11580. signal(SIGPIPE, SIG_IGN);
  11581. #endif
  11582. auto server_thread = std::thread([] {
  11583. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11584. default_socket_options(srv);
  11585. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11586. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11587. sockaddr_in addr{};
  11588. addr.sin_family = AF_INET;
  11589. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11590. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11591. int opt = 1;
  11592. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11593. #ifdef _WIN32
  11594. reinterpret_cast<const char *>(&opt),
  11595. #else
  11596. &opt,
  11597. #endif
  11598. sizeof(opt));
  11599. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11600. ::listen(srv, 1);
  11601. sockaddr_in cli_addr{};
  11602. socklen_t cli_len = sizeof(cli_addr);
  11603. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11604. if (cli != INVALID_SOCKET) {
  11605. char buf[4096];
  11606. ::recv(cli, buf, sizeof(buf), 0);
  11607. auto content_length = std::to_string(DATA_SIZE);
  11608. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11609. "Content-Length: " +
  11610. content_length +
  11611. "\r\n"
  11612. "Connection: close\r\n"
  11613. "\r\n";
  11614. ::send(cli,
  11615. #ifdef _WIN32
  11616. static_cast<const char *>(response_header.c_str()),
  11617. static_cast<int>(response_header.size()),
  11618. #else
  11619. response_header.c_str(), response_header.size(),
  11620. #endif
  11621. 0);
  11622. std::string chunk(64 * 1024, 'A');
  11623. size_t total_sent = 0;
  11624. while (total_sent < DATA_SIZE) {
  11625. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11626. auto sent = ::send(cli,
  11627. #ifdef _WIN32
  11628. static_cast<const char *>(chunk.c_str()),
  11629. static_cast<int>(to_send),
  11630. #else
  11631. chunk.c_str(), to_send,
  11632. #endif
  11633. 0);
  11634. if (sent <= 0) break;
  11635. total_sent += static_cast<size_t>(sent);
  11636. }
  11637. detail::close_socket(cli);
  11638. }
  11639. detail::close_socket(srv);
  11640. });
  11641. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11642. size_t total_received = 0;
  11643. {
  11644. Client cli("127.0.0.1", PORT + 2);
  11645. cli.set_read_timeout(10, 0);
  11646. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11647. auto res =
  11648. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11649. total_received += data_length;
  11650. return true;
  11651. });
  11652. // Should fail because 200MB exceeds the explicit 150MB limit
  11653. EXPECT_FALSE(res);
  11654. }
  11655. server_thread.join();
  11656. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11657. << "Client with content_receiver should respect the explicit "
  11658. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11659. << total_received << " bytes.";
  11660. }
  11661. // Verify that an explicit set_payload_max_length larger than the response
  11662. // allows the content_receiver to read all data successfully.
  11663. TEST(ClientVulnerabilityTest,
  11664. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11665. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11666. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11667. #ifndef _WIN32
  11668. signal(SIGPIPE, SIG_IGN);
  11669. #endif
  11670. auto server_thread = std::thread([] {
  11671. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11672. default_socket_options(srv);
  11673. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11674. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11675. sockaddr_in addr{};
  11676. addr.sin_family = AF_INET;
  11677. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11678. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11679. int opt = 1;
  11680. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11681. #ifdef _WIN32
  11682. reinterpret_cast<const char *>(&opt),
  11683. #else
  11684. &opt,
  11685. #endif
  11686. sizeof(opt));
  11687. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11688. ::listen(srv, 1);
  11689. sockaddr_in cli_addr{};
  11690. socklen_t cli_len = sizeof(cli_addr);
  11691. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11692. if (cli != INVALID_SOCKET) {
  11693. char buf[4096];
  11694. ::recv(cli, buf, sizeof(buf), 0);
  11695. auto content_length = std::to_string(DATA_SIZE);
  11696. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11697. "Content-Length: " +
  11698. content_length +
  11699. "\r\n"
  11700. "Connection: close\r\n"
  11701. "\r\n";
  11702. ::send(cli,
  11703. #ifdef _WIN32
  11704. static_cast<const char *>(response_header.c_str()),
  11705. static_cast<int>(response_header.size()),
  11706. #else
  11707. response_header.c_str(), response_header.size(),
  11708. #endif
  11709. 0);
  11710. std::string chunk(64 * 1024, 'A');
  11711. size_t total_sent = 0;
  11712. while (total_sent < DATA_SIZE) {
  11713. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11714. auto sent = ::send(cli,
  11715. #ifdef _WIN32
  11716. static_cast<const char *>(chunk.c_str()),
  11717. static_cast<int>(to_send),
  11718. #else
  11719. chunk.c_str(), to_send,
  11720. #endif
  11721. 0);
  11722. if (sent <= 0) break;
  11723. total_sent += static_cast<size_t>(sent);
  11724. }
  11725. #ifdef _WIN32
  11726. ::shutdown(cli, SD_SEND);
  11727. #else
  11728. ::shutdown(cli, SHUT_WR);
  11729. #endif
  11730. char drain[1024];
  11731. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11732. detail::close_socket(cli);
  11733. }
  11734. detail::close_socket(srv);
  11735. });
  11736. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11737. size_t total_received = 0;
  11738. {
  11739. Client cli("127.0.0.1", PORT + 2);
  11740. cli.set_read_timeout(10, 0);
  11741. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11742. auto res =
  11743. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11744. total_received += data_length;
  11745. return true;
  11746. });
  11747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11748. EXPECT_EQ(StatusCode::OK_200, res->status);
  11749. }
  11750. server_thread.join();
  11751. EXPECT_EQ(total_received, DATA_SIZE)
  11752. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11753. << " bytes (larger than " << DATA_SIZE
  11754. << " bytes response), content_receiver should read all data, but only "
  11755. "read "
  11756. << total_received << " bytes.";
  11757. }
  11758. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11759. // Regression test for "zip bomb" attack on the client side: a malicious server
  11760. // sends a small gzip-compressed response that decompresses to a huge payload.
  11761. // The client must enforce payload_max_length on the decompressed size.
  11762. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11763. constexpr size_t DECOMPRESSED_SIZE =
  11764. 10 * 1024 * 1024; // 10MB after decompression
  11765. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11766. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11767. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11768. std::string compressed;
  11769. {
  11770. httplib::detail::gzip_compressor compressor;
  11771. bool ok =
  11772. compressor.compress(uncompressed.data(), uncompressed.size(),
  11773. /*last=*/true, [&](const char *buf, size_t len) {
  11774. compressed.append(buf, len);
  11775. return true;
  11776. });
  11777. ASSERT_TRUE(ok);
  11778. }
  11779. // Sanity: compressed data should be much smaller than the decompressed size
  11780. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11781. #ifndef _WIN32
  11782. signal(SIGPIPE, SIG_IGN);
  11783. #endif
  11784. // Set up the listening socket in the main thread so the server is guaranteed
  11785. // to be ready before the client connects (eliminates race condition).
  11786. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11787. default_socket_options(srv);
  11788. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11789. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11790. sockaddr_in addr{};
  11791. addr.sin_family = AF_INET;
  11792. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11793. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11794. int opt = 1;
  11795. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11796. #ifdef _WIN32
  11797. reinterpret_cast<const char *>(&opt),
  11798. #else
  11799. &opt,
  11800. #endif
  11801. sizeof(opt));
  11802. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11803. ASSERT_EQ(0, ::listen(srv, 1));
  11804. auto server_thread = std::thread([&compressed, srv] {
  11805. sockaddr_in cli_addr{};
  11806. socklen_t cli_len = sizeof(cli_addr);
  11807. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11808. if (cli != INVALID_SOCKET) {
  11809. // Read the full HTTP request (until \r\n\r\n)
  11810. char buf[4096];
  11811. size_t total = 0;
  11812. while (total < sizeof(buf)) {
  11813. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11814. if (n <= 0) break;
  11815. total += static_cast<size_t>(n);
  11816. // Check for end of headers
  11817. if (total >= 4) {
  11818. std::string req(buf, total);
  11819. if (req.find("\r\n\r\n") != std::string::npos) break;
  11820. }
  11821. }
  11822. // Malicious response: gzip-compressed body, no Content-Length
  11823. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11824. "Content-Encoding: gzip\r\n"
  11825. "Connection: close\r\n"
  11826. "\r\n";
  11827. ::send(cli,
  11828. #ifdef _WIN32
  11829. static_cast<const char *>(response_header.c_str()),
  11830. static_cast<int>(response_header.size()),
  11831. #else
  11832. response_header.c_str(), response_header.size(),
  11833. #endif
  11834. 0);
  11835. // Send the compressed payload (small on the wire, huge when decompressed)
  11836. size_t total_sent = 0;
  11837. while (total_sent < compressed.size()) {
  11838. auto to_send = std::min(compressed.size() - total_sent,
  11839. static_cast<size_t>(64 * 1024));
  11840. auto sent =
  11841. ::send(cli,
  11842. #ifdef _WIN32
  11843. static_cast<const char *>(compressed.c_str() + total_sent),
  11844. static_cast<int>(to_send),
  11845. #else
  11846. compressed.c_str() + total_sent, to_send,
  11847. #endif
  11848. 0);
  11849. if (sent <= 0) break;
  11850. total_sent += static_cast<size_t>(sent);
  11851. }
  11852. detail::close_socket(cli);
  11853. }
  11854. });
  11855. auto se = detail::scope_exit([&] {
  11856. detail::close_socket(srv);
  11857. server_thread.join();
  11858. });
  11859. size_t total_decompressed = 0;
  11860. {
  11861. Client cli("127.0.0.1", PORT + 3);
  11862. cli.set_read_timeout(5, 0);
  11863. cli.set_decompress(true);
  11864. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11865. auto stream = cli.open_stream("GET", "/zipbomb");
  11866. ASSERT_TRUE(stream.is_valid());
  11867. char buffer[64 * 1024];
  11868. ssize_t n;
  11869. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11870. total_decompressed += static_cast<size_t>(n);
  11871. }
  11872. }
  11873. // The decompressed size must be capped by payload_max_length. Without
  11874. // protection, the client would decompress the full 10MB from a tiny
  11875. // compressed payload, enabling a zip bomb DoS attack.
  11876. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11877. << "Client decompressed " << total_decompressed
  11878. << " bytes from a gzip response. The decompressed size should be "
  11879. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11880. }
  11881. #endif
  11882. TEST(HostAndPortPropertiesTest, NoSSL) {
  11883. httplib::Client cli("www.google.com", 1234);
  11884. ASSERT_EQ("www.google.com", cli.host());
  11885. ASSERT_EQ(1234, cli.port());
  11886. }
  11887. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11888. httplib::Client cli("www.google.com:1234");
  11889. ASSERT_EQ("www.google.com", cli.host());
  11890. ASSERT_EQ(1234, cli.port());
  11891. }
  11892. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11893. // Port number that overflows int — should not crash, client becomes invalid
  11894. httplib::Client cli("http://www.google.com:99999999999999999999");
  11895. ASSERT_FALSE(cli.is_valid());
  11896. }
  11897. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11898. // Port 99999 exceeds valid range (1-65535) — should not crash
  11899. httplib::Client cli("http://www.google.com:99999");
  11900. ASSERT_FALSE(cli.is_valid());
  11901. }
  11902. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11903. httplib::Client cli("http://www.google.com:80abc");
  11904. ASSERT_FALSE(cli.is_valid());
  11905. }
  11906. #ifdef CPPHTTPLIB_SSL_ENABLED
  11907. TEST(HostAndPortPropertiesTest, SSL) {
  11908. httplib::SSLClient cli("www.google.com");
  11909. ASSERT_EQ("www.google.com", cli.host());
  11910. ASSERT_EQ(443, cli.port());
  11911. }
  11912. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11913. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11914. std::string cert;
  11915. read_file(CA_CERT_FILE, cert);
  11916. httplib::SSLClient httplib_client("www.google.com");
  11917. // Load CA store first time
  11918. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11919. // Load CA store second time (update)
  11920. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11921. // Verify client is still valid and can make connections
  11922. httplib_client.enable_server_certificate_verification(true);
  11923. auto res = httplib_client.Get("/");
  11924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11925. // Google may return 200 or 301 depending on various factors
  11926. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11927. res->status == StatusCode::MovedPermanently_301);
  11928. }
  11929. TEST(SSLClientTest, ServerNameIndication_Online) {
  11930. auto host = "httpbingo.org";
  11931. auto path = std::string{"/get"};
  11932. SSLClient cli(host, 443);
  11933. auto res = cli.Get(path);
  11934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11935. ASSERT_EQ(StatusCode::OK_200, res->status);
  11936. }
  11937. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11938. // Use a site that will cause SSL verification failure due to self-signed cert
  11939. SSLClient cli("self-signed.badssl.com", 443);
  11940. cli.enable_server_certificate_verification(true);
  11941. auto res = cli.Get("/");
  11942. ASSERT_TRUE(!res);
  11943. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11944. // Verify backend error is captured for SSLServerVerification
  11945. // This occurs when certificate verification fails
  11946. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11947. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11948. EXPECT_NE(0UL, res.ssl_backend_error());
  11949. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11950. // For OpenSSL, ssl_error is 0 for verification errors
  11951. EXPECT_EQ(0, res.ssl_error());
  11952. #if !defined(_WIN32) || \
  11953. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11954. // On non-Windows or when Windows Schannel is disabled, the error comes
  11955. // from OpenSSL's verification
  11956. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11957. res.ssl_backend_error());
  11958. #endif
  11959. #endif
  11960. }
  11961. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11962. // Use a site where hostname doesn't match the certificate
  11963. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11964. SSLClient cli("wrong.host.badssl.com", 443);
  11965. cli.enable_server_certificate_verification(true);
  11966. cli.enable_server_hostname_verification(true);
  11967. auto res = cli.Get("/");
  11968. ASSERT_TRUE(!res);
  11969. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11970. // Verify backend error is captured for hostname verification failure
  11971. EXPECT_NE(0UL, res.ssl_backend_error());
  11972. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11973. // For OpenSSL, ssl_error is 0 for verification errors
  11974. EXPECT_EQ(0, res.ssl_error());
  11975. #if !defined(_WIN32) || \
  11976. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11977. // On non-Windows or when Windows Schannel is disabled, the error comes
  11978. // from OpenSSL's hostname verification
  11979. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11980. res.ssl_backend_error());
  11981. #endif
  11982. #endif
  11983. }
  11984. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11985. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11986. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11987. SSLClient cli("www.google.com", 443);
  11988. cli.enable_server_certificate_verification(true);
  11989. auto res = cli.Get("/");
  11990. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11991. }
  11992. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11993. SSLClient cli("www.google.com", 443);
  11994. cli.enable_server_certificate_verification(true);
  11995. cli.enable_windows_certificate_verification(false);
  11996. auto res = cli.Get("/");
  11997. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11998. }
  11999. // The server sends an intermediate cross-signed by a root Windows trusts,
  12000. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12001. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12002. SSLClient cli("accounts.spotify.com", 443);
  12003. auto res = cli.Get("/");
  12004. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12005. << " ssl_backend_error=" << res.ssl_backend_error();
  12006. }
  12007. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12008. // policy status, which no backend reports for a self-signed certificate.
  12009. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12010. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12011. ASSERT_TRUE(svr.is_valid());
  12012. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12013. auto se = detail::scope_exit([&] {
  12014. svr.stop();
  12015. t.join();
  12016. ASSERT_FALSE(svr.is_running());
  12017. });
  12018. svr.wait_until_ready();
  12019. SSLClient cli("127.0.0.1", PORT);
  12020. cli.set_connection_timeout(30);
  12021. auto res = cli.Get("/");
  12022. ASSERT_FALSE(res);
  12023. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12024. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12025. }
  12026. #endif
  12027. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12028. Client cli("https://google.com");
  12029. auto res = cli.Get("/");
  12030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12031. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12032. }
  12033. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12034. SSLClient cli("google.com");
  12035. cli.set_ca_cert_path(CA_CERT_FILE);
  12036. auto res = cli.Get("/");
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12039. }
  12040. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12041. SSLClient cli("google.com");
  12042. cli.enable_server_certificate_verification(true);
  12043. cli.set_ca_cert_path("hello");
  12044. auto res = cli.Get("/");
  12045. ASSERT_TRUE(!res);
  12046. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12047. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12048. // should be set
  12049. EXPECT_EQ(0, res.ssl_error());
  12050. // Verify backend error is captured for SSLLoadingCerts
  12051. // This error occurs when loading CA certificates fails
  12052. EXPECT_NE(0UL, res.ssl_backend_error());
  12053. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12054. // OpenSSL specific error codes:
  12055. // > openssl errstr 0x80000002
  12056. // error:80000002:system library::No such file or directory
  12057. // > openssl errstr 0xA000126
  12058. // error:0A000126:SSL routines::unexpected eof while reading
  12059. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12060. res.ssl_backend_error() == 0xA000126);
  12061. #endif
  12062. }
  12063. TEST(SSLClientTest, ServerCertificateVerification4) {
  12064. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12065. ASSERT_TRUE(svr.is_valid());
  12066. svr.Get("/test", [&](const Request &, Response &res) {
  12067. res.set_content("test", "text/plain");
  12068. svr.stop();
  12069. ASSERT_TRUE(true);
  12070. });
  12071. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12072. auto se = detail::scope_exit([&] {
  12073. t.join();
  12074. ASSERT_FALSE(svr.is_running());
  12075. });
  12076. svr.wait_until_ready();
  12077. SSLClient cli("127.0.0.1", PORT);
  12078. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12079. cli.enable_server_certificate_verification(true);
  12080. cli.set_connection_timeout(30);
  12081. auto res = cli.Get("/test");
  12082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12083. ASSERT_EQ(StatusCode::OK_200, res->status);
  12084. }
  12085. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12086. std::string cert;
  12087. read_file(CA_CERT_FILE, cert);
  12088. SSLClient cli("google.com");
  12089. cli.load_ca_cert_store(cert.data(), cert.size());
  12090. const auto res = cli.Get("/");
  12091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12092. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12093. }
  12094. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12095. // clang-format off
  12096. static constexpr char cert[] =
  12097. "GlobalSign Root CA\n"
  12098. "==================\n"
  12099. "-----BEGIN CERTIFICATE-----\n"
  12100. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12101. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12102. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12103. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12104. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12105. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12106. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12107. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12108. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12109. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12110. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12111. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12112. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12113. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12114. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12115. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12116. "-----END CERTIFICATE-----\n";
  12117. // clang-format on
  12118. SSLClient cli("google.com");
  12119. cli.load_ca_cert_store(cert, sizeof(cert));
  12120. const auto res = cli.Get("/");
  12121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12122. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12123. }
  12124. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12125. SSLClient cli("www.youtube.com");
  12126. cli.set_ca_cert_path(CA_CERT_FILE);
  12127. cli.enable_server_certificate_verification(true);
  12128. cli.set_follow_location(true);
  12129. auto res = cli.Get("/");
  12130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12131. ASSERT_EQ(StatusCode::OK_200, res->status);
  12132. }
  12133. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12134. SSLClient cli("wWw.YouTube.Com");
  12135. cli.set_ca_cert_path(CA_CERT_FILE);
  12136. cli.enable_server_certificate_verification(true);
  12137. cli.enable_server_hostname_verification(true);
  12138. cli.set_follow_location(true);
  12139. auto res = cli.Get("/");
  12140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12141. ASSERT_EQ(StatusCode::OK_200, res->status);
  12142. }
  12143. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12144. SSLClient cli("gOoGlE.COm");
  12145. cli.enable_server_certificate_verification(true);
  12146. cli.enable_server_hostname_verification(true);
  12147. cli.set_follow_location(true);
  12148. auto res = cli.Get("/");
  12149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12150. ASSERT_EQ(StatusCode::OK_200, res->status);
  12151. }
  12152. TEST(SSLClientTest, Issue2004_Online) {
  12153. Client client("https://google.com");
  12154. client.set_follow_location(true);
  12155. auto res = client.Get("/");
  12156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12157. ASSERT_EQ(StatusCode::OK_200, res->status);
  12158. auto body = res->body;
  12159. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12160. }
  12161. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12162. // Create SSLClient with invalid cert/key to make is_valid() return false
  12163. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12164. "nonexistent_key.pem");
  12165. // is_valid() should be false due to cert loading failure
  12166. ASSERT_FALSE(cli.is_valid());
  12167. auto res = cli.Get("/");
  12168. ASSERT_FALSE(res);
  12169. EXPECT_EQ(Error::SSLConnection, res.error());
  12170. }
  12171. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12172. // Test for Issue #2251: SSL error not properly reported when client cert
  12173. // and key paths are swapped or mismatched
  12174. // This simulates the scenario where user accidentally swaps the cert and key
  12175. // files
  12176. // Using client cert file as private key and vice versa (completely wrong)
  12177. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12178. // Should fail validation due to cert/key mismatch
  12179. ASSERT_FALSE(cli.is_valid());
  12180. // Attempt to make a request should fail with proper error
  12181. auto res = cli.Get("/");
  12182. ASSERT_FALSE(res);
  12183. EXPECT_EQ(Error::SSLConnection, res.error());
  12184. // SSL error should be recorded in the Result object (this is the key fix for
  12185. // Issue #2251)
  12186. auto backend_error = res.ssl_backend_error();
  12187. EXPECT_NE(0u, backend_error);
  12188. }
  12189. // Tests cert/key mismatch detection at the TLS context level
  12190. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12191. // Test that using mismatched cert/key causes connection failure.
  12192. // We verify this at the SSLClient level rather than through internal
  12193. // TLS API functions.
  12194. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12195. cli.enable_server_certificate_verification(false);
  12196. cli.set_connection_timeout(2);
  12197. // The mismatch should cause a connection or handshake error
  12198. auto res = cli.Get("/test");
  12199. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12200. // Either way, the request should fail
  12201. EXPECT_FALSE(res);
  12202. }
  12203. #endif
  12204. #if 0
  12205. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12206. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12207. ASSERT_TRUE(cli != nullptr);
  12208. cli->set_address_family(AF_INET6);
  12209. cli->set_interface("en0");
  12210. auto res = cli->Get("/get");
  12211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12212. ASSERT_EQ(StatusCode::OK_200, res->status);
  12213. }
  12214. #endif
  12215. // Client certificate tests - work with all TLS backends
  12216. #ifdef CPPHTTPLIB_SSL_ENABLED
  12217. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  12218. void ClientCertPresent(
  12219. const std::string &client_cert_file,
  12220. const std::string &client_private_key_file,
  12221. const std::string &client_encrypted_private_key_pass = std::string(),
  12222. const ClientCertServerSetup &setup = nullptr) {
  12223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12224. CLIENT_CA_CERT_DIR);
  12225. ASSERT_TRUE(svr.is_valid());
  12226. if (setup) { setup(svr); }
  12227. svr.Get("/test", [&](const Request &req, Response &res) {
  12228. res.set_content("test", "text/plain");
  12229. auto cert = req.peer_cert();
  12230. ASSERT_TRUE(static_cast<bool>(cert));
  12231. std::string common_name = cert.subject_cn();
  12232. EXPECT_EQ("Common Name", common_name);
  12233. });
  12234. auto port = svr.bind_to_any_port(HOST);
  12235. ASSERT_LT(0, port);
  12236. thread t = thread([&]() { svr.listen_after_bind(); });
  12237. auto se = detail::scope_exit([&] {
  12238. svr.stop();
  12239. t.join();
  12240. ASSERT_FALSE(svr.is_running());
  12241. });
  12242. svr.wait_until_ready();
  12243. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  12244. client_encrypted_private_key_pass);
  12245. cli.enable_server_certificate_verification(false);
  12246. cli.set_connection_timeout(30);
  12247. auto res = cli.Get("/test");
  12248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12249. ASSERT_EQ(StatusCode::OK_200, res->status);
  12250. }
  12251. TEST(SSLClientServerTest, ClientCertPresent) {
  12252. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12253. }
  12254. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12255. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12256. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12257. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12258. }
  12259. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  12260. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12261. CLIENT_CA_CERT_DIR);
  12262. ASSERT_TRUE(svr.is_valid());
  12263. if (setup) { setup(svr); }
  12264. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  12265. auto port = svr.bind_to_any_port(HOST);
  12266. ASSERT_LT(0, port);
  12267. thread t = thread([&]() { svr.listen_after_bind(); });
  12268. auto se = detail::scope_exit([&] {
  12269. svr.stop();
  12270. t.join();
  12271. ASSERT_FALSE(svr.is_running());
  12272. });
  12273. svr.wait_until_ready();
  12274. SSLClient cli(HOST, port);
  12275. cli.set_connection_timeout(30);
  12276. // Skip the server certificate check, so that the request fails because the
  12277. // client certificate is missing rather than because cert.pem is not trusted
  12278. cli.enable_server_certificate_verification(false);
  12279. auto res = cli.Get("/test");
  12280. ASSERT_FALSE(res);
  12281. // The server rejects the client during the handshake, or on TLS 1.3 right
  12282. // after it, which the client notices on its first write or read
  12283. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  12284. res.error() == Error::Write || res.error() == Error::Read)
  12285. << to_string(res.error());
  12286. if (res.error() == Error::SSLConnection) {
  12287. EXPECT_NE(0UL, res.ssl_backend_error());
  12288. }
  12289. }
  12290. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  12291. // A server that requires client certificates must keep requiring them after a
  12292. // verify callback is set on its context, or set and then cleared again.
  12293. void ClientCertStillRequired(bool clear_callback) {
  12294. auto setup = [clear_callback](SSLServer &svr) {
  12295. ASSERT_TRUE(tls::set_verify_callback(
  12296. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  12297. if (clear_callback) {
  12298. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  12299. }
  12300. };
  12301. ClientCertMissing(setup);
  12302. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  12303. setup);
  12304. }
  12305. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  12306. ClientCertStillRequired(false);
  12307. }
  12308. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  12309. ClientCertStillRequired(true);
  12310. }
  12311. // PEM memory-based constructor tests (works with all TLS backends)
  12312. void PemMemoryClientCertPresent(
  12313. const std::string &client_cert_file,
  12314. const std::string &client_private_key_file,
  12315. const std::string &client_encrypted_private_key_pass = std::string()) {
  12316. // Read PEM files into memory
  12317. std::string server_cert_pem, server_key_pem;
  12318. std::string client_ca_pem;
  12319. std::string client_cert_pem, client_key_pem;
  12320. read_file(SERVER_CERT_FILE, server_cert_pem);
  12321. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12322. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12323. read_file(client_cert_file, client_cert_pem);
  12324. read_file(client_private_key_file, client_key_pem);
  12325. // Create server with PEM memory
  12326. SSLServer::PemMemory server_pem = {
  12327. server_cert_pem.c_str(),
  12328. server_cert_pem.size(),
  12329. server_key_pem.c_str(),
  12330. server_key_pem.size(),
  12331. client_ca_pem.c_str(),
  12332. client_ca_pem.size(),
  12333. nullptr // no password for server key
  12334. };
  12335. SSLServer svr(server_pem);
  12336. ASSERT_TRUE(svr.is_valid());
  12337. svr.Get("/test", [&](const Request &, Response &res) {
  12338. res.set_content("test", "text/plain");
  12339. });
  12340. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12341. auto se = detail::scope_exit([&] {
  12342. svr.stop();
  12343. t.join();
  12344. ASSERT_FALSE(svr.is_running());
  12345. });
  12346. svr.wait_until_ready();
  12347. // Create client with PEM memory
  12348. const char *password = client_encrypted_private_key_pass.empty()
  12349. ? nullptr
  12350. : client_encrypted_private_key_pass.c_str();
  12351. SSLClient::PemMemory client_pem = {
  12352. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12353. client_key_pem.size(), password};
  12354. SSLClient cli(HOST, PORT, client_pem);
  12355. cli.enable_server_certificate_verification(false);
  12356. cli.set_connection_timeout(30);
  12357. auto res = cli.Get("/test");
  12358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12359. ASSERT_EQ(StatusCode::OK_200, res->status);
  12360. }
  12361. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12362. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12363. }
  12364. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12365. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12366. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12367. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12368. }
  12369. TEST(SSLClientServerTest, TrustDirOptional) {
  12370. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12371. ASSERT_TRUE(svr.is_valid());
  12372. svr.Get("/test", [&](const Request &, Response &res) {
  12373. res.set_content("test", "text/plain");
  12374. });
  12375. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12376. auto se = detail::scope_exit([&] {
  12377. svr.stop();
  12378. t.join();
  12379. ASSERT_FALSE(svr.is_running());
  12380. });
  12381. svr.wait_until_ready();
  12382. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12383. cli.enable_server_certificate_verification(false);
  12384. cli.set_connection_timeout(30);
  12385. auto res = cli.Get("/test");
  12386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12387. ASSERT_EQ(StatusCode::OK_200, res->status);
  12388. }
  12389. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12390. class NoListenSSLServer : public SSLServer {
  12391. public:
  12392. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12393. const char *client_ca_cert_file_path,
  12394. const char *client_ca_cert_dir_path = nullptr)
  12395. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12396. client_ca_cert_dir_path),
  12397. stop_(false) {}
  12398. std::atomic_bool stop_;
  12399. private:
  12400. bool process_and_close_socket(socket_t /*sock*/) override {
  12401. // Don't create SSL context
  12402. while (!stop_.load()) {
  12403. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12404. }
  12405. return true;
  12406. }
  12407. };
  12408. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12409. CLIENT_CA_CERT_FILE);
  12410. ASSERT_TRUE(svr.is_valid());
  12411. svr.Get("/test", [&](const Request &, Response &res) {
  12412. res.set_content("test", "text/plain");
  12413. });
  12414. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12415. auto se = detail::scope_exit([&] {
  12416. svr.stop_ = true;
  12417. svr.stop();
  12418. t.join();
  12419. ASSERT_FALSE(svr.is_running());
  12420. });
  12421. svr.wait_until_ready();
  12422. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12423. cli.enable_server_certificate_verification(false);
  12424. cli.set_connection_timeout(1);
  12425. auto res = cli.Get("/test");
  12426. ASSERT_TRUE(!res);
  12427. EXPECT_EQ(Error::SSLConnection, res.error());
  12428. // Timeout results in WantRead error code (maps to backend-specific value)
  12429. EXPECT_NE(0, res.ssl_error());
  12430. }
  12431. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12432. // Test SSLServer with client certificate verification using the standard
  12433. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12435. CLIENT_CA_CERT_DIR);
  12436. ASSERT_TRUE(svr.is_valid());
  12437. svr.Get("/test", [&](const Request &req, Response &res) {
  12438. res.set_content("test", "text/plain");
  12439. auto cert = req.peer_cert();
  12440. ASSERT_TRUE(static_cast<bool>(cert));
  12441. auto common_name = cert.subject_cn();
  12442. EXPECT_EQ("Common Name", common_name);
  12443. });
  12444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12445. auto se = detail::scope_exit([&] {
  12446. svr.stop();
  12447. t.join();
  12448. ASSERT_FALSE(svr.is_running());
  12449. });
  12450. svr.wait_until_ready();
  12451. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12452. cli.enable_server_certificate_verification(false);
  12453. cli.set_connection_timeout(30);
  12454. auto res = cli.Get("/test");
  12455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12456. ASSERT_EQ(StatusCode::OK_200, res->status);
  12457. }
  12458. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12459. // Verifies that wildcard matching and exact matching work consistently
  12460. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12461. using namespace httplib::tls;
  12462. // We need a running server to test against
  12463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12464. ASSERT_TRUE(svr.is_valid());
  12465. svr.Get("/test", [](const Request &, Response &res) {
  12466. res.set_content("ok", "text/plain");
  12467. });
  12468. thread t([&]() { svr.listen(HOST, PORT); });
  12469. auto se = detail::scope_exit([&] {
  12470. svr.stop();
  12471. t.join();
  12472. });
  12473. svr.wait_until_ready();
  12474. bool verify_callback_called = false;
  12475. bool verify_result_wrong = false;
  12476. SSLClient cli(HOST, PORT);
  12477. cli.enable_server_certificate_verification(true);
  12478. cli.set_ca_cert_path(CA_CERT_FILE);
  12479. cli.set_connection_timeout(5);
  12480. // Note: Test certificate has CN="Common Name", not "localhost"
  12481. bool verify_result_cn = false;
  12482. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12483. verify_callback_called = true;
  12484. if (!ctx.cert) return false;
  12485. // Test 1: "Common Name" should match (our test server cert CN)
  12486. verify_result_cn = ctx.check_hostname("Common Name");
  12487. // Test 2: wrong hostname should not match
  12488. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12489. return true; // Accept for the purpose of this test
  12490. });
  12491. auto res = cli.Get("/test");
  12492. // The request may succeed or fail depending on cert configuration
  12493. // but the callback should have been called
  12494. ASSERT_TRUE(verify_callback_called)
  12495. << "Verify callback should have been called";
  12496. // CN="Common Name" should match our test certificate
  12497. //
  12498. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12499. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12500. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12501. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12502. // <openssl/base.h>, which is included transitively when
  12503. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12504. #if defined(OPENSSL_IS_BORINGSSL)
  12505. EXPECT_FALSE(verify_result_cn)
  12506. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12507. #else
  12508. EXPECT_TRUE(verify_result_cn)
  12509. << "verify_hostname should match 'Common Name' (certificate CN)";
  12510. #endif
  12511. // Wrong hostname should not match
  12512. EXPECT_FALSE(verify_result_wrong)
  12513. << "verify_hostname should not match 'wronghost.example.com'";
  12514. }
  12515. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12516. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12517. // X509_check_ip behavior and must hold for every backend.
  12518. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12519. using namespace httplib::tls;
  12520. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12521. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12522. ASSERT_TRUE(svr.is_valid());
  12523. svr.Get("/test", [](const Request &, Response &res) {
  12524. res.set_content("ok", "text/plain");
  12525. });
  12526. thread t([&]() { svr.listen(HOST, PORT); });
  12527. auto se = detail::scope_exit([&] {
  12528. svr.stop();
  12529. t.join();
  12530. });
  12531. svr.wait_until_ready();
  12532. bool verify_callback_called = false;
  12533. bool ip_matched_via_cn = true;
  12534. SSLClient cli(HOST, PORT);
  12535. cli.enable_server_certificate_verification(true);
  12536. cli.set_ca_cert_path(CA_CERT_FILE);
  12537. cli.set_connection_timeout(5);
  12538. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12539. verify_callback_called = true;
  12540. if (!ctx.cert) return false;
  12541. // The IP appears only in the CN, so it must NOT be accepted.
  12542. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12543. return true; // Accept for the purpose of this test
  12544. });
  12545. cli.Get("/test");
  12546. ASSERT_TRUE(verify_callback_called)
  12547. << "Verify callback should have been called";
  12548. EXPECT_FALSE(ip_matched_via_cn)
  12549. << "An IP host must not be authenticated via the certificate CN";
  12550. }
  12551. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12552. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12553. using namespace httplib::tls;
  12554. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12555. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12556. ASSERT_TRUE(svr.is_valid());
  12557. svr.Get("/test", [](const Request &, Response &res) {
  12558. res.set_content("ok", "text/plain");
  12559. });
  12560. thread t([&]() { svr.listen(HOST, PORT); });
  12561. auto se = detail::scope_exit([&] {
  12562. svr.stop();
  12563. t.join();
  12564. });
  12565. svr.wait_until_ready();
  12566. bool verify_callback_called = false;
  12567. bool san_matched = false;
  12568. bool wrong_ipv6_matched = true;
  12569. bool cn_ipv6_matched = true;
  12570. SSLClient cli(HOST, PORT);
  12571. cli.enable_server_certificate_verification(true);
  12572. cli.set_ca_cert_path(CA_CERT_FILE);
  12573. cli.set_connection_timeout(5);
  12574. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12575. verify_callback_called = true;
  12576. if (!ctx.cert) return false;
  12577. // Matches the IPv6 iPAddress SAN.
  12578. san_matched = ctx.check_hostname("2001:db8::1");
  12579. // A different IPv6 address must not match.
  12580. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12581. // "::1" lives only in the CN, so it must not be accepted.
  12582. cn_ipv6_matched = ctx.check_hostname("::1");
  12583. return true; // Accept for the purpose of this test
  12584. });
  12585. cli.Get("/test");
  12586. ASSERT_TRUE(verify_callback_called)
  12587. << "Verify callback should have been called";
  12588. EXPECT_TRUE(san_matched)
  12589. << "verify_hostname should match an IPv6 iPAddress SAN";
  12590. EXPECT_FALSE(wrong_ipv6_matched)
  12591. << "verify_hostname should not match a non-matching IPv6 address";
  12592. EXPECT_FALSE(cn_ipv6_matched)
  12593. << "An IPv6 host must not be authenticated via the certificate CN";
  12594. }
  12595. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12596. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12597. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12598. using namespace httplib::tls;
  12599. // SANs: DNS:a.zz, IP:42.46.122.122
  12600. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12601. ASSERT_TRUE(svr.is_valid());
  12602. svr.Get("/test", [](const Request &, Response &res) {
  12603. res.set_content("ok", "text/plain");
  12604. });
  12605. auto port = svr.bind_to_any_port(HOST);
  12606. thread t([&]() { svr.listen_after_bind(); });
  12607. auto se = detail::scope_exit([&] {
  12608. svr.stop();
  12609. t.join();
  12610. });
  12611. svr.wait_until_ready();
  12612. bool verify_callback_called = false;
  12613. bool dns_san_matched = false;
  12614. bool ip_san_matched = false;
  12615. bool ip_matched_via_dns_san = true;
  12616. bool dns_matched_via_ip_san = true;
  12617. SSLClient cli(HOST, port);
  12618. cli.enable_server_certificate_verification(true);
  12619. cli.set_ca_cert_path(CA_CERT_FILE);
  12620. cli.set_connection_timeout(5);
  12621. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12622. verify_callback_called = true;
  12623. if (!ctx.cert) return false;
  12624. dns_san_matched = ctx.check_hostname("a.zz");
  12625. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12626. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12627. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12628. return true; // Accept for the purpose of this test
  12629. });
  12630. cli.Get("/test");
  12631. ASSERT_TRUE(verify_callback_called)
  12632. << "Verify callback should have been called";
  12633. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12634. EXPECT_TRUE(ip_san_matched)
  12635. << "verify_hostname should match an iPAddress SAN";
  12636. EXPECT_FALSE(ip_matched_via_dns_san)
  12637. << "An IP host must not be authenticated via a dNSName SAN";
  12638. EXPECT_FALSE(dns_matched_via_ip_san)
  12639. << "A DNS host must not be authenticated via an iPAddress SAN";
  12640. }
  12641. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12642. // "www.*.example.test" names one host and not every host under example.test.
  12643. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12644. using namespace httplib::tls;
  12645. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12646. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12647. ASSERT_TRUE(svr.is_valid());
  12648. svr.Get("/test", [](const Request &, Response &res) {
  12649. res.set_content("ok", "text/plain");
  12650. });
  12651. auto port = svr.bind_to_any_port(HOST);
  12652. thread t([&]() { svr.listen_after_bind(); });
  12653. auto se = detail::scope_exit([&] {
  12654. svr.stop();
  12655. t.join();
  12656. });
  12657. svr.wait_until_ready();
  12658. bool verify_callback_called = false;
  12659. bool leftmost_wildcard_matched = false;
  12660. bool wildcard_spanned_labels = true;
  12661. bool inner_wildcard_matched = true;
  12662. SSLClient cli(HOST, port);
  12663. cli.enable_server_certificate_verification(true);
  12664. cli.set_ca_cert_path(CA_CERT_FILE);
  12665. cli.set_connection_timeout(5);
  12666. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12667. verify_callback_called = true;
  12668. if (!ctx.cert) return false;
  12669. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12670. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12671. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12672. return true; // Accept for the purpose of this test
  12673. });
  12674. cli.Get("/test");
  12675. ASSERT_TRUE(verify_callback_called)
  12676. << "Verify callback should have been called";
  12677. EXPECT_TRUE(leftmost_wildcard_matched)
  12678. << "A leftmost wildcard should match a single label";
  12679. EXPECT_FALSE(wildcard_spanned_labels)
  12680. << "A wildcard label must not match more than one label";
  12681. EXPECT_FALSE(inner_wildcard_matched)
  12682. << "A wildcard outside the leftmost label must not be honoured";
  12683. }
  12684. // sans() must report each SAN entry under its own type.
  12685. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12686. using namespace httplib::tls;
  12687. // SANs: DNS:a.zz, IP:42.46.122.122
  12688. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12689. ASSERT_TRUE(svr.is_valid());
  12690. svr.Get("/test", [](const Request &, Response &res) {
  12691. res.set_content("ok", "text/plain");
  12692. });
  12693. auto port = svr.bind_to_any_port(HOST);
  12694. thread t([&]() { svr.listen_after_bind(); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. t.join();
  12698. });
  12699. svr.wait_until_ready();
  12700. bool verify_callback_called = false;
  12701. std::vector<SanEntry> sans;
  12702. SSLClient cli(HOST, port);
  12703. cli.enable_server_certificate_verification(true);
  12704. cli.set_ca_cert_path(CA_CERT_FILE);
  12705. cli.set_connection_timeout(5);
  12706. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12707. verify_callback_called = true;
  12708. if (!ctx.cert) return false;
  12709. sans = ctx.sans();
  12710. return true; // Accept for the purpose of this test
  12711. });
  12712. cli.Get("/test");
  12713. ASSERT_TRUE(verify_callback_called)
  12714. << "Verify callback should have been called";
  12715. auto has_san = [&](SanType type, const std::string &value) {
  12716. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12717. return san.type == type && san.value == value;
  12718. });
  12719. };
  12720. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12721. << "sans() should report the dNSName SAN";
  12722. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12723. << "sans() should report the iPAddress SAN";
  12724. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12725. << "sans() must not report the dNSName SAN as an address";
  12726. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12727. << "sans() must not report the iPAddress SAN as a DNS name";
  12728. }
  12729. #endif
  12730. // mbedTLS-specific callback constructor test
  12731. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12732. #ifdef CPPHTTPLIB_SSL_ENABLED
  12733. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12734. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12735. ASSERT_TRUE(svr.is_valid());
  12736. // Set up a handler to verify client certificate is present
  12737. bool client_cert_verified = false;
  12738. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12739. // Verify that client certificate was provided
  12740. client_cert_verified = true;
  12741. res.set_content("success", "text/plain");
  12742. });
  12743. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12744. auto se = detail::scope_exit([&] {
  12745. svr.stop();
  12746. t.join();
  12747. ASSERT_FALSE(svr.is_running());
  12748. });
  12749. svr.wait_until_ready();
  12750. // Client with certificate
  12751. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12752. cli.enable_server_certificate_verification(false);
  12753. cli.set_connection_timeout(30);
  12754. auto res = cli.Get("/test");
  12755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12756. ASSERT_EQ(StatusCode::OK_200, res->status);
  12757. ASSERT_TRUE(client_cert_verified);
  12758. EXPECT_EQ("success", res->body);
  12759. }
  12760. #endif
  12761. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12762. // backends
  12763. #ifdef CPPHTTPLIB_SSL_ENABLED
  12764. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12765. using namespace httplib::tls;
  12766. // Test that when client CA cert file is provided,
  12767. // the server properly requests and validates client certificates
  12768. // Create a server with client authentication
  12769. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12770. ASSERT_TRUE(svr.is_valid());
  12771. bool handler_called = false;
  12772. svr.Get("/test", [&](const Request &req, Response &res) {
  12773. handler_called = true;
  12774. // Verify that a client certificate was provided
  12775. auto cert = req.peer_cert();
  12776. ASSERT_TRUE(static_cast<bool>(cert));
  12777. // Get the issuer name
  12778. std::string issuer_str = cert.issuer_name();
  12779. ASSERT_FALSE(issuer_str.empty());
  12780. // The client certificate should be issued by our test CA
  12781. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12782. res.set_content("authenticated", "text/plain");
  12783. });
  12784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12785. auto se = detail::scope_exit([&] {
  12786. svr.stop();
  12787. t.join();
  12788. ASSERT_FALSE(svr.is_running());
  12789. });
  12790. svr.wait_until_ready();
  12791. // Connect with a client certificate issued by the CA
  12792. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12793. cli.enable_server_certificate_verification(false);
  12794. cli.set_connection_timeout(30);
  12795. auto res = cli.Get("/test");
  12796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12797. ASSERT_EQ(StatusCode::OK_200, res->status);
  12798. ASSERT_TRUE(handler_called);
  12799. EXPECT_EQ("authenticated", res->body);
  12800. }
  12801. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12802. using namespace httplib::tls;
  12803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12804. ASSERT_TRUE(svr.is_valid());
  12805. svr.Get("/test", [](const Request &, Response &res) {
  12806. res.set_content("ok", "text/plain");
  12807. });
  12808. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12809. auto se = detail::scope_exit([&] {
  12810. svr.stop();
  12811. t.join();
  12812. });
  12813. svr.wait_until_ready();
  12814. SSLClient cli(HOST, PORT);
  12815. cli.enable_server_certificate_verification(false);
  12816. cli.set_connection_timeout(30);
  12817. bool cert_checked = false;
  12818. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12819. if (ctx.cert) {
  12820. auto sans = ctx.sans();
  12821. // Test certificate may or may not have SANs - just verify the API
  12822. // works If SANs exist, verify the types are valid
  12823. for (const auto &san : sans) {
  12824. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12825. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12826. san.type == SanType::OTHER);
  12827. EXPECT_FALSE(san.value.empty());
  12828. }
  12829. cert_checked = true;
  12830. }
  12831. return true;
  12832. });
  12833. auto res = cli.Get("/test");
  12834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12835. EXPECT_TRUE(cert_checked);
  12836. }
  12837. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12838. using namespace httplib::tls;
  12839. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12840. ASSERT_TRUE(svr.is_valid());
  12841. svr.Get("/test", [](const Request &, Response &res) {
  12842. res.set_content("ok", "text/plain");
  12843. });
  12844. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12845. auto se = detail::scope_exit([&] {
  12846. svr.stop();
  12847. t.join();
  12848. });
  12849. svr.wait_until_ready();
  12850. SSLClient cli(HOST, PORT);
  12851. cli.enable_server_certificate_verification(false);
  12852. cli.set_connection_timeout(30);
  12853. bool validity_checked = false;
  12854. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12855. if (ctx.cert) {
  12856. time_t not_before = 0, not_after = 0;
  12857. bool result = ctx.validity(not_before, not_after);
  12858. EXPECT_TRUE(result);
  12859. // Verify that not_before < now < not_after for a valid cert
  12860. time_t now = time(nullptr);
  12861. EXPECT_LT(not_before, now);
  12862. EXPECT_GT(not_after, now);
  12863. validity_checked = true;
  12864. }
  12865. return true;
  12866. });
  12867. auto res = cli.Get("/test");
  12868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12869. EXPECT_TRUE(validity_checked);
  12870. }
  12871. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12872. using namespace httplib::tls;
  12873. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12874. ASSERT_TRUE(svr.is_valid());
  12875. svr.Get("/test", [](const Request &, Response &res) {
  12876. res.set_content("ok", "text/plain");
  12877. });
  12878. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12879. auto se = detail::scope_exit([&] {
  12880. svr.stop();
  12881. t.join();
  12882. });
  12883. svr.wait_until_ready();
  12884. SSLClient cli(HOST, PORT);
  12885. cli.enable_server_certificate_verification(false);
  12886. cli.set_connection_timeout(30);
  12887. bool serial_checked = false;
  12888. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12889. if (ctx.cert) {
  12890. std::string serial = ctx.serial();
  12891. EXPECT_FALSE(serial.empty());
  12892. // Serial should be a hex string
  12893. for (char c : serial) {
  12894. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12895. (c >= 'a' && c <= 'f'));
  12896. }
  12897. serial_checked = true;
  12898. }
  12899. return true;
  12900. });
  12901. auto res = cli.Get("/test");
  12902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12903. EXPECT_TRUE(serial_checked);
  12904. }
  12905. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12906. // Test 1: Valid CA file - no error should be recorded
  12907. {
  12908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12909. CLIENT_CA_CERT_FILE);
  12910. ASSERT_TRUE(svr.is_valid());
  12911. // With valid setup, last_ssl_error should be 0
  12912. EXPECT_EQ(0, svr.ssl_last_error());
  12913. }
  12914. // Test 2: Invalid CA file content
  12915. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12916. {
  12917. // Create a temporary file with completely invalid content
  12918. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12919. {
  12920. std::ofstream ofs(temp_invalid_ca);
  12921. ofs << "This is not a certificate file at all\n";
  12922. ofs << "Just plain text content\n";
  12923. }
  12924. // Create server with invalid CA file
  12925. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12926. // Clean up temporary file
  12927. std::remove(temp_invalid_ca);
  12928. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12929. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12930. // Note: SSL_CTX_load_verify_locations typically fails first,
  12931. // but our error handling code path is still exercised
  12932. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12933. }
  12934. }
  12935. TEST(VerifyCallbackTest, VerifyContextFields) {
  12936. using namespace httplib::tls;
  12937. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12938. ASSERT_TRUE(svr.is_valid());
  12939. svr.Get("/test", [](const Request &, Response &res) {
  12940. res.set_content("ok", "text/plain");
  12941. });
  12942. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12943. auto se = detail::scope_exit([&] {
  12944. svr.stop();
  12945. t.join();
  12946. });
  12947. svr.wait_until_ready();
  12948. SSLClient cli(HOST, PORT);
  12949. cli.enable_server_certificate_verification(false);
  12950. cli.set_connection_timeout(30);
  12951. int callback_count = 0;
  12952. bool saw_leaf_cert = false;
  12953. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12954. if (ctx.cert) {
  12955. callback_count++;
  12956. // We should see at least one certificate (the leaf)
  12957. std::string cn = ctx.subject_cn();
  12958. if (!cn.empty()) { saw_leaf_cert = true; }
  12959. // Verify context fields are populated
  12960. EXPECT_NE(ctx.session, nullptr);
  12961. EXPECT_GE(ctx.depth, 0);
  12962. }
  12963. return true;
  12964. });
  12965. auto res = cli.Get("/test");
  12966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12967. EXPECT_GT(callback_count, 0);
  12968. EXPECT_TRUE(saw_leaf_cert);
  12969. }
  12970. // Each client's verifier is stored with its own TLS context, so configuring a
  12971. // second client on the same thread must not replace the first one's.
  12972. TEST(VerifyCallbackTest, PerClientVerifiersOnSameThread) {
  12973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12974. ASSERT_TRUE(svr.is_valid());
  12975. svr.Get("/test", [](const Request &, Response &res) {
  12976. res.set_content("ok", "text/plain");
  12977. });
  12978. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12979. auto se = detail::scope_exit([&] {
  12980. svr.stop();
  12981. t.join();
  12982. });
  12983. svr.wait_until_ready();
  12984. std::atomic<int> count1{0};
  12985. std::atomic<int> count2{0};
  12986. SSLClient cli1(HOST, PORT);
  12987. cli1.enable_server_certificate_verification(false);
  12988. cli1.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12989. count1++;
  12990. return true;
  12991. });
  12992. SSLClient cli2(HOST, PORT);
  12993. cli2.enable_server_certificate_verification(false);
  12994. cli2.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  12995. count2++;
  12996. return true;
  12997. });
  12998. auto res1 = cli1.Get("/test");
  12999. ASSERT_TRUE(res1) << "Error: " << to_string(res1.error());
  13000. EXPECT_GT(count1.load(), 0);
  13001. EXPECT_EQ(0, count2.load());
  13002. count1 = 0;
  13003. auto res2 = cli2.Get("/test");
  13004. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  13005. EXPECT_EQ(0, count1.load());
  13006. EXPECT_GT(count2.load(), 0);
  13007. }
  13008. // A verifier set on one thread must still run when the request is made from
  13009. // another thread.
  13010. TEST(VerifyCallbackTest, VerifierRunsOnAnotherThread) {
  13011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13012. ASSERT_TRUE(svr.is_valid());
  13013. svr.Get("/test", [](const Request &, Response &res) {
  13014. res.set_content("ok", "text/plain");
  13015. });
  13016. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13017. auto se = detail::scope_exit([&] {
  13018. svr.stop();
  13019. t.join();
  13020. });
  13021. svr.wait_until_ready();
  13022. std::atomic<int> count{0};
  13023. SSLClient cli(HOST, PORT);
  13024. cli.enable_server_certificate_verification(false);
  13025. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13026. count++;
  13027. return true;
  13028. });
  13029. Result res;
  13030. thread worker([&]() { res = cli.Get("/test"); });
  13031. worker.join();
  13032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13033. EXPECT_GT(count.load(), 0);
  13034. }
  13035. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13036. using httplib::tls::TlsError;
  13037. // Test that verify_error_to_string returns empty for success
  13038. std::string success_str = TlsError::verify_error_to_string(0);
  13039. EXPECT_TRUE(success_str.empty());
  13040. // Test that verify_error_to_string returns non-empty for error codes
  13041. // Using a common error code (certificate expired)
  13042. std::string error_str =
  13043. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13044. EXPECT_FALSE(error_str.empty());
  13045. }
  13046. TEST(SessionVerifierTest, CertificateAccepted) {
  13047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13048. ASSERT_TRUE(svr.is_valid());
  13049. svr.Get("/test", [](const Request &, Response &res) {
  13050. res.set_content("ok", "text/plain");
  13051. });
  13052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13053. auto se = detail::scope_exit([&] {
  13054. svr.stop();
  13055. t.join();
  13056. });
  13057. svr.wait_until_ready();
  13058. SSLClient cli(HOST, PORT);
  13059. cli.enable_server_certificate_verification(false);
  13060. cli.set_connection_timeout(30);
  13061. bool callback_called = false;
  13062. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13063. EXPECT_NE(session, nullptr);
  13064. callback_called = true;
  13065. return SSLVerifierResponse::CertificateAccepted;
  13066. });
  13067. auto res = cli.Get("/test");
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. EXPECT_EQ(200, res->status);
  13070. EXPECT_TRUE(callback_called);
  13071. }
  13072. TEST(SessionVerifierTest, CertificateRejected) {
  13073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13074. ASSERT_TRUE(svr.is_valid());
  13075. svr.Get("/test", [](const Request &, Response &res) {
  13076. res.set_content("ok", "text/plain");
  13077. });
  13078. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13079. auto se = detail::scope_exit([&] {
  13080. svr.stop();
  13081. t.join();
  13082. });
  13083. svr.wait_until_ready();
  13084. SSLClient cli(HOST, PORT);
  13085. cli.enable_server_certificate_verification(false);
  13086. cli.set_connection_timeout(30);
  13087. bool callback_called = false;
  13088. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13089. EXPECT_NE(session, nullptr);
  13090. callback_called = true;
  13091. return SSLVerifierResponse::CertificateRejected;
  13092. });
  13093. auto res = cli.Get("/test");
  13094. EXPECT_FALSE(res);
  13095. EXPECT_TRUE(callback_called);
  13096. }
  13097. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13098. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13099. ASSERT_TRUE(svr.is_valid());
  13100. svr.Get("/test", [](const Request &, Response &res) {
  13101. res.set_content("ok", "text/plain");
  13102. });
  13103. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13104. auto se = detail::scope_exit([&] {
  13105. svr.stop();
  13106. t.join();
  13107. });
  13108. svr.wait_until_ready();
  13109. // NoDecisionMade with verification disabled should succeed (no default check)
  13110. SSLClient cli(HOST, PORT);
  13111. cli.enable_server_certificate_verification(false);
  13112. cli.set_connection_timeout(30);
  13113. bool callback_called = false;
  13114. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13115. EXPECT_NE(session, nullptr);
  13116. callback_called = true;
  13117. return SSLVerifierResponse::NoDecisionMade;
  13118. });
  13119. auto res = cli.Get("/test");
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. EXPECT_EQ(200, res->status);
  13122. EXPECT_TRUE(callback_called);
  13123. }
  13124. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13126. ASSERT_TRUE(svr.is_valid());
  13127. svr.Get("/test", [](const Request &, Response &res) {
  13128. res.set_content("ok", "text/plain");
  13129. });
  13130. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13131. auto se = detail::scope_exit([&] {
  13132. svr.stop();
  13133. t.join();
  13134. });
  13135. svr.wait_until_ready();
  13136. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13137. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13138. // so we only check that the request fails, not whether the callback was
  13139. // called.
  13140. SSLClient cli(HOST, PORT);
  13141. cli.enable_server_certificate_verification(true);
  13142. cli.set_connection_timeout(30);
  13143. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13144. EXPECT_NE(session, nullptr);
  13145. return SSLVerifierResponse::NoDecisionMade;
  13146. });
  13147. auto res = cli.Get("/test");
  13148. EXPECT_FALSE(res);
  13149. }
  13150. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13151. // Test SSL server using PemMemory constructor with client CA certificates
  13152. // Read PEM files
  13153. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13154. read_file(SERVER_CERT_FILE, server_cert_pem);
  13155. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13156. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13157. // Create SSLServer with PemMemory constructor including client CA
  13158. SSLServer::PemMemory server_pem = {
  13159. server_cert_pem.c_str(),
  13160. server_cert_pem.size(),
  13161. server_key_pem.c_str(),
  13162. server_key_pem.size(),
  13163. client_ca_pem.c_str(),
  13164. client_ca_pem.size(),
  13165. nullptr // no password for server key
  13166. };
  13167. SSLServer svr(server_pem);
  13168. ASSERT_TRUE(svr.is_valid());
  13169. // No SSL error should be recorded for valid setup
  13170. EXPECT_EQ(0, svr.ssl_last_error());
  13171. // Set up server endpoints
  13172. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13173. res.set_content("ok", "text/plain");
  13174. });
  13175. // Start server in a thread
  13176. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13177. svr.wait_until_ready();
  13178. // Connect with client certificate (using constructor with paths)
  13179. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13180. cli.enable_server_certificate_verification(false);
  13181. auto res = cli.Get("/test-pem-ca");
  13182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13183. EXPECT_EQ(200, res->status);
  13184. EXPECT_EQ("ok", res->body);
  13185. svr.stop();
  13186. server_thread.join();
  13187. }
  13188. #endif
  13189. #ifdef _WIN32
  13190. TEST(CleanupTest, WSACleanup) {
  13191. int ret = WSACleanup();
  13192. ASSERT_EQ(0, ret);
  13193. }
  13194. #endif
  13195. #ifndef CPPHTTPLIB_SSL_ENABLED
  13196. TEST(NoSSLSupport, SimpleInterface) {
  13197. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13198. }
  13199. #endif
  13200. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13201. TEST(InvalidScheme, SimpleInterface) {
  13202. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13203. }
  13204. #endif
  13205. TEST(NoScheme, SimpleInterface) {
  13206. Client cli("yahoo.com:80");
  13207. ASSERT_TRUE(cli.is_valid());
  13208. }
  13209. TEST(SendAPI, SimpleInterface_Online) {
  13210. Client cli("http://yahoo.com");
  13211. Request req;
  13212. req.method = "GET";
  13213. req.path = "/";
  13214. auto res = cli.send(req);
  13215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13216. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13217. }
  13218. TEST(SendAPI, WithParamsInRequest) {
  13219. Server svr;
  13220. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13221. EXPECT_TRUE(req.has_param("test"));
  13222. EXPECT_EQ("test_value", req.get_param_value("test"));
  13223. });
  13224. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13225. auto se = detail::scope_exit([&] {
  13226. svr.stop();
  13227. t.join();
  13228. ASSERT_FALSE(svr.is_running());
  13229. });
  13230. svr.wait_until_ready();
  13231. Client cli(HOST, PORT);
  13232. {
  13233. Request req;
  13234. req.method = "GET";
  13235. req.path = "/";
  13236. req.params.emplace("test", "test_value");
  13237. auto res = cli.send(req);
  13238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13239. }
  13240. {
  13241. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13243. }
  13244. }
  13245. TEST(ClientImplMethods, GetSocketTest) {
  13246. httplib::Server svr;
  13247. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13248. res.status = StatusCode::OK_200;
  13249. });
  13250. auto port = svr.bind_to_any_port("127.0.0.1");
  13251. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13252. auto se = detail::scope_exit([&] {
  13253. svr.stop();
  13254. thread.join();
  13255. ASSERT_FALSE(svr.is_running());
  13256. });
  13257. svr.wait_until_ready();
  13258. {
  13259. httplib::Client cli("127.0.0.1", port);
  13260. cli.set_keep_alive(true);
  13261. // Use the behavior of cpp-httplib of opening the connection
  13262. // only when the first request happens. If that changes,
  13263. // this test would be obsolete.
  13264. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13265. // This also implicitly tests the server. But other tests would fail much
  13266. // earlier than this one to be considered.
  13267. auto res = cli.Get("/");
  13268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13269. EXPECT_EQ(StatusCode::OK_200, res->status);
  13270. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13271. }
  13272. }
  13273. #ifdef CPPHTTPLIB_SSL_ENABLED
  13274. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13275. Client cli("http://yahoo.com");
  13276. auto res = cli.Get("/");
  13277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13278. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13279. cli.set_follow_location(true);
  13280. res = cli.Get("/");
  13281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13282. EXPECT_EQ(StatusCode::OK_200, res->status);
  13283. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13284. }
  13285. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13286. Client cli("https://yahoo.com");
  13287. auto res = cli.Get("/");
  13288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13289. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13290. cli.set_follow_location(true);
  13291. res = cli.Get("/");
  13292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13293. EXPECT_EQ(StatusCode::OK_200, res->status);
  13294. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13295. }
  13296. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13297. Client cli("https://yahoo.com");
  13298. auto res = cli.Get("/");
  13299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13300. ASSERT_FALSE(!res);
  13301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13302. ASSERT_FALSE(res == nullptr);
  13303. ASSERT_TRUE(res != nullptr);
  13304. EXPECT_EQ(Error::Success, res.error());
  13305. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13306. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13307. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13308. cli.set_follow_location(true);
  13309. res = cli.Get("/");
  13310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13311. EXPECT_EQ(Error::Success, res.error());
  13312. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13313. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13314. EXPECT_EQ(StatusCode::OK_200, res->status);
  13315. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13316. }
  13317. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13318. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13319. Client cli("https://cdnjs.cloudflare.com");
  13320. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13321. Headers{{"Accept-Encoding", "br"}});
  13322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13323. EXPECT_EQ(StatusCode::OK_200, res->status);
  13324. EXPECT_EQ(287630U, res->body.size());
  13325. EXPECT_EQ("application/javascript; charset=utf-8",
  13326. res->get_header_value("Content-Type"));
  13327. }
  13328. #endif
  13329. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13330. #undef REDIR_HOST // Silence compiler warning
  13331. #define REDIR_HOST "https://httpbingo.org"
  13332. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13333. Client cli(REDIR_HOST);
  13334. cli.set_follow_location(true);
  13335. auto res =
  13336. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13338. EXPECT_EQ(StatusCode::OK_200, res->status);
  13339. }
  13340. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13341. Client cli(REDIR_HOST);
  13342. cli.set_follow_location(true);
  13343. Params params;
  13344. params.emplace("url", "http://example.com");
  13345. params.emplace("status_code", "302");
  13346. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13348. EXPECT_EQ(StatusCode::OK_200, res->status);
  13349. }
  13350. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13351. Client cli(REDIR_HOST);
  13352. cli.set_follow_location(true);
  13353. Params params;
  13354. params.emplace("url", "http://example.com");
  13355. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13357. EXPECT_EQ(StatusCode::OK_200, res->status);
  13358. }
  13359. TEST(HttpToHttpsRedirectTest, CertFile) {
  13360. auto ssl_port = PORT + 1;
  13361. Server svr;
  13362. ASSERT_TRUE(svr.is_valid());
  13363. svr.Get("/index", [&](const Request &, Response &res) {
  13364. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13365. "/index");
  13366. svr.stop();
  13367. });
  13368. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13369. ASSERT_TRUE(ssl_svr.is_valid());
  13370. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13371. res.set_content("test", "text/plain");
  13372. ssl_svr.stop();
  13373. });
  13374. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13375. thread t2 =
  13376. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13377. auto se = detail::scope_exit([&] {
  13378. t2.join();
  13379. t.join();
  13380. ASSERT_FALSE(svr.is_running());
  13381. });
  13382. svr.wait_until_ready();
  13383. ssl_svr.wait_until_ready();
  13384. Client cli("127.0.0.1", PORT);
  13385. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13386. cli.enable_server_certificate_verification(true);
  13387. cli.set_follow_location(true);
  13388. cli.set_connection_timeout(30);
  13389. auto res = cli.Get("/index");
  13390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13391. ASSERT_EQ(StatusCode::OK_200, res->status);
  13392. }
  13393. TEST(SSLClientRedirectTest, CertFile) {
  13394. auto ssl_port = PORT + 1;
  13395. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13396. ASSERT_TRUE(ssl_svr1.is_valid());
  13397. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13398. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13399. "/index");
  13400. ssl_svr1.stop();
  13401. });
  13402. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13403. ASSERT_TRUE(ssl_svr2.is_valid());
  13404. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13405. res.set_content("test", "text/plain");
  13406. ssl_svr2.stop();
  13407. });
  13408. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13409. thread t2 =
  13410. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13411. auto se = detail::scope_exit([&] {
  13412. t2.join();
  13413. t.join();
  13414. ASSERT_FALSE(ssl_svr1.is_running());
  13415. });
  13416. ssl_svr1.wait_until_ready();
  13417. ssl_svr2.wait_until_ready();
  13418. SSLClient cli("127.0.0.1", PORT);
  13419. std::string cert;
  13420. read_file(SERVER_CERT2_FILE, cert);
  13421. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13422. cli.enable_server_certificate_verification(true);
  13423. cli.set_follow_location(true);
  13424. cli.set_connection_timeout(30);
  13425. auto res = cli.Get("/index");
  13426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13427. ASSERT_EQ(StatusCode::OK_200, res->status);
  13428. }
  13429. // A store set via set_ca_cert_store() must be carried over to the client that
  13430. // follows a cross-host redirect, rather than replaced by the system CAs.
  13431. TEST(SSLClientRedirectTest, SetCaCertStore) {
  13432. auto ssl_port = PORT + 1;
  13433. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13434. ASSERT_TRUE(ssl_svr1.is_valid());
  13435. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13436. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13437. "/index");
  13438. });
  13439. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13440. ASSERT_TRUE(ssl_svr2.is_valid());
  13441. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13442. res.set_content("test", "text/plain");
  13443. });
  13444. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13445. thread t2 =
  13446. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13447. auto se = detail::scope_exit([&] {
  13448. ssl_svr2.stop();
  13449. ssl_svr1.stop();
  13450. t2.join();
  13451. t.join();
  13452. ASSERT_FALSE(ssl_svr1.is_running());
  13453. });
  13454. ssl_svr1.wait_until_ready();
  13455. ssl_svr2.wait_until_ready();
  13456. SSLClient cli("127.0.0.1", PORT);
  13457. std::string cert;
  13458. read_file(SERVER_CERT2_FILE, cert);
  13459. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13460. cli.enable_server_certificate_verification(true);
  13461. cli.set_follow_location(true);
  13462. cli.set_connection_timeout(30);
  13463. auto res = cli.Get("/index");
  13464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13465. ASSERT_EQ(StatusCode::OK_200, res->status);
  13466. }
  13467. // The session verifier must also run for the host a redirect leads to.
  13468. TEST(SSLClientRedirectTest, SessionVerifier) {
  13469. auto ssl_port = PORT + 1;
  13470. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13471. ASSERT_TRUE(ssl_svr1.is_valid());
  13472. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13473. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13474. "/index");
  13475. });
  13476. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13477. ASSERT_TRUE(ssl_svr2.is_valid());
  13478. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13479. res.set_content("test", "text/plain");
  13480. });
  13481. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13482. thread t2 =
  13483. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13484. auto se = detail::scope_exit([&] {
  13485. ssl_svr2.stop();
  13486. ssl_svr1.stop();
  13487. t2.join();
  13488. t.join();
  13489. ASSERT_FALSE(ssl_svr1.is_running());
  13490. });
  13491. ssl_svr1.wait_until_ready();
  13492. ssl_svr2.wait_until_ready();
  13493. SSLClient cli("127.0.0.1", PORT);
  13494. std::string cert;
  13495. read_file(SERVER_CERT2_FILE, cert);
  13496. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13497. cli.enable_server_certificate_verification(true);
  13498. cli.set_follow_location(true);
  13499. cli.set_connection_timeout(30);
  13500. // Accept the first host only.
  13501. std::atomic<int> sessions{0};
  13502. cli.set_session_verifier([&](tls::session_t) -> SSLVerifierResponse {
  13503. return sessions++ == 0 ? SSLVerifierResponse::CertificateAccepted
  13504. : SSLVerifierResponse::CertificateRejected;
  13505. });
  13506. auto res = cli.Get("/index");
  13507. ASSERT_FALSE(res);
  13508. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13509. EXPECT_EQ(2, sessions.load());
  13510. }
  13511. // So must the verifier given to set_server_certificate_verifier().
  13512. TEST(SSLClientRedirectTest, ServerCertificateVerifier) {
  13513. auto ssl_port = PORT + 1;
  13514. std::atomic<bool> redirected{false};
  13515. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13516. ASSERT_TRUE(ssl_svr1.is_valid());
  13517. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13518. redirected = true;
  13519. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13520. "/index");
  13521. });
  13522. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13523. ASSERT_TRUE(ssl_svr2.is_valid());
  13524. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13525. res.set_content("test", "text/plain");
  13526. });
  13527. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13528. thread t2 =
  13529. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13530. auto se = detail::scope_exit([&] {
  13531. ssl_svr2.stop();
  13532. ssl_svr1.stop();
  13533. t2.join();
  13534. t.join();
  13535. ASSERT_FALSE(ssl_svr1.is_running());
  13536. });
  13537. ssl_svr1.wait_until_ready();
  13538. ssl_svr2.wait_until_ready();
  13539. SSLClient cli("127.0.0.1", PORT);
  13540. std::string cert;
  13541. read_file(SERVER_CERT2_FILE, cert);
  13542. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13543. cli.enable_server_certificate_verification(true);
  13544. cli.set_follow_location(true);
  13545. cli.set_connection_timeout(30);
  13546. // Accept the host that redirects only; the verifier runs once per
  13547. // certificate in the chain, so count the calls made after the redirect.
  13548. std::atomic<int> calls_after_redirect{0};
  13549. cli.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  13550. if (!redirected) { return true; }
  13551. calls_after_redirect++;
  13552. return false;
  13553. });
  13554. auto res = cli.Get("/index");
  13555. ASSERT_FALSE(res);
  13556. EXPECT_LT(0, calls_after_redirect.load());
  13557. }
  13558. #endif
  13559. #ifdef CPPHTTPLIB_SSL_ENABLED
  13560. // Test that set_ca_cert_store() skips system certs (consistent with
  13561. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13562. // should be trusted - system certs should NOT be loaded.
  13563. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13564. // Load a specific cert that is NOT a system CA cert
  13565. std::string cert;
  13566. read_file(SERVER_CERT2_FILE, cert);
  13567. SSLClient cli("google.com");
  13568. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13569. cli.enable_server_certificate_verification(true);
  13570. // This should FAIL because:
  13571. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13572. // 2. System certs should NOT be loaded when custom store is set
  13573. // If system certs WERE loaded, this would succeed
  13574. auto res = cli.Get("/");
  13575. ASSERT_FALSE(res);
  13576. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13577. }
  13578. // Same as above, but through the native store handle path. Regression test:
  13579. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13580. // merged system certs into the user-provided store.
  13581. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13582. std::string cert;
  13583. read_file(SERVER_CERT2_FILE, cert);
  13584. SSLClient cli("google.com");
  13585. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13586. cli.enable_server_certificate_verification(true);
  13587. auto res = cli.Get("/");
  13588. ASSERT_FALSE(res);
  13589. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13590. }
  13591. // A custom store set via the native handle must still verify a server whose
  13592. // cert it does contain.
  13593. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13594. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13595. ASSERT_TRUE(svr.is_valid());
  13596. svr.Get("/test", [&](const Request &, Response &res) {
  13597. res.set_content("test", "text/plain");
  13598. });
  13599. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13600. auto se = detail::scope_exit([&] {
  13601. svr.stop();
  13602. t.join();
  13603. ASSERT_FALSE(svr.is_running());
  13604. });
  13605. svr.wait_until_ready();
  13606. SSLClient cli("127.0.0.1", PORT);
  13607. std::string cert;
  13608. read_file(SERVER_CERT2_FILE, cert);
  13609. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13610. cli.enable_server_certificate_verification(true);
  13611. cli.set_connection_timeout(30);
  13612. auto res = cli.Get("/test");
  13613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13614. ASSERT_EQ(StatusCode::OK_200, res->status);
  13615. }
  13616. // CA certs loaded through the universal Client must be transferred to the
  13617. // client created internally for following an HTTPS redirect. Regression test:
  13618. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13619. // the CA data for redirect transfer.
  13620. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13621. auto ssl_port = PORT + 1;
  13622. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13623. ASSERT_TRUE(ssl_svr1.is_valid());
  13624. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13625. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13626. "/index");
  13627. });
  13628. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13629. ASSERT_TRUE(ssl_svr2.is_valid());
  13630. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13631. res.set_content("test", "text/plain");
  13632. });
  13633. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13634. thread t2 =
  13635. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13636. auto se = detail::scope_exit([&] {
  13637. ssl_svr2.stop();
  13638. ssl_svr1.stop();
  13639. t2.join();
  13640. t.join();
  13641. ASSERT_FALSE(ssl_svr1.is_running());
  13642. });
  13643. ssl_svr1.wait_until_ready();
  13644. ssl_svr2.wait_until_ready();
  13645. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13646. std::string cert;
  13647. read_file(SERVER_CERT2_FILE, cert);
  13648. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13649. cli.enable_server_certificate_verification(true);
  13650. cli.set_follow_location(true);
  13651. cli.set_connection_timeout(30);
  13652. auto res = cli.Get("/index");
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13654. ASSERT_EQ(StatusCode::OK_200, res->status);
  13655. }
  13656. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13657. // so a host signed by a system CA verifies even though a custom CA is set
  13658. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13659. std::string cert;
  13660. read_file(SERVER_CERT2_FILE, cert);
  13661. SSLClient cli("google.com");
  13662. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13663. cli.enable_system_ca(true);
  13664. cli.enable_server_certificate_verification(true);
  13665. auto res = cli.Get("/");
  13666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13667. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13668. }
  13669. // The custom CA remains effective when combined with the system CA
  13670. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13671. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13672. ASSERT_TRUE(svr.is_valid());
  13673. svr.Get("/test", [&](const Request &, Response &res) {
  13674. res.set_content("test", "text/plain");
  13675. });
  13676. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13677. auto se = detail::scope_exit([&] {
  13678. svr.stop();
  13679. t.join();
  13680. ASSERT_FALSE(svr.is_running());
  13681. });
  13682. svr.wait_until_ready();
  13683. SSLClient cli("127.0.0.1", PORT);
  13684. std::string cert;
  13685. read_file(SERVER_CERT2_FILE, cert);
  13686. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13687. cli.enable_system_ca(true);
  13688. cli.enable_server_certificate_verification(true);
  13689. cli.set_connection_timeout(30);
  13690. auto res = cli.Get("/test");
  13691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13692. ASSERT_EQ(StatusCode::OK_200, res->status);
  13693. }
  13694. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13695. // skip chain verification entirely (only the certificate identity was
  13696. // checked), so a server presenting an untrusted certificate with a matching
  13697. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13698. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13699. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13700. ASSERT_TRUE(svr.is_valid());
  13701. svr.Get("/test", [&](const Request &, Response &res) {
  13702. res.set_content("test", "text/plain");
  13703. });
  13704. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13705. auto se = detail::scope_exit([&] {
  13706. svr.stop();
  13707. t.join();
  13708. ASSERT_FALSE(svr.is_running());
  13709. });
  13710. svr.wait_until_ready();
  13711. SSLClient cli("127.0.0.1", PORT);
  13712. std::string cert;
  13713. // A trusted CA that did not sign the server certificate. The server cert
  13714. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13715. // this connection.
  13716. read_file(CLIENT_CA_CERT_FILE, cert);
  13717. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13718. cli.enable_server_certificate_verification(true);
  13719. cli.set_connection_timeout(30);
  13720. auto res = cli.Get("/test");
  13721. ASSERT_FALSE(res);
  13722. }
  13723. // enable_system_ca(false) prevents system CA loading entirely
  13724. TEST(SSLClientTest, DisableSystemCa_Online) {
  13725. SSLClient cli("google.com");
  13726. cli.enable_system_ca(false);
  13727. cli.enable_server_certificate_verification(true);
  13728. auto res = cli.Get("/");
  13729. ASSERT_FALSE(res);
  13730. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13731. // itself when the CA chain is empty
  13732. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13733. res.error() == Error::SSLConnection);
  13734. }
  13735. // The universal Client forwards enable_system_ca()
  13736. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13737. std::string cert;
  13738. read_file(SERVER_CERT2_FILE, cert);
  13739. Client cli("https://google.com");
  13740. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13741. cli.enable_system_ca(true);
  13742. cli.enable_server_certificate_verification(true);
  13743. auto res = cli.Get("/");
  13744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13745. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13746. }
  13747. // The system CA policy must carry over to the client created internally for
  13748. // following a cross-host HTTPS redirect
  13749. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13750. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13751. ASSERT_TRUE(svr.is_valid());
  13752. svr.Get("/index", [&](const Request &, Response &res) {
  13753. res.set_redirect("https://www.google.com/");
  13754. });
  13755. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13756. auto se = detail::scope_exit([&] {
  13757. svr.stop();
  13758. t.join();
  13759. ASSERT_FALSE(svr.is_running());
  13760. });
  13761. svr.wait_until_ready();
  13762. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13763. std::string cert;
  13764. read_file(SERVER_CERT2_FILE, cert);
  13765. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13766. cli.enable_system_ca(true);
  13767. cli.enable_server_certificate_verification(true);
  13768. cli.set_follow_location(true);
  13769. cli.set_connection_timeout(30);
  13770. // Receiving any response proves the redirect client completed the TLS
  13771. // handshake with a system-CA-signed host
  13772. auto res = cli.Get("/index");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. }
  13775. TEST(MultipartFormDataTest, LargeData) {
  13776. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13777. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13778. const ContentReader &content_reader) {
  13779. if (req.is_multipart_form_data()) {
  13780. std::vector<FormData> items;
  13781. content_reader(
  13782. [&](const FormData &file) {
  13783. items.push_back(file);
  13784. return true;
  13785. },
  13786. [&](const char *data, size_t data_length) {
  13787. items.back().content.append(data, data_length);
  13788. return true;
  13789. });
  13790. EXPECT_TRUE(std::string(items[0].name) == "document");
  13791. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13792. EXPECT_TRUE(items[0].filename == "2MB_data");
  13793. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13794. EXPECT_TRUE(items[1].name == "hello");
  13795. EXPECT_TRUE(items[1].content == "world");
  13796. EXPECT_TRUE(items[1].filename == "");
  13797. EXPECT_TRUE(items[1].content_type == "");
  13798. } else {
  13799. std::string body;
  13800. content_reader([&](const char *data, size_t data_length) {
  13801. body.append(data, data_length);
  13802. return true;
  13803. });
  13804. }
  13805. });
  13806. auto port = svr.bind_to_any_port(HOST);
  13807. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13808. auto se = detail::scope_exit([&] {
  13809. svr.stop();
  13810. t.join();
  13811. ASSERT_FALSE(svr.is_running());
  13812. });
  13813. svr.wait_until_ready();
  13814. {
  13815. std::string data(1024 * 1024 * 2, '.');
  13816. std::stringstream buffer;
  13817. buffer << data;
  13818. SSLClient cli(HOST, port);
  13819. cli.enable_server_certificate_verification(false);
  13820. UploadFormDataItems items{
  13821. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13822. {"hello", "world", "", ""},
  13823. };
  13824. auto res = cli.Post("/post", items);
  13825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13826. ASSERT_EQ(StatusCode::OK_200, res->status);
  13827. }
  13828. }
  13829. TEST(MultipartFormDataTest, DataProviderItems) {
  13830. std::random_device seed_gen;
  13831. std::mt19937 random(seed_gen());
  13832. std::string rand1;
  13833. rand1.resize(1000);
  13834. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13835. std::string rand2;
  13836. rand2.resize(3000);
  13837. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13839. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13840. const ContentReader &content_reader) {
  13841. ASSERT_FALSE(req.is_multipart_form_data());
  13842. std::string body;
  13843. content_reader([&](const char *data, size_t data_length) {
  13844. body.append(data, data_length);
  13845. return true;
  13846. });
  13847. EXPECT_EQ(body, "");
  13848. });
  13849. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13850. const ContentReader &content_reader) {
  13851. ASSERT_TRUE(req.is_multipart_form_data());
  13852. std::vector<FormData> items;
  13853. content_reader(
  13854. [&](const FormData &file) {
  13855. items.push_back(file);
  13856. return true;
  13857. },
  13858. [&](const char *data, size_t data_length) {
  13859. items.back().content.append(data, data_length);
  13860. return true;
  13861. });
  13862. ASSERT_TRUE(items.size() == 2);
  13863. EXPECT_EQ(std::string(items[0].name), "name1");
  13864. EXPECT_EQ(items[0].content, "Testing123");
  13865. EXPECT_EQ(items[0].filename, "filename1");
  13866. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13867. EXPECT_EQ(items[1].name, "name2");
  13868. EXPECT_EQ(items[1].content, "Testing456");
  13869. EXPECT_EQ(items[1].filename, "");
  13870. EXPECT_EQ(items[1].content_type, "");
  13871. });
  13872. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13873. const ContentReader &content_reader) {
  13874. ASSERT_TRUE(req.is_multipart_form_data());
  13875. std::vector<FormData> items;
  13876. content_reader(
  13877. [&](const FormData &file) {
  13878. items.push_back(file);
  13879. return true;
  13880. },
  13881. [&](const char *data, size_t data_length) {
  13882. items.back().content.append(data, data_length);
  13883. return true;
  13884. });
  13885. ASSERT_TRUE(items.size() == 2);
  13886. EXPECT_EQ(items[0].name, "name3");
  13887. EXPECT_EQ(items[0].content, rand1);
  13888. EXPECT_EQ(items[0].filename, "filename3");
  13889. EXPECT_EQ(items[0].content_type, "");
  13890. EXPECT_EQ(items[1].name, "name4");
  13891. EXPECT_EQ(items[1].content, rand2);
  13892. EXPECT_EQ(items[1].filename, "filename4");
  13893. EXPECT_EQ(items[1].content_type, "");
  13894. });
  13895. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13896. const ContentReader &content_reader) {
  13897. ASSERT_TRUE(req.is_multipart_form_data());
  13898. std::vector<FormData> items;
  13899. content_reader(
  13900. [&](const FormData &file) {
  13901. items.push_back(file);
  13902. return true;
  13903. },
  13904. [&](const char *data, size_t data_length) {
  13905. items.back().content.append(data, data_length);
  13906. return true;
  13907. });
  13908. ASSERT_TRUE(items.size() == 4);
  13909. EXPECT_EQ(std::string(items[0].name), "name1");
  13910. EXPECT_EQ(items[0].content, "Testing123");
  13911. EXPECT_EQ(items[0].filename, "filename1");
  13912. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13913. EXPECT_EQ(items[1].name, "name2");
  13914. EXPECT_EQ(items[1].content, "Testing456");
  13915. EXPECT_EQ(items[1].filename, "");
  13916. EXPECT_EQ(items[1].content_type, "");
  13917. EXPECT_EQ(items[2].name, "name3");
  13918. EXPECT_EQ(items[2].content, rand1);
  13919. EXPECT_EQ(items[2].filename, "filename3");
  13920. EXPECT_EQ(items[2].content_type, "");
  13921. EXPECT_EQ(items[3].name, "name4");
  13922. EXPECT_EQ(items[3].content, rand2);
  13923. EXPECT_EQ(items[3].filename, "filename4");
  13924. EXPECT_EQ(items[3].content_type, "");
  13925. });
  13926. auto port = svr.bind_to_any_port("localhost");
  13927. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13928. auto se = detail::scope_exit([&] {
  13929. svr.stop();
  13930. t.join();
  13931. ASSERT_FALSE(svr.is_running());
  13932. });
  13933. svr.wait_until_ready();
  13934. {
  13935. SSLClient cli("localhost", port);
  13936. cli.enable_server_certificate_verification(false);
  13937. UploadFormDataItems items{
  13938. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13939. {"name2", "Testing456", "", ""}, // not a file
  13940. };
  13941. {
  13942. auto res = cli.Post("/post-none", {}, {}, {});
  13943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13944. ASSERT_EQ(StatusCode::OK_200, res->status);
  13945. }
  13946. FormDataProviderItems providers;
  13947. {
  13948. auto res =
  13949. cli.Post("/post-items", {}, items, providers); // empty providers
  13950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13951. ASSERT_EQ(StatusCode::OK_200, res->status);
  13952. }
  13953. providers.push_back({"name3",
  13954. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13955. // test the offset is given correctly at each step
  13956. if (!offset)
  13957. sink.os.write(rand1.data(), 30);
  13958. else if (offset == 30)
  13959. sink.os.write(rand1.data() + 30, 300);
  13960. else if (offset == 330)
  13961. sink.os.write(rand1.data() + 330, 670);
  13962. else if (offset == rand1.size())
  13963. sink.done();
  13964. return true;
  13965. },
  13966. "filename3",
  13967. {}});
  13968. providers.push_back({"name4",
  13969. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13970. // test the offset is given correctly at each step
  13971. if (!offset)
  13972. sink.os.write(rand2.data(), 2000);
  13973. else if (offset == 2000)
  13974. sink.os.write(rand2.data() + 2000, 1);
  13975. else if (offset == 2001)
  13976. sink.os.write(rand2.data() + 2001, 999);
  13977. else if (offset == rand2.size())
  13978. sink.done();
  13979. return true;
  13980. },
  13981. "filename4",
  13982. {}});
  13983. {
  13984. auto res = cli.Post("/post-providers", {}, {}, providers);
  13985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13986. ASSERT_EQ(StatusCode::OK_200, res->status);
  13987. }
  13988. {
  13989. auto res = cli.Post("/post-both", {}, items, providers);
  13990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13991. ASSERT_EQ(StatusCode::OK_200, res->status);
  13992. }
  13993. }
  13994. }
  13995. TEST(MultipartFormDataTest, BadHeader) {
  13996. Server svr;
  13997. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13998. res.set_content("ok", "text/plain");
  13999. });
  14000. thread t = thread([&] { svr.listen(HOST, PORT); });
  14001. auto se = detail::scope_exit([&] {
  14002. svr.stop();
  14003. t.join();
  14004. ASSERT_FALSE(svr.is_running());
  14005. });
  14006. svr.wait_until_ready();
  14007. const std::string body =
  14008. "This is the preamble. It is to be ignored, though it\r\n"
  14009. "is a handy place for composition agents to include an\r\n"
  14010. "explanatory note to non-MIME conformant readers.\r\n"
  14011. "\r\n"
  14012. "\r\n"
  14013. "--simple boundary\r\n"
  14014. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14015. ": BAD...\r\n"
  14016. "\r\n"
  14017. "value1\r\n"
  14018. "--simple boundary\r\n"
  14019. "Content-Disposition: form-data; name=\"field2\"; "
  14020. "filename=\"example.txt\"\r\n"
  14021. "\r\n"
  14022. "value2\r\n"
  14023. "--simple boundary--\r\n"
  14024. "This is the epilogue. It is also to be ignored.\r\n";
  14025. std::string content_type =
  14026. R"(multipart/form-data; boundary="simple boundary")";
  14027. Client cli(HOST, PORT);
  14028. auto res = cli.Post("/post", body, content_type.c_str());
  14029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14030. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14031. }
  14032. TEST(MultipartFormDataTest, WithPreamble) {
  14033. Server svr;
  14034. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14035. res.set_content("ok", "text/plain");
  14036. });
  14037. thread t = thread([&] { svr.listen(HOST, PORT); });
  14038. auto se = detail::scope_exit([&] {
  14039. svr.stop();
  14040. t.join();
  14041. ASSERT_FALSE(svr.is_running());
  14042. });
  14043. svr.wait_until_ready();
  14044. const std::string body =
  14045. "This is the preamble. It is to be ignored, though it\r\n"
  14046. "is a handy place for composition agents to include an\r\n"
  14047. "explanatory note to non-MIME conformant readers.\r\n"
  14048. "\r\n"
  14049. "\r\n"
  14050. "--simple boundary\r\n"
  14051. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14052. "\r\n"
  14053. "value1\r\n"
  14054. "--simple boundary\r\n"
  14055. "Content-Disposition: form-data; name=\"field2\"; "
  14056. "filename=\"example.txt\"\r\n"
  14057. "\r\n"
  14058. "value2\r\n"
  14059. "--simple boundary--\r\n"
  14060. "This is the epilogue. It is also to be ignored.\r\n";
  14061. std::string content_type =
  14062. R"(multipart/form-data; boundary="simple boundary")";
  14063. Client cli(HOST, PORT);
  14064. auto res = cli.Post("/post", body, content_type.c_str());
  14065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14066. EXPECT_EQ(StatusCode::OK_200, res->status);
  14067. }
  14068. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14069. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14070. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14071. const ContentReader &content_reader) {
  14072. if (req.is_multipart_form_data()) {
  14073. std::vector<FormData> items;
  14074. content_reader(
  14075. [&](const FormData &file) {
  14076. items.push_back(file);
  14077. return true;
  14078. },
  14079. [&](const char *data, size_t data_length) {
  14080. items.back().content.append(data, data_length);
  14081. return true;
  14082. });
  14083. EXPECT_TRUE(std::string(items[0].name) == "document");
  14084. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14085. EXPECT_TRUE(items[0].filename == "2MB_data");
  14086. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14087. EXPECT_TRUE(items[1].name == "hello");
  14088. EXPECT_TRUE(items[1].content == "world");
  14089. EXPECT_TRUE(items[1].filename == "");
  14090. EXPECT_TRUE(items[1].content_type == "");
  14091. } else {
  14092. std::string body;
  14093. content_reader([&](const char *data, size_t data_length) {
  14094. body.append(data, data_length);
  14095. return true;
  14096. });
  14097. }
  14098. });
  14099. auto port = svr.bind_to_any_port("localhost");
  14100. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14101. auto se = detail::scope_exit([&] {
  14102. svr.stop();
  14103. t.join();
  14104. ASSERT_FALSE(svr.is_running());
  14105. });
  14106. svr.wait_until_ready();
  14107. {
  14108. std::string data(1024 * 1024 * 2, '.');
  14109. std::stringstream buffer;
  14110. buffer << data;
  14111. SSLClient cli("localhost", port);
  14112. cli.enable_server_certificate_verification(false);
  14113. UploadFormDataItems items{
  14114. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14115. {"hello", "world", "", ""},
  14116. };
  14117. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14119. ASSERT_EQ(StatusCode::OK_200, res->status);
  14120. }
  14121. }
  14122. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14123. std::string data(1024 * 1024 * 2, '&');
  14124. std::stringstream buffer;
  14125. buffer << data;
  14126. Client cli("https://localhost:8080");
  14127. UploadFormDataItems items{
  14128. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14129. {"hello", "world", "", ""},
  14130. };
  14131. for (const char &c : " \t\r\n") {
  14132. auto res =
  14133. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14134. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14135. ASSERT_FALSE(res);
  14136. }
  14137. }
  14138. TEST(MultipartFormDataTest, PutFormData) {
  14139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14140. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14141. const ContentReader &content_reader) {
  14142. if (req.is_multipart_form_data()) {
  14143. std::vector<FormData> items;
  14144. content_reader(
  14145. [&](const FormData &file) {
  14146. items.push_back(file);
  14147. return true;
  14148. },
  14149. [&](const char *data, size_t data_length) {
  14150. items.back().content.append(data, data_length);
  14151. return true;
  14152. });
  14153. EXPECT_TRUE(std::string(items[0].name) == "document");
  14154. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14155. EXPECT_TRUE(items[0].filename == "2MB_data");
  14156. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14157. EXPECT_TRUE(items[1].name == "hello");
  14158. EXPECT_TRUE(items[1].content == "world");
  14159. EXPECT_TRUE(items[1].filename == "");
  14160. EXPECT_TRUE(items[1].content_type == "");
  14161. } else {
  14162. std::string body;
  14163. content_reader([&](const char *data, size_t data_length) {
  14164. body.append(data, data_length);
  14165. return true;
  14166. });
  14167. }
  14168. });
  14169. auto port = svr.bind_to_any_port("localhost");
  14170. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14171. auto se = detail::scope_exit([&] {
  14172. svr.stop();
  14173. t.join();
  14174. ASSERT_FALSE(svr.is_running());
  14175. });
  14176. svr.wait_until_ready();
  14177. {
  14178. std::string data(1024 * 1024 * 2, '&');
  14179. std::stringstream buffer;
  14180. buffer << data;
  14181. SSLClient cli("localhost", port);
  14182. cli.enable_server_certificate_verification(false);
  14183. UploadFormDataItems items{
  14184. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14185. {"hello", "world", "", ""},
  14186. };
  14187. auto res = cli.Put("/put", items);
  14188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14189. ASSERT_EQ(StatusCode::OK_200, res->status);
  14190. }
  14191. }
  14192. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14193. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14194. svr.Put("/put_customboundary",
  14195. [&](const Request &req, const Response & /*res*/,
  14196. const ContentReader &content_reader) {
  14197. if (req.is_multipart_form_data()) {
  14198. std::vector<FormData> items;
  14199. content_reader(
  14200. [&](const FormData &file) {
  14201. items.push_back(file);
  14202. return true;
  14203. },
  14204. [&](const char *data, size_t data_length) {
  14205. items.back().content.append(data, data_length);
  14206. return true;
  14207. });
  14208. EXPECT_TRUE(std::string(items[0].name) == "document");
  14209. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14210. EXPECT_TRUE(items[0].filename == "2MB_data");
  14211. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14212. EXPECT_TRUE(items[1].name == "hello");
  14213. EXPECT_TRUE(items[1].content == "world");
  14214. EXPECT_TRUE(items[1].filename == "");
  14215. EXPECT_TRUE(items[1].content_type == "");
  14216. } else {
  14217. std::string body;
  14218. content_reader([&](const char *data, size_t data_length) {
  14219. body.append(data, data_length);
  14220. return true;
  14221. });
  14222. }
  14223. });
  14224. auto port = svr.bind_to_any_port("localhost");
  14225. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14226. auto se = detail::scope_exit([&] {
  14227. svr.stop();
  14228. t.join();
  14229. ASSERT_FALSE(svr.is_running());
  14230. });
  14231. svr.wait_until_ready();
  14232. {
  14233. std::string data(1024 * 1024 * 2, '&');
  14234. std::stringstream buffer;
  14235. buffer << data;
  14236. SSLClient cli("localhost", port);
  14237. cli.enable_server_certificate_verification(false);
  14238. UploadFormDataItems items{
  14239. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14240. {"hello", "world", "", ""},
  14241. };
  14242. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. ASSERT_EQ(StatusCode::OK_200, res->status);
  14245. }
  14246. }
  14247. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14248. std::string data(1024 * 1024 * 2, '&');
  14249. std::stringstream buffer;
  14250. buffer << data;
  14251. Client cli("https://localhost:8080");
  14252. cli.enable_server_certificate_verification(false);
  14253. UploadFormDataItems items{
  14254. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14255. {"hello", "world", "", ""},
  14256. };
  14257. for (const char &c : " \t\r\n") {
  14258. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14259. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14260. ASSERT_FALSE(res);
  14261. }
  14262. }
  14263. TEST(MultipartFormDataTest, AlternateFilename) {
  14264. auto handled = false;
  14265. Server svr;
  14266. svr.Post("/test", [&](const Request &req, Response &res) {
  14267. ASSERT_EQ(2u, req.form.files.size());
  14268. ASSERT_EQ(1u, req.form.fields.size());
  14269. // Test files
  14270. const auto &file1 = req.form.get_file("file1");
  14271. ASSERT_EQ("file1", file1.name);
  14272. ASSERT_EQ("A.txt", file1.filename);
  14273. ASSERT_EQ("text/plain", file1.content_type);
  14274. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14275. const auto &file2 = req.form.get_file("file2");
  14276. ASSERT_EQ("file2", file2.name);
  14277. ASSERT_EQ("a.html", file2.filename);
  14278. ASSERT_EQ("text/html", file2.content_type);
  14279. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14280. file2.content);
  14281. // Test text field
  14282. const auto &text = req.form.get_field("text");
  14283. ASSERT_EQ("text default", text);
  14284. res.set_content("ok", "text/plain");
  14285. handled = true;
  14286. });
  14287. thread t = thread([&] { svr.listen(HOST, PORT); });
  14288. auto se = detail::scope_exit([&] {
  14289. svr.stop();
  14290. t.join();
  14291. ASSERT_FALSE(svr.is_running());
  14292. ASSERT_TRUE(handled);
  14293. });
  14294. svr.wait_until_ready();
  14295. auto req = "POST /test HTTP/1.1\r\n"
  14296. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14297. "Content-Length: 399\r\n"
  14298. "\r\n"
  14299. "----------\r\n"
  14300. "Content-Disposition: form-data; name=\"text\"\r\n"
  14301. "\r\n"
  14302. "text default\r\n"
  14303. "----------\r\n"
  14304. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14305. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14306. "Content-Type: text/plain\r\n"
  14307. "\r\n"
  14308. "Content of a.txt.\r\n"
  14309. "\r\n"
  14310. "----------\r\n"
  14311. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14312. "\"a.html\"\r\n"
  14313. "Content-Type: text/html\r\n"
  14314. "\r\n"
  14315. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14316. "\r\n"
  14317. "------------\r\n";
  14318. ASSERT_TRUE(send_request(1, req));
  14319. }
  14320. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14321. auto handled = false;
  14322. Server svr;
  14323. svr.Post("/test", [&](const Request &req, Response &res) {
  14324. // Case-insensitive "utf-8''" prefix with a long value
  14325. const auto &file = req.form.get_file("file1");
  14326. ASSERT_EQ("file1", file.name);
  14327. // 8000 chars exercises both the Content-Disposition parser and the
  14328. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14329. // Prior to the fix, std::regex_match on this header would cause O(N)
  14330. // stack recursion in libstdc++, leading to SIGSEGV.
  14331. std::string expected_filename(8000, 'A');
  14332. ASSERT_EQ(expected_filename, file.filename);
  14333. res.set_content("ok", "text/plain");
  14334. handled = true;
  14335. });
  14336. thread t = thread([&] { svr.listen(HOST, PORT); });
  14337. auto se = detail::scope_exit([&] {
  14338. svr.stop();
  14339. t.join();
  14340. ASSERT_FALSE(svr.is_running());
  14341. ASSERT_TRUE(handled);
  14342. });
  14343. svr.wait_until_ready();
  14344. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14345. // Regression test for GHSA-qq6v-r583-3h69
  14346. std::string long_filename(8000, 'A');
  14347. std::string body = "----------\r\n"
  14348. "Content-Disposition: form-data; name=\"file1\"; "
  14349. "filename*=\"Utf-8''" +
  14350. long_filename +
  14351. "\"\r\n"
  14352. "\r\n"
  14353. "hello\r\n"
  14354. "------------\r\n";
  14355. auto req = "POST /test HTTP/1.1\r\n"
  14356. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14357. "Content-Length: " +
  14358. std::to_string(body.size()) + "\r\n\r\n" + body;
  14359. ASSERT_TRUE(send_request(1, req));
  14360. }
  14361. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14362. auto handled = false;
  14363. Server svr;
  14364. svr.Post("/test", [&](const Request &req, Response &) {
  14365. ASSERT_EQ(2u, req.form.fields.size());
  14366. const auto &text1 = req.form.get_field("text1");
  14367. ASSERT_EQ("text1", text1);
  14368. const auto &text2 = req.form.get_field("text2");
  14369. ASSERT_EQ("text2", text2);
  14370. handled = true;
  14371. });
  14372. thread t = thread([&] { svr.listen(HOST, PORT); });
  14373. auto se = detail::scope_exit([&] {
  14374. svr.stop();
  14375. t.join();
  14376. ASSERT_FALSE(svr.is_running());
  14377. ASSERT_TRUE(handled);
  14378. });
  14379. svr.wait_until_ready();
  14380. auto req = "POST /test HTTP/1.1\r\n"
  14381. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14382. "Content-Length: 146\r\n"
  14383. "\r\n----------\r\n"
  14384. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14385. "\r\n"
  14386. "text1"
  14387. "\r\n----------\r\n"
  14388. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14389. "\r\n"
  14390. "text2"
  14391. "\r\n------------";
  14392. std::string response;
  14393. ASSERT_TRUE(send_request(1, req, &response));
  14394. ASSERT_EQ("200", response.substr(9, 3));
  14395. }
  14396. TEST(MultipartFormDataTest, ContentLength) {
  14397. auto handled = false;
  14398. Server svr;
  14399. svr.Post("/test", [&](const Request &req, Response &) {
  14400. ASSERT_EQ(2u, req.form.fields.size());
  14401. const auto &text1 = req.form.get_field("text1");
  14402. ASSERT_EQ("text1", text1);
  14403. const auto &text2 = req.form.get_field("text2");
  14404. ASSERT_EQ("text2", text2);
  14405. handled = true;
  14406. });
  14407. thread t = thread([&] { svr.listen(HOST, PORT); });
  14408. auto se = detail::scope_exit([&] {
  14409. svr.stop();
  14410. t.join();
  14411. ASSERT_FALSE(svr.is_running());
  14412. ASSERT_TRUE(handled);
  14413. });
  14414. svr.wait_until_ready();
  14415. auto req = "POST /test HTTP/1.1\r\n"
  14416. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14417. "Content-Length: 167\r\n"
  14418. "\r\n----------\r\n"
  14419. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14420. "Content-Length: 5\r\n"
  14421. "\r\n"
  14422. "text1"
  14423. "\r\n----------\r\n"
  14424. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14425. "\r\n"
  14426. "text2"
  14427. "\r\n------------\r\n";
  14428. std::string response;
  14429. ASSERT_TRUE(send_request(1, req, &response));
  14430. ASSERT_EQ("200", response.substr(9, 3));
  14431. }
  14432. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14433. auto handled = false;
  14434. Server svr;
  14435. svr.Post("/test", [&](const Request &req, Response &) {
  14436. ASSERT_EQ(2u, req.form.fields.size());
  14437. const auto &text1 = req.form.get_field("text1");
  14438. ASSERT_EQ("text1", text1);
  14439. // TODO: Add header access for text fields if needed
  14440. const auto &text2 = req.form.get_field("text2");
  14441. ASSERT_EQ("text2", text2);
  14442. // TODO: Header access for text fields needs to be implemented
  14443. // auto &headers = it->second.headers;
  14444. // ASSERT_EQ(3U, headers.size());
  14445. // auto custom_header = headers.find("x-whatever");
  14446. // ASSERT_TRUE(custom_header != headers.end());
  14447. // ASSERT_NE("customvalue", custom_header->second);
  14448. // ASSERT_EQ("CustomValue", custom_header->second);
  14449. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14450. handled = true;
  14451. });
  14452. thread t = thread([&] { svr.listen(HOST, PORT); });
  14453. auto se = detail::scope_exit([&] {
  14454. svr.stop();
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. ASSERT_TRUE(handled);
  14458. });
  14459. svr.wait_until_ready();
  14460. auto req = "POST /test HTTP/1.1\r\n"
  14461. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14462. "Content-Length: 232\r\n"
  14463. "\r\n----------\r\n"
  14464. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14465. "Content-Length: 5\r\n"
  14466. "X-Test: 1\r\n"
  14467. "\r\n"
  14468. "text1"
  14469. "\r\n----------\r\n"
  14470. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14471. "Content-Type: text/plain\r\n"
  14472. "X-Whatever: CustomValue\r\n"
  14473. "\r\n"
  14474. "text2"
  14475. "\r\n------------\r\n"
  14476. "That should be disregarded. Not even read";
  14477. std::string response;
  14478. ASSERT_TRUE(send_request(1, req, &response));
  14479. ASSERT_EQ("200", response.substr(9, 3));
  14480. }
  14481. TEST(MultipartFormDataTest, LargeHeader) {
  14482. auto handled = false;
  14483. Server svr;
  14484. svr.Post("/test", [&](const Request &req, Response &) {
  14485. ASSERT_EQ(1u, req.form.fields.size());
  14486. const auto &text = req.form.get_field("name1");
  14487. ASSERT_EQ("text1", text);
  14488. handled = true;
  14489. });
  14490. thread t = thread([&] { svr.listen(HOST, PORT); });
  14491. auto se = detail::scope_exit([&] {
  14492. svr.stop();
  14493. t.join();
  14494. ASSERT_FALSE(svr.is_running());
  14495. ASSERT_TRUE(handled);
  14496. });
  14497. svr.wait_until_ready();
  14498. auto boundary = std::string("cpp-httplib-multipart-data");
  14499. std::string content = "--" + boundary +
  14500. "\r\n"
  14501. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14502. "\r\n"
  14503. "text1\r\n"
  14504. "--" +
  14505. boundary + "--\r\n";
  14506. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14507. "Content-Type: multipart/form-data;boundary=" +
  14508. boundary +
  14509. "\r\n"
  14510. "Content-Length: " +
  14511. std::to_string(content.size()) +
  14512. "\r\n"
  14513. "Dummy-Header: ";
  14514. std::string header_suffix = "\r\n"
  14515. "\r\n";
  14516. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14517. size_t header_dummy_size =
  14518. read_buff_size -
  14519. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14520. auto header_dummy = std::string(header_dummy_size, '@');
  14521. auto req = header_prefix + header_dummy + header_suffix + content;
  14522. std::string response;
  14523. ASSERT_TRUE(send_request(1, req, &response));
  14524. ASSERT_EQ("200", response.substr(9, 3));
  14525. }
  14526. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14527. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14528. // (not chunked Transfer-Encoding) after the streaming refactor.
  14529. auto handled = false;
  14530. Server svr;
  14531. svr.Post("/upload", [&](const Request &req, Response &res) {
  14532. auto cl_it = req.headers.find("Content-Length");
  14533. EXPECT_TRUE(cl_it != req.headers.end());
  14534. auto te_it = req.headers.find("Transfer-Encoding");
  14535. EXPECT_TRUE(te_it == req.headers.end());
  14536. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14537. res.set_content("ok", "text/plain");
  14538. handled = true;
  14539. });
  14540. auto port = svr.bind_to_any_port(HOST);
  14541. auto t = thread([&] { svr.listen_after_bind(); });
  14542. auto se = detail::scope_exit([&] {
  14543. svr.stop();
  14544. t.join();
  14545. ASSERT_FALSE(svr.is_running());
  14546. ASSERT_TRUE(handled);
  14547. });
  14548. svr.wait_until_ready();
  14549. UploadFormDataItems items = {
  14550. {"field1", "hello", "", "text/plain"},
  14551. {"file1", "world", "test.txt", "application/octet-stream"},
  14552. };
  14553. Client cli(HOST, port);
  14554. auto res = cli.Post("/upload", {}, items);
  14555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14556. EXPECT_EQ(StatusCode::OK_200, res->status);
  14557. }
  14558. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14559. // Verify that make_multipart_content_provider coalesces many small segments
  14560. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14561. constexpr size_t kItemCount = 1000;
  14562. UploadFormDataItems items;
  14563. items.reserve(kItemCount);
  14564. for (size_t i = 0; i < kItemCount; i++) {
  14565. items.push_back(
  14566. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14567. }
  14568. const std::string boundary = "----test-boundary";
  14569. auto content_length = detail::get_multipart_content_length(items, boundary);
  14570. auto provider = detail::make_multipart_content_provider(items, boundary);
  14571. // Drive the provider the same way write_content_with_progress does
  14572. size_t write_count = 0;
  14573. size_t total_bytes = 0;
  14574. DataSink sink;
  14575. size_t offset = 0;
  14576. sink.write = [&](const char *d, size_t l) -> bool {
  14577. (void)d;
  14578. write_count++;
  14579. total_bytes += l;
  14580. offset += l;
  14581. return true;
  14582. };
  14583. sink.is_writable = []() -> bool { return true; };
  14584. while (offset < content_length) {
  14585. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14586. }
  14587. EXPECT_EQ(content_length, total_bytes);
  14588. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14589. // With buffering into 64KB blocks, write_count should be much smaller.
  14590. auto segment_count = 3 * kItemCount + 1;
  14591. EXPECT_LT(write_count, segment_count / 10);
  14592. }
  14593. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14594. // Integration test: send many UploadFormDataItems and verify the server
  14595. // receives all of them correctly (#2410).
  14596. constexpr size_t kItemCount = 500;
  14597. auto handled = false;
  14598. Server svr;
  14599. svr.Post("/upload", [&](const Request &req, Response &res) {
  14600. EXPECT_EQ(kItemCount, req.form.fields.size());
  14601. for (size_t i = 0; i < kItemCount; i++) {
  14602. auto key = "field" + std::to_string(i);
  14603. auto val = "value" + std::to_string(i);
  14604. auto it = req.form.fields.find(key);
  14605. if (it != req.form.fields.end()) {
  14606. EXPECT_EQ(val, it->second.content);
  14607. } else {
  14608. ADD_FAILURE() << "Missing field: " << key;
  14609. }
  14610. }
  14611. res.set_content("ok", "text/plain");
  14612. handled = true;
  14613. });
  14614. auto port = svr.bind_to_any_port(HOST);
  14615. auto t = thread([&] { svr.listen_after_bind(); });
  14616. auto se = detail::scope_exit([&] {
  14617. svr.stop();
  14618. t.join();
  14619. ASSERT_FALSE(svr.is_running());
  14620. ASSERT_TRUE(handled);
  14621. });
  14622. svr.wait_until_ready();
  14623. UploadFormDataItems items;
  14624. items.reserve(kItemCount);
  14625. for (size_t i = 0; i < kItemCount; i++) {
  14626. items.push_back(
  14627. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14628. }
  14629. Client cli(HOST, port);
  14630. auto res = cli.Post("/upload", items);
  14631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14632. EXPECT_EQ(StatusCode::OK_200, res->status);
  14633. }
  14634. TEST(MultipartFormDataTest, MakeFileProvider) {
  14635. // Verify make_file_provider sends a file's contents correctly.
  14636. const std::string file_content(4096, 'Z');
  14637. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14638. {
  14639. std::ofstream ofs(tmp_path, std::ios::binary);
  14640. ofs.write(file_content.data(),
  14641. static_cast<std::streamsize>(file_content.size()));
  14642. }
  14643. auto handled = false;
  14644. Server svr;
  14645. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14646. const ContentReader &content_reader) {
  14647. ASSERT_TRUE(req.is_multipart_form_data());
  14648. std::vector<FormData> items;
  14649. content_reader(
  14650. [&](const FormData &file) {
  14651. items.push_back(file);
  14652. return true;
  14653. },
  14654. [&](const char *data, size_t data_length) {
  14655. items.back().content.append(data, data_length);
  14656. return true;
  14657. });
  14658. ASSERT_EQ(1u, items.size());
  14659. EXPECT_EQ("myfile", items[0].name);
  14660. EXPECT_EQ("data.bin", items[0].filename);
  14661. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14662. EXPECT_EQ(file_content, items[0].content);
  14663. handled = true;
  14664. });
  14665. auto port = svr.bind_to_any_port(HOST);
  14666. auto t = thread([&] { svr.listen_after_bind(); });
  14667. auto se = detail::scope_exit([&] {
  14668. svr.stop();
  14669. t.join();
  14670. ASSERT_FALSE(svr.is_running());
  14671. ASSERT_TRUE(handled);
  14672. std::remove(tmp_path.c_str());
  14673. });
  14674. svr.wait_until_ready();
  14675. FormDataProviderItems providers;
  14676. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14677. "application/octet-stream"));
  14678. Client cli(HOST, port);
  14679. auto res = cli.Post("/upload", {}, {}, providers);
  14680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14681. EXPECT_EQ(StatusCode::OK_200, res->status);
  14682. }
  14683. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14684. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14685. // (100) headers is rejected with a 400 Bad Request response.
  14686. Server svr;
  14687. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14688. res.set_content("ok", "text/plain");
  14689. });
  14690. thread t = thread([&] { svr.listen(HOST, PORT); });
  14691. auto se = detail::scope_exit([&] {
  14692. svr.stop();
  14693. t.join();
  14694. ASSERT_FALSE(svr.is_running());
  14695. });
  14696. svr.wait_until_ready();
  14697. // Build a multipart part with 101 custom headers (exceeding
  14698. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14699. std::stringstream body;
  14700. body << "--simpleboundary\r\n"
  14701. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14702. for (int i = 0; i < 101; i++) {
  14703. body << "X-Custom-Header-" << i << ": value\r\n";
  14704. }
  14705. body << "\r\n"
  14706. << "value1\r\n"
  14707. << "--simpleboundary--\r\n";
  14708. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14709. Client cli(HOST, PORT);
  14710. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14713. }
  14714. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14715. // A body that never contains the declared boundary must not be accumulated
  14716. // while the parser waits for it. Buffering it would also make every read
  14717. // rescan everything seen so far, which is quadratic in the body size.
  14718. Server svr;
  14719. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14720. res.set_content("ok", "text/plain");
  14721. });
  14722. auto port = svr.bind_to_any_port(HOST);
  14723. thread 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. });
  14729. svr.wait_until_ready();
  14730. Client cli(HOST, port);
  14731. cli.set_read_timeout(60, 0);
  14732. cli.set_write_timeout(60, 0);
  14733. // '-' is the worst case: it matches the first character of the boundary, so
  14734. // every position has to be checked against it.
  14735. auto post_dashes = [&](size_t size) {
  14736. const std::string body(size, '-');
  14737. auto start = std::chrono::steady_clock::now();
  14738. auto res =
  14739. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14740. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14741. std::chrono::steady_clock::now() - start)
  14742. .count();
  14743. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14744. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14745. return ms;
  14746. };
  14747. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14748. // Windows.
  14749. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14750. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14751. // Comparing the two sizes rather than checking an absolute duration keeps
  14752. // this meaningful across build types and CI load, both of which move the
  14753. // absolute numbers by more than an order of magnitude. Four times the bytes
  14754. // costs about four times the time when parsing is linear, and about sixteen
  14755. // times when the body is buffered and rescanned.
  14756. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14757. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14758. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14759. << "ms, which suggests the body is being buffered and rescanned";
  14760. }
  14761. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14762. // A boundary can only be followed by CRLF or by "--", so anything else is
  14763. // malformed no matter what comes next. The parser must say so right away
  14764. // instead of buffering the rest of the declared body.
  14765. Server svr;
  14766. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14767. res.set_content("ok", "text/plain");
  14768. });
  14769. auto port = svr.bind_to_any_port(HOST);
  14770. thread t = thread([&] { svr.listen_after_bind(); });
  14771. auto se = detail::scope_exit([&] {
  14772. svr.stop();
  14773. t.join();
  14774. ASSERT_FALSE(svr.is_running());
  14775. });
  14776. svr.wait_until_ready();
  14777. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14778. // buffers instead of failing would still be waiting for the remaining bytes.
  14779. const std::string body = "--zzzz\r\n"
  14780. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14781. "\r\n"
  14782. "text1"
  14783. "\r\n--zzzzXX";
  14784. const std::string req = "POST /post HTTP/1.1\r\n"
  14785. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14786. "Content-Length: 1048576\r\n"
  14787. "\r\n" +
  14788. body;
  14789. std::string response;
  14790. ASSERT_TRUE(send_request(3, req, &response, port));
  14791. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14792. EXPECT_EQ("400", response.substr(9, 3));
  14793. }
  14794. // Posts a multipart body split into two writes, so that the server sees the
  14795. // split at whatever offset the caller chose, and expects the single "text1"
  14796. // field to come through.
  14797. static void expect_split_multipart_ok(const std::string &body1,
  14798. const std::string &body2) {
  14799. auto handled = false;
  14800. Server svr;
  14801. svr.Post("/post", [&](const Request &req, Response &) {
  14802. EXPECT_EQ(1u, req.form.fields.size());
  14803. EXPECT_EQ("text1", req.form.get_field("text1"));
  14804. handled = true;
  14805. });
  14806. auto port = svr.bind_to_any_port(HOST);
  14807. thread t = thread([&] { svr.listen_after_bind(); });
  14808. auto se = detail::scope_exit([&] {
  14809. svr.stop();
  14810. t.join();
  14811. ASSERT_FALSE(svr.is_running());
  14812. ASSERT_TRUE(handled);
  14813. });
  14814. svr.wait_until_ready();
  14815. // "Connection: close" makes the server close once it has answered, so the
  14816. // response drain ends immediately instead of idling until the read timeout.
  14817. const std::string head =
  14818. "POST /post HTTP/1.1\r\n"
  14819. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14820. "Connection: close\r\n"
  14821. "Content-Length: " +
  14822. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14823. std::string response;
  14824. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14825. ASSERT_GE(response.size(), 12u) << "no response";
  14826. EXPECT_EQ("200", response.substr(9, 3));
  14827. }
  14828. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14829. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14830. // ignored, including when it does not arrive in the same read as the
  14831. // close-delimiter itself.
  14832. expect_split_multipart_ok("--zzzz\r\n"
  14833. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14834. "\r\n"
  14835. "text1"
  14836. "\r\n--zzzz--",
  14837. "\r\nthis epilogue must be ignored\r\n");
  14838. }
  14839. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14840. // The initial boundary may be preceded by a preamble of any length and may
  14841. // straddle a read boundary. Discarding data while waiting for it must not
  14842. // throw away a partial boundary sitting at the end of the buffer.
  14843. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14844. "zz\r\n"
  14845. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14846. "\r\n"
  14847. "text1"
  14848. "\r\n--zzzz--\r\n");
  14849. }
  14850. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14851. // The received boundary was only checked for being non-empty, so it could be
  14852. // as long as a header is allowed to be. The parser scans the body for
  14853. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14854. // costs a nearly full comparison at nearly every position, making the
  14855. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14856. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14857. Server svr;
  14858. svr.Post("/post", [](const Request &req, Response &res) {
  14859. EXPECT_EQ(1u, req.form.fields.size());
  14860. EXPECT_EQ("text1", req.form.get_field("text1"));
  14861. res.set_content("ok", "text/plain");
  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. });
  14870. svr.wait_until_ready();
  14871. Client cli(HOST, port);
  14872. auto post_with_boundary_of_length = [&](size_t len) {
  14873. const std::string boundary(len, 'a');
  14874. const std::string body =
  14875. "--" + boundary +
  14876. "\r\n"
  14877. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14878. "\r\n"
  14879. "text1"
  14880. "\r\n--" +
  14881. boundary + "--\r\n";
  14882. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14883. };
  14884. auto res = post_with_boundary_of_length(70);
  14885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14886. EXPECT_EQ(StatusCode::OK_200, res->status);
  14887. res = post_with_boundary_of_length(71);
  14888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14889. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14890. }
  14891. TEST(MakeFileBodyTest, Basic) {
  14892. const std::string file_content(4096, 'Z');
  14893. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14894. {
  14895. std::ofstream ofs(tmp_path, std::ios::binary);
  14896. ofs.write(file_content.data(),
  14897. static_cast<std::streamsize>(file_content.size()));
  14898. }
  14899. auto handled = false;
  14900. Server svr;
  14901. svr.Post("/upload", [&](const Request &req, Response &res) {
  14902. EXPECT_EQ(file_content, req.body);
  14903. handled = true;
  14904. res.status = StatusCode::OK_200;
  14905. });
  14906. auto port = svr.bind_to_any_port(HOST);
  14907. auto t = thread([&] { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. t.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. ASSERT_TRUE(handled);
  14913. std::remove(tmp_path.c_str());
  14914. });
  14915. svr.wait_until_ready();
  14916. auto fb = make_file_body(tmp_path);
  14917. ASSERT_GT(fb.first, 0u);
  14918. Client cli(HOST, port);
  14919. auto res =
  14920. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14922. EXPECT_EQ(StatusCode::OK_200, res->status);
  14923. }
  14924. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14925. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14926. {
  14927. std::ofstream ofs(path, std::ios::binary);
  14928. const std::string content(100, 'A');
  14929. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14930. }
  14931. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14932. auto body = make_file_body(path);
  14933. ASSERT_EQ(100u, body.first);
  14934. ASSERT_TRUE(static_cast<bool>(body.second));
  14935. // Rewritten shorter after its length was measured - and, on a server, after
  14936. // that length has already gone out as Content-Length.
  14937. {
  14938. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14939. const std::string content(10, 'A');
  14940. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14941. }
  14942. std::string written;
  14943. DataSink sink;
  14944. sink.write = [&](const char *d, size_t l) {
  14945. written.append(d, l);
  14946. return true;
  14947. };
  14948. // The provider has to report failure. write_content_with_progress() advances
  14949. // its offset only by what was written, so a provider that returns true
  14950. // without completing the length it promised is called again straight away,
  14951. // and again.
  14952. EXPECT_FALSE(body.second(0, body.first, sink));
  14953. EXPECT_EQ(std::string(10, 'A'), written);
  14954. }
  14955. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14956. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14957. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14958. {
  14959. std::ofstream ofs(path, std::ios::binary);
  14960. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14961. }
  14962. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14963. auto body = make_file_body(path);
  14964. ASSERT_EQ(content.size(), body.first);
  14965. ASSERT_TRUE(static_cast<bool>(body.second));
  14966. std::string written;
  14967. DataSink sink;
  14968. sink.write = [&](const char *d, size_t l) {
  14969. written.append(d, l);
  14970. return true;
  14971. };
  14972. EXPECT_TRUE(body.second(0, body.first, sink));
  14973. EXPECT_EQ(content, written);
  14974. }
  14975. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14976. static constexpr unsigned int number_of_tasks{1000000};
  14977. std::atomic_uint count{0};
  14978. std::unique_ptr<TaskQueue> task_queue{
  14979. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14980. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14981. auto queued = task_queue->enqueue(
  14982. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14983. EXPECT_TRUE(queued);
  14984. }
  14985. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14986. task_queue->shutdown();
  14987. #else
  14988. EXPECT_NO_THROW(task_queue->shutdown());
  14989. #endif
  14990. EXPECT_EQ(number_of_tasks, count.load());
  14991. }
  14992. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14993. static constexpr unsigned int number_of_tasks{1000000};
  14994. static constexpr unsigned int qlimit{2};
  14995. unsigned int queued_count{0};
  14996. std::atomic_uint count{0};
  14997. std::unique_ptr<TaskQueue> task_queue{
  14998. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14999. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15000. if (task_queue->enqueue(
  15001. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15002. queued_count++;
  15003. }
  15004. }
  15005. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15006. task_queue->shutdown();
  15007. #else
  15008. EXPECT_NO_THROW(task_queue->shutdown());
  15009. #endif
  15010. EXPECT_EQ(queued_count, count.load());
  15011. EXPECT_TRUE(queued_count <= number_of_tasks);
  15012. EXPECT_TRUE(queued_count >= qlimit);
  15013. }
  15014. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15015. // Use a short idle timeout so a dynamic thread spawns, times out and
  15016. // exits during the test, and the pool keeps working afterwards.
  15017. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15018. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15019. /*idle_timeout_sec=*/1}};
  15020. std::atomic_uint count{0};
  15021. std::condition_variable cv;
  15022. std::mutex mtx;
  15023. bool release = false;
  15024. // Block the base thread so the second task spawns a dynamic thread.
  15025. EXPECT_TRUE(task_queue->enqueue([&] {
  15026. std::unique_lock<std::mutex> lock(mtx);
  15027. while (!release) {
  15028. cv.wait(lock);
  15029. }
  15030. count++;
  15031. }));
  15032. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15033. // Let the dynamic thread finish its task and exceed the idle timeout.
  15034. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15035. {
  15036. std::unique_lock<std::mutex> lock(mtx);
  15037. release = true;
  15038. }
  15039. cv.notify_all();
  15040. // The pool must still accept and run tasks after the dynamic thread exited.
  15041. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15042. task_queue->shutdown();
  15043. EXPECT_EQ(3u, count.load());
  15044. }
  15045. TEST(TaskQueueTest, MaxQueuedRequests) {
  15046. static constexpr unsigned int qlimit{3};
  15047. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15048. std::condition_variable sem_cv;
  15049. std::mutex sem_mtx;
  15050. int credits = 0;
  15051. bool queued;
  15052. /* Fill up the queue with tasks that will block until we give them credits to
  15053. * complete. */
  15054. for (unsigned int n = 0; n <= qlimit;) {
  15055. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15056. std::unique_lock<std::mutex> lock(sem_mtx);
  15057. while (credits <= 0) {
  15058. sem_cv.wait(lock);
  15059. }
  15060. /* Consume the credit and signal the test code if they are all gone. */
  15061. if (--credits == 0) { sem_cv.notify_one(); }
  15062. });
  15063. if (n < qlimit) {
  15064. /* The first qlimit enqueues must succeed. */
  15065. EXPECT_TRUE(queued);
  15066. } else {
  15067. /* The last one will succeed only when the worker thread
  15068. * starts and dequeues the first blocking task. Although
  15069. * not necessary for the correctness of this test, we sleep for
  15070. * a short while to avoid busy waiting. */
  15071. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15072. }
  15073. if (queued) { n++; }
  15074. }
  15075. /* Further enqueues must fail since the queue is full. */
  15076. for (auto i = 0; i < 4; i++) {
  15077. queued = task_queue->enqueue([] {});
  15078. EXPECT_FALSE(queued);
  15079. }
  15080. /* Give the credits to allow the previous tasks to complete. */
  15081. {
  15082. std::unique_lock<std::mutex> lock(sem_mtx);
  15083. credits += qlimit + 1;
  15084. }
  15085. sem_cv.notify_all();
  15086. /* Wait for all the credits to be consumed. */
  15087. {
  15088. std::unique_lock<std::mutex> lock(sem_mtx);
  15089. while (credits > 0) {
  15090. sem_cv.wait(lock);
  15091. }
  15092. }
  15093. /* Check that we are able again to enqueue at least qlimit tasks. */
  15094. for (unsigned int i = 0; i < qlimit; i++) {
  15095. queued = task_queue->enqueue([] {});
  15096. EXPECT_TRUE(queued);
  15097. }
  15098. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15099. task_queue->shutdown();
  15100. #else
  15101. EXPECT_NO_THROW(task_queue->shutdown());
  15102. #endif
  15103. }
  15104. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15105. Server svr;
  15106. std::string method;
  15107. std::string body;
  15108. auto has_content_length = false;
  15109. auto has_transfer_encoding = false;
  15110. std::atomic<int> bad_requests{0};
  15111. // Leftover body bytes get parsed as a malformed request and answered with
  15112. // 400
  15113. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15114. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15115. });
  15116. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15117. res.set_redirect("/down", StatusCode::SeeOther_303);
  15118. });
  15119. svr.Get("/down", [&](const Request &req, Response &res) {
  15120. method = req.method;
  15121. body = req.body;
  15122. has_content_length = req.has_header("Content-Length");
  15123. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15124. res.set_content("ok", "text/plain");
  15125. });
  15126. auto port = svr.bind_to_any_port(HOST);
  15127. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15128. auto se = detail::scope_exit([&] {
  15129. svr.stop();
  15130. thread.join();
  15131. ASSERT_FALSE(svr.is_running());
  15132. });
  15133. svr.wait_until_ready();
  15134. const std::string payload = "SECRET-BODY";
  15135. auto check = [&](Client &cli, const Result &res) {
  15136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15137. EXPECT_EQ(StatusCode::OK_200, res->status);
  15138. EXPECT_EQ("ok", res->body);
  15139. EXPECT_EQ("GET", method);
  15140. EXPECT_TRUE(body.empty());
  15141. EXPECT_FALSE(has_content_length);
  15142. EXPECT_FALSE(has_transfer_encoding);
  15143. // Nothing of the original body may be left on the connection
  15144. auto res2 = cli.Get("/down");
  15145. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15146. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15147. EXPECT_EQ("ok", res2->body);
  15148. EXPECT_EQ(0, bad_requests);
  15149. };
  15150. // With content length
  15151. {
  15152. Client cli(HOST, port);
  15153. cli.set_keep_alive(true);
  15154. cli.set_follow_location(true);
  15155. auto res = cli.Post(
  15156. "/up", payload.size(),
  15157. [&](size_t offset, size_t length, DataSink &sink) {
  15158. return sink.write(payload.data() + offset, length);
  15159. },
  15160. "text/plain");
  15161. check(cli, res);
  15162. }
  15163. // Without content length (chunked)
  15164. {
  15165. Client cli(HOST, port);
  15166. cli.set_keep_alive(true);
  15167. cli.set_follow_location(true);
  15168. auto res = cli.Post(
  15169. "/up",
  15170. [&](size_t /*offset*/, DataSink &sink) {
  15171. sink.write(payload.data(), payload.size());
  15172. sink.done();
  15173. return true;
  15174. },
  15175. "text/plain");
  15176. check(cli, res);
  15177. }
  15178. }
  15179. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15180. Server svr;
  15181. std::string target;
  15182. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15183. // Echo the still-encoded name back in the Location
  15184. const std::string prefix = "/start/";
  15185. res.status = StatusCode::Found_302;
  15186. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15187. });
  15188. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15189. target = req.target;
  15190. res.set_content("ok", "text/plain");
  15191. });
  15192. auto port = svr.bind_to_any_port(HOST);
  15193. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15194. auto se = detail::scope_exit([&] {
  15195. svr.stop();
  15196. thread.join();
  15197. ASSERT_FALSE(svr.is_running());
  15198. });
  15199. svr.wait_until_ready();
  15200. // Decoding the Location path would turn the first four into a path
  15201. // separator, a query delimiter, a fragment delimiter and a different
  15202. // percent-encoded octet. The rest must keep reaching the server as they are.
  15203. const std::vector<std::string> names = {
  15204. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15205. };
  15206. for (auto path_encode : {true, false}) {
  15207. Client cli(HOST, port);
  15208. cli.set_follow_location(true);
  15209. cli.set_path_encode(path_encode);
  15210. for (const auto &name : names) {
  15211. target.clear();
  15212. auto res = cli.Get("/start/" + name);
  15213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15214. EXPECT_EQ(StatusCode::OK_200, res->status);
  15215. EXPECT_EQ("/dest/" + name, target);
  15216. }
  15217. }
  15218. }
  15219. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15220. Server svr;
  15221. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15222. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15223. });
  15224. svr.Get("/hello", [](const Request &req, Response &res) {
  15225. res.set_content(req.get_param_value("key"), "text/plain");
  15226. });
  15227. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15228. auto se = detail::scope_exit([&] {
  15229. svr.stop();
  15230. thread.join();
  15231. ASSERT_FALSE(svr.is_running());
  15232. });
  15233. svr.wait_until_ready();
  15234. {
  15235. Client cli(HOST, PORT);
  15236. cli.set_follow_location(true);
  15237. auto res = cli.Get("/");
  15238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15239. EXPECT_EQ(StatusCode::OK_200, res->status);
  15240. EXPECT_EQ("val&key2=val2", res->body);
  15241. }
  15242. }
  15243. #endif
  15244. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15245. Server svr;
  15246. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15247. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15248. });
  15249. svr.Get("/hello", [](const Request &req, Response &res) {
  15250. res.set_content(req.get_param_value("key"), "text/plain");
  15251. });
  15252. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15253. auto se = detail::scope_exit([&] {
  15254. svr.stop();
  15255. thread.join();
  15256. ASSERT_FALSE(svr.is_running());
  15257. });
  15258. svr.wait_until_ready();
  15259. {
  15260. Client cli(HOST, PORT);
  15261. cli.set_follow_location(true);
  15262. auto res = cli.Get("/");
  15263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15264. EXPECT_EQ(StatusCode::OK_200, res->status);
  15265. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15266. }
  15267. }
  15268. TEST(RedirectTest, RedirectWithPlusInPath) {
  15269. Server svr;
  15270. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15271. res.set_redirect("/a+b");
  15272. });
  15273. // Route pattern uses regex; escape + as \\+
  15274. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15275. res.set_content(req.path, "text/plain");
  15276. });
  15277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15278. auto se = detail::scope_exit([&] {
  15279. svr.stop();
  15280. thread.join();
  15281. ASSERT_FALSE(svr.is_running());
  15282. });
  15283. svr.wait_until_ready();
  15284. {
  15285. Client cli(HOST, PORT);
  15286. cli.set_follow_location(true);
  15287. auto res = cli.Get("/");
  15288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15289. EXPECT_EQ(StatusCode::OK_200, res->status);
  15290. EXPECT_EQ("/a+b", res->body);
  15291. }
  15292. }
  15293. TEST(RedirectTest, ResolveRelativeLocation) {
  15294. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15295. const std::vector<std::pair<std::string, std::string>> cases = {
  15296. {"g", "/b/c/g"},
  15297. {"./g", "/b/c/g"},
  15298. {"g/", "/b/c/g/"},
  15299. {"?y", "/b/c/d;p?y"},
  15300. {"g?y", "/b/c/g?y"},
  15301. {"#s", "/b/c/d;p?q#s"},
  15302. {"g#s", "/b/c/g#s"},
  15303. {"g?y#s", "/b/c/g?y#s"},
  15304. {";x", "/b/c/;x"},
  15305. {"g;x", "/b/c/g;x"},
  15306. {".", "/b/c/"},
  15307. {"./", "/b/c/"},
  15308. {"..", "/b/"},
  15309. {"../", "/b/"},
  15310. {"../g", "/b/g"},
  15311. {"../..", "/"},
  15312. {"../../", "/"},
  15313. {"../../g", "/g"},
  15314. {"../../../g", "/g"},
  15315. {"g.", "/b/c/g."},
  15316. {".g", "/b/c/.g"},
  15317. {"g..", "/b/c/g.."},
  15318. {"..g", "/b/c/..g"},
  15319. {"./../g", "/b/g"},
  15320. {"./g/.", "/b/c/g/"},
  15321. {"g/./h", "/b/c/g/h"},
  15322. {"g/../h", "/b/c/h"},
  15323. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15324. {"g;x=1/../y", "/b/c/y"},
  15325. {"g?y/./x", "/b/c/g?y/./x"},
  15326. {"g#s/../x", "/b/c/g#s/../x"},
  15327. // Not relative-path references, so left for parse_url.
  15328. {"/g", "/g"},
  15329. {"//g", "//g"},
  15330. {"http://g/x", "http://g/x"},
  15331. {"g:h", "g:h"},
  15332. };
  15333. for (const auto &c : cases) {
  15334. EXPECT_EQ(c.second,
  15335. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15336. << c.first;
  15337. }
  15338. }
  15339. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15340. Server svr;
  15341. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15342. res.set_redirect(req.get_param_value("to"));
  15343. });
  15344. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15345. res.set_content(req.target, "text/plain");
  15346. });
  15347. svr.Get("/other", [](const Request &req, Response &res) {
  15348. res.set_content(req.target, "text/plain");
  15349. });
  15350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15351. auto se = detail::scope_exit([&] {
  15352. svr.stop();
  15353. thread.join();
  15354. ASSERT_FALSE(svr.is_running());
  15355. });
  15356. svr.wait_until_ready();
  15357. const std::vector<std::pair<std::string, std::string>> cases = {
  15358. {"next", "/dir/next"},
  15359. {"./next?x=1", "/dir/next?x=1"},
  15360. {"../other", "/other"},
  15361. };
  15362. for (const auto &c : cases) {
  15363. Client cli(HOST, PORT);
  15364. cli.set_follow_location(true);
  15365. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15366. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15367. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15368. EXPECT_EQ(c.second, res->body) << c.first;
  15369. }
  15370. }
  15371. #ifdef CPPHTTPLIB_SSL_ENABLED
  15372. TEST(RedirectTest, Issue2185_Online) {
  15373. SSLClient client("github.com");
  15374. client.set_follow_location(true);
  15375. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15376. "Coollab-Windows.zip");
  15377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15378. EXPECT_EQ(StatusCode::OK_200, res->status);
  15379. EXPECT_EQ(9920427U, res->body.size());
  15380. }
  15381. #endif
  15382. TEST(VulnerabilityTest, CRLFInjection) {
  15383. Server svr;
  15384. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15385. res.set_content("Hello 1", "text/plain");
  15386. });
  15387. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15388. res.set_content("Hello 2", "text/plain");
  15389. });
  15390. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15391. res.set_content("Hello 3", "text/plain");
  15392. });
  15393. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15394. res.set_content("Hello 4", "text/plain");
  15395. });
  15396. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15397. for (const auto &x : req.headers) {
  15398. auto key = x.first;
  15399. EXPECT_STRNE("evil", key.c_str());
  15400. }
  15401. });
  15402. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15403. auto se = detail::scope_exit([&] {
  15404. svr.stop();
  15405. thread.join();
  15406. ASSERT_FALSE(svr.is_running());
  15407. });
  15408. svr.wait_until_ready();
  15409. {
  15410. Client cli(HOST, PORT);
  15411. cli.Post("/test1", "A=B",
  15412. "application/x-www-form-urlencoded\r\nevil: hello1");
  15413. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15414. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15415. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15416. }
  15417. }
  15418. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15419. auto server_thread = std::thread([] {
  15420. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15421. default_socket_options(srv);
  15422. sockaddr_in addr{};
  15423. addr.sin_family = AF_INET;
  15424. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15425. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15426. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15427. ::listen(srv, 1);
  15428. sockaddr_in cli_addr{};
  15429. socklen_t cli_len = sizeof(cli_addr);
  15430. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15431. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15432. std::string buf_all;
  15433. char buf[2048];
  15434. ssize_t n;
  15435. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15436. buf_all.append(buf, static_cast<size_t>(n));
  15437. size_t pos;
  15438. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15439. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15440. auto e = request_block.find("\r\n");
  15441. if (e != std::string::npos) {
  15442. auto request_line = request_block.substr(0, e);
  15443. std::string msg =
  15444. "CRLF injection detected in request line: '" + request_line + "'";
  15445. EXPECT_FALSE(true) << msg;
  15446. }
  15447. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15448. ::send(cli,
  15449. #ifdef _WIN32
  15450. static_cast<const char *>(resp.c_str()),
  15451. static_cast<int>(resp.size()),
  15452. #else
  15453. resp.c_str(), resp.size(),
  15454. #endif
  15455. 0);
  15456. buf_all.erase(0, pos + 4);
  15457. }
  15458. }
  15459. detail::close_socket(cli);
  15460. detail::close_socket(srv);
  15461. });
  15462. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15463. auto cli = Client("127.0.0.1", PORT + 1);
  15464. auto headers = Headers{
  15465. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15466. {"Connection", "keep-alive"}};
  15467. auto res = cli.Get("/hi", headers);
  15468. EXPECT_FALSE(res);
  15469. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15470. server_thread.join();
  15471. }
  15472. // A request rejected before any byte reaches the socket must fail right away
  15473. // instead of waiting for a response the server will never send.
  15474. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15475. // The kernel completes the TCP handshake from the listen backlog, so the
  15476. // client connects, but nothing ever reads, responds or closes.
  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. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15484. ASSERT_EQ(0, ::listen(srv, 8));
  15485. auto cli = Client("127.0.0.1", PORT + 1);
  15486. cli.set_read_timeout(10, 0);
  15487. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15488. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15489. std::chrono::steady_clock::now() - start)
  15490. .count();
  15491. };
  15492. {
  15493. Request req;
  15494. req.method = "GE T";
  15495. req.path = "/";
  15496. auto start = std::chrono::steady_clock::now();
  15497. auto res = cli.send(req);
  15498. EXPECT_FALSE(res);
  15499. EXPECT_EQ(Error::Write, res.error());
  15500. EXPECT_LT(elapsed_ms(start), 1000);
  15501. }
  15502. {
  15503. auto start = std::chrono::steady_clock::now();
  15504. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15505. EXPECT_FALSE(res);
  15506. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15507. EXPECT_LT(elapsed_ms(start), 1000);
  15508. }
  15509. EXPECT_FALSE(cli.is_socket_open());
  15510. detail::close_socket(srv);
  15511. }
  15512. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15513. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15514. default_socket_options(srv);
  15515. sockaddr_in addr{};
  15516. addr.sin_family = AF_INET;
  15517. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15518. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15519. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15520. ASSERT_EQ(0, ::listen(srv, 1));
  15521. std::string received;
  15522. auto server_thread = std::thread([&] {
  15523. auto sock = ::accept(srv, nullptr, nullptr);
  15524. if (sock == INVALID_SOCKET) { return; }
  15525. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15526. char buf[2048];
  15527. ssize_t n;
  15528. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15529. received.append(buf, static_cast<size_t>(n));
  15530. }
  15531. detail::close_socket(sock);
  15532. });
  15533. {
  15534. auto cli = Client("127.0.0.1", PORT + 1);
  15535. // "Z" sorts after the default headers, so writing straight to the socket
  15536. // would have sent the request line and those headers before the rejection.
  15537. auto handle =
  15538. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15539. EXPECT_FALSE(handle.is_valid());
  15540. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15541. }
  15542. server_thread.join();
  15543. detail::close_socket(srv);
  15544. EXPECT_TRUE(received.empty()) << received;
  15545. }
  15546. TEST(PathParamsTest, StaticMatch) {
  15547. const auto pattern = "/users/all";
  15548. detail::PathParamsMatcher matcher(pattern);
  15549. Request request;
  15550. request.path = "/users/all";
  15551. ASSERT_TRUE(matcher.match(request));
  15552. std::unordered_map<std::string, std::string> expected_params = {};
  15553. EXPECT_EQ(request.path_params, expected_params);
  15554. }
  15555. TEST(PathParamsTest, StaticMismatch) {
  15556. const auto pattern = "/users/all";
  15557. detail::PathParamsMatcher matcher(pattern);
  15558. Request request;
  15559. request.path = "/users/1";
  15560. ASSERT_FALSE(matcher.match(request));
  15561. }
  15562. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15563. const auto pattern = "/users/:id/subscriptions";
  15564. detail::PathParamsMatcher matcher(pattern);
  15565. Request request;
  15566. request.path = "/users/42/subscriptions";
  15567. ASSERT_TRUE(matcher.match(request));
  15568. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15569. EXPECT_EQ(request.path_params, expected_params);
  15570. }
  15571. TEST(PathParamsTest, SingleParamInTheEnd) {
  15572. const auto pattern = "/users/:id";
  15573. detail::PathParamsMatcher matcher(pattern);
  15574. Request request;
  15575. request.path = "/users/24";
  15576. ASSERT_TRUE(matcher.match(request));
  15577. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15578. EXPECT_EQ(request.path_params, expected_params);
  15579. }
  15580. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15581. const auto pattern = "/users/:id/";
  15582. detail::PathParamsMatcher matcher(pattern);
  15583. Request request;
  15584. request.path = "/users/42/";
  15585. ASSERT_TRUE(matcher.match(request));
  15586. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15587. EXPECT_EQ(request.path_params, expected_params);
  15588. }
  15589. TEST(PathParamsTest, EmptyParam) {
  15590. const auto pattern = "/users/:id/";
  15591. detail::PathParamsMatcher matcher(pattern);
  15592. Request request;
  15593. request.path = "/users//";
  15594. ASSERT_TRUE(matcher.match(request));
  15595. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15596. EXPECT_EQ(request.path_params, expected_params);
  15597. }
  15598. TEST(PathParamsTest, FragmentMismatch) {
  15599. const auto pattern = "/users/:id/";
  15600. detail::PathParamsMatcher matcher(pattern);
  15601. Request request;
  15602. request.path = "/admins/24/";
  15603. ASSERT_FALSE(matcher.match(request));
  15604. }
  15605. TEST(PathParamsTest, ExtraFragments) {
  15606. const auto pattern = "/users/:id";
  15607. detail::PathParamsMatcher matcher(pattern);
  15608. Request request;
  15609. request.path = "/users/42/subscriptions";
  15610. ASSERT_FALSE(matcher.match(request));
  15611. }
  15612. TEST(PathParamsTest, MissingTrailingParam) {
  15613. const auto pattern = "/users/:id";
  15614. detail::PathParamsMatcher matcher(pattern);
  15615. Request request;
  15616. request.path = "/users";
  15617. ASSERT_FALSE(matcher.match(request));
  15618. }
  15619. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15620. const auto pattern = "/users/:id/subscriptions";
  15621. detail::PathParamsMatcher matcher(pattern);
  15622. Request request;
  15623. request.path = "/users/subscriptions";
  15624. ASSERT_FALSE(matcher.match(request));
  15625. }
  15626. TEST(PathParamsTest, MultipleParams) {
  15627. const auto pattern = "/users/:userid/subscriptions/:subid";
  15628. detail::PathParamsMatcher matcher(pattern);
  15629. Request request;
  15630. request.path = "/users/42/subscriptions/2";
  15631. ASSERT_TRUE(matcher.match(request));
  15632. std::unordered_map<std::string, std::string> expected_params = {
  15633. {"userid", "42"}, {"subid", "2"}};
  15634. EXPECT_EQ(request.path_params, expected_params);
  15635. }
  15636. TEST(PathParamsTest, SequenceOfParams) {
  15637. const auto pattern = "/values/:x/:y/:z";
  15638. detail::PathParamsMatcher matcher(pattern);
  15639. Request request;
  15640. request.path = "/values/1/2/3";
  15641. ASSERT_TRUE(matcher.match(request));
  15642. std::unordered_map<std::string, std::string> expected_params = {
  15643. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15644. EXPECT_EQ(request.path_params, expected_params);
  15645. }
  15646. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15647. const auto pattern = "/prefix:suffix";
  15648. detail::PathParamsMatcher matcher(pattern);
  15649. Request request;
  15650. request.path = "/prefix:suffix";
  15651. ASSERT_TRUE(matcher.match(request));
  15652. const std::unordered_map<std::string, std::string> expected_params = {};
  15653. EXPECT_EQ(request.path_params, expected_params);
  15654. }
  15655. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15656. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15657. // calling thread's stack on a long enough path for a quantified pattern;
  15658. // RegexMatcher must refuse to run regex matching on paths beyond
  15659. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15660. detail::RegexMatcher matcher("/files/(.*)");
  15661. Request within_limit;
  15662. within_limit.path = "/files/" + std::string(10, 'A');
  15663. EXPECT_TRUE(matcher.match(within_limit));
  15664. Request over_limit;
  15665. over_limit.path =
  15666. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15667. EXPECT_FALSE(matcher.match(over_limit));
  15668. }
  15669. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15670. Server svr;
  15671. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15672. res.set_content("ok", "text/plain");
  15673. });
  15674. auto port = svr.bind_to_any_port(HOST);
  15675. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15676. auto se = detail::scope_exit([&] {
  15677. svr.stop();
  15678. thread.join();
  15679. ASSERT_FALSE(svr.is_running());
  15680. });
  15681. svr.wait_until_ready();
  15682. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15683. // request URI limit; this used to be able to crash the process.
  15684. std::string path =
  15685. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15686. std::string req = "GET " + path +
  15687. " HTTP/1.1\r\n"
  15688. "Host: " +
  15689. std::string(HOST) + ":" + std::to_string(port) +
  15690. "\r\n"
  15691. "Connection: close\r\n"
  15692. "\r\n";
  15693. std::string response;
  15694. ASSERT_TRUE(send_request(5, req, &response, port));
  15695. EXPECT_NE(std::string::npos, response.find("404"));
  15696. }
  15697. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15698. Server svr;
  15699. auto handler = [](const Request & /*req*/, Response &res) {
  15700. res.set_content("hit", "text/plain");
  15701. };
  15702. // No regex metacharacter, so this one is compared literally
  15703. svr.Get("/literal/route", handler);
  15704. // '.' is a regex metacharacter, so this one must keep regex semantics
  15705. svr.Get("/a.c", handler);
  15706. auto port = svr.bind_to_any_port(HOST);
  15707. std::thread t([&]() { svr.listen_after_bind(); });
  15708. auto se = detail::scope_exit([&] {
  15709. svr.stop();
  15710. t.join();
  15711. ASSERT_FALSE(svr.is_running());
  15712. });
  15713. svr.wait_until_ready();
  15714. Client cli(HOST, port);
  15715. struct {
  15716. const char *path;
  15717. int status;
  15718. } cases[] = {
  15719. {"/literal/route", StatusCode::OK_200},
  15720. {"/literal/routes", StatusCode::NotFound_404},
  15721. {"/literal/rout", StatusCode::NotFound_404},
  15722. {"/abc", StatusCode::OK_200},
  15723. {"/a.c", StatusCode::OK_200},
  15724. };
  15725. for (const auto &x : cases) {
  15726. auto res = cli.Get(x.path);
  15727. ASSERT_TRUE(res) << x.path;
  15728. EXPECT_EQ(x.status, res->status) << x.path;
  15729. }
  15730. }
  15731. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15732. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15733. // from exhausting the stack, so it must only constrain routes that actually
  15734. // run a regular expression. A literal route is matched by comparison and
  15735. // stays usable at any length.
  15736. Server svr;
  15737. const std::string pattern =
  15738. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15739. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15740. res.set_content("hit", "text/plain");
  15741. });
  15742. auto port = svr.bind_to_any_port(HOST);
  15743. std::thread t([&]() { svr.listen_after_bind(); });
  15744. auto se = detail::scope_exit([&] {
  15745. svr.stop();
  15746. t.join();
  15747. ASSERT_FALSE(svr.is_running());
  15748. });
  15749. svr.wait_until_ready();
  15750. Client cli(HOST, port);
  15751. auto res = cli.Get(pattern);
  15752. ASSERT_TRUE(res);
  15753. EXPECT_EQ(StatusCode::OK_200, res->status);
  15754. }
  15755. TEST(ParseUrlTest, VariousPatterns) {
  15756. {
  15757. detail::UrlComponents uc;
  15758. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15759. EXPECT_EQ("http", uc.scheme);
  15760. EXPECT_EQ("example.com", uc.host);
  15761. EXPECT_EQ("8080", uc.port);
  15762. EXPECT_EQ("/path", uc.path);
  15763. EXPECT_EQ("?q=1", uc.query);
  15764. }
  15765. {
  15766. detail::UrlComponents uc;
  15767. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15768. EXPECT_EQ("https", uc.scheme);
  15769. EXPECT_EQ("example.com", uc.host);
  15770. EXPECT_TRUE(uc.port.empty());
  15771. EXPECT_EQ("/path", uc.path);
  15772. }
  15773. {
  15774. detail::UrlComponents uc;
  15775. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15776. EXPECT_EQ("::1", uc.host);
  15777. EXPECT_EQ("8080", uc.port);
  15778. EXPECT_EQ("/path", uc.path);
  15779. }
  15780. {
  15781. detail::UrlComponents uc;
  15782. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15783. }
  15784. {
  15785. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15786. // the path while the connection still targets the bracketed host.
  15787. detail::UrlComponents uc;
  15788. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15789. }
  15790. {
  15791. detail::UrlComponents uc;
  15792. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15793. }
  15794. {
  15795. detail::UrlComponents uc;
  15796. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15797. EXPECT_EQ("::1", uc.host);
  15798. EXPECT_TRUE(uc.port.empty());
  15799. EXPECT_EQ("/path", uc.path);
  15800. }
  15801. {
  15802. detail::UrlComponents uc;
  15803. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15804. EXPECT_TRUE(uc.scheme.empty());
  15805. EXPECT_EQ("example.com", uc.host);
  15806. EXPECT_EQ("/path", uc.path);
  15807. EXPECT_EQ("?q=1", uc.query);
  15808. }
  15809. {
  15810. detail::UrlComponents uc;
  15811. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15812. EXPECT_TRUE(uc.host.empty());
  15813. EXPECT_EQ("/path", uc.path);
  15814. EXPECT_EQ("?q=1", uc.query);
  15815. }
  15816. {
  15817. detail::UrlComponents uc;
  15818. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15819. EXPECT_EQ("example.com", uc.host);
  15820. EXPECT_EQ("8080", uc.port);
  15821. }
  15822. {
  15823. // Unix socket path — must not be parsed as host
  15824. detail::UrlComponents uc;
  15825. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15826. EXPECT_TRUE(uc.host.empty());
  15827. }
  15828. {
  15829. detail::UrlComponents uc;
  15830. ASSERT_TRUE(detail::parse_url("", uc));
  15831. EXPECT_TRUE(uc.host.empty());
  15832. EXPECT_TRUE(uc.path.empty());
  15833. }
  15834. {
  15835. detail::UrlComponents uc;
  15836. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15837. }
  15838. {
  15839. detail::UrlComponents uc;
  15840. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15841. }
  15842. {
  15843. // Accepted by parse_url; callers restrict to http/https
  15844. detail::UrlComponents uc;
  15845. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15846. EXPECT_EQ("ftp", uc.scheme);
  15847. }
  15848. {
  15849. detail::UrlComponents uc;
  15850. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15851. }
  15852. {
  15853. detail::UrlComponents uc;
  15854. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15855. }
  15856. }
  15857. TEST(ParseUrlTest, FragmentHandling) {
  15858. {
  15859. detail::UrlComponents uc;
  15860. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15861. EXPECT_EQ("/path", uc.path);
  15862. EXPECT_TRUE(uc.query.empty());
  15863. }
  15864. {
  15865. detail::UrlComponents uc;
  15866. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15867. EXPECT_TRUE(uc.path.empty());
  15868. EXPECT_TRUE(uc.query.empty());
  15869. }
  15870. }
  15871. TEST(ParseUrlTest, UserinfoHandling) {
  15872. // Userinfo with @ but no colon — host includes @
  15873. detail::UrlComponents uc;
  15874. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15875. EXPECT_EQ("user@host.com", uc.host);
  15876. EXPECT_EQ("/path", uc.path);
  15877. }
  15878. TEST(ParseUrlTest, IPv6EdgeCases) {
  15879. {
  15880. detail::UrlComponents uc;
  15881. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15882. EXPECT_TRUE(uc.scheme.empty());
  15883. EXPECT_EQ("::1", uc.host);
  15884. EXPECT_EQ("8080", uc.port);
  15885. }
  15886. {
  15887. // Zone ID '%25' is not in [a-fA-F0-9:]
  15888. detail::UrlComponents uc;
  15889. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15890. }
  15891. }
  15892. TEST(ParseUrlTest, SchemeEdgeCases) {
  15893. {
  15894. detail::UrlComponents uc;
  15895. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15896. }
  15897. {
  15898. detail::UrlComponents uc;
  15899. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15900. }
  15901. {
  15902. detail::UrlComponents uc;
  15903. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15904. }
  15905. }
  15906. TEST(ParseUrlTest, PortEdgeCases) {
  15907. {
  15908. detail::UrlComponents uc;
  15909. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15910. EXPECT_TRUE(uc.port.empty());
  15911. EXPECT_EQ("/path", uc.path);
  15912. }
  15913. {
  15914. // parse_url accepts any port string; validation is done by parse_port
  15915. detail::UrlComponents uc;
  15916. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15917. EXPECT_EQ("abc", uc.port);
  15918. }
  15919. }
  15920. TEST(ParseUrlTest, WebSocketPatterns) {
  15921. {
  15922. detail::UrlComponents uc;
  15923. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15924. EXPECT_EQ("ws", uc.scheme);
  15925. EXPECT_EQ("echo.example.com", uc.host);
  15926. EXPECT_EQ("8080", uc.port);
  15927. EXPECT_EQ("/ws", uc.path);
  15928. }
  15929. {
  15930. detail::UrlComponents uc;
  15931. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15932. EXPECT_EQ("wss", uc.scheme);
  15933. EXPECT_EQ("echo.example.com", uc.host);
  15934. EXPECT_TRUE(uc.port.empty());
  15935. EXPECT_EQ("/ws", uc.path);
  15936. }
  15937. }
  15938. TEST(ParseUrlTest, QueryOnly) {
  15939. detail::UrlComponents uc;
  15940. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15941. EXPECT_TRUE(uc.host.empty());
  15942. EXPECT_TRUE(uc.path.empty());
  15943. EXPECT_EQ("?q=1&r=2", uc.query);
  15944. }
  15945. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15946. detail::UrlComponents uc;
  15947. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15948. EXPECT_TRUE(uc.scheme.empty());
  15949. EXPECT_EQ("example.com", uc.host);
  15950. EXPECT_EQ("443", uc.port);
  15951. EXPECT_EQ("/path", uc.path);
  15952. }
  15953. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15954. // If ipv6 regex working, regex match codepath is taken.
  15955. // else port will default to 80 in Client impl
  15956. int clientImplMagicPort = 80;
  15957. int port = 4321;
  15958. // above ports must be different to avoid false negative
  15959. EXPECT_NE(clientImplMagicPort, port);
  15960. std::string ipV6TestURL = "http://[ff06::c3]";
  15961. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15962. CLIENT_PRIVATE_KEY_FILE);
  15963. EXPECT_EQ(cli.port(), port);
  15964. }
  15965. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15966. auto file_path = "./www/dir/index.html";
  15967. auto dir_path = "./www/dir";
  15968. detail::FileStat stat_file(file_path);
  15969. EXPECT_TRUE(stat_file.is_file());
  15970. EXPECT_FALSE(stat_file.is_dir());
  15971. detail::FileStat stat_dir(dir_path);
  15972. EXPECT_FALSE(stat_dir.is_file());
  15973. EXPECT_TRUE(stat_dir.is_dir());
  15974. }
  15975. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15976. // IPv4 with default HTTP port (80)
  15977. EXPECT_EQ("example.com",
  15978. detail::make_host_and_port_string("example.com", 80, false));
  15979. // IPv4 with default HTTPS port (443)
  15980. EXPECT_EQ("example.com",
  15981. detail::make_host_and_port_string("example.com", 443, true));
  15982. // IPv4 with non-default HTTP port
  15983. EXPECT_EQ("example.com:8080",
  15984. detail::make_host_and_port_string("example.com", 8080, false));
  15985. // IPv4 with non-default HTTPS port
  15986. EXPECT_EQ("example.com:8443",
  15987. detail::make_host_and_port_string("example.com", 8443, true));
  15988. // IPv6 with default HTTP port (80)
  15989. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15990. // IPv6 with default HTTPS port (443)
  15991. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15992. // IPv6 with non-default HTTP port
  15993. EXPECT_EQ("[::1]:8080",
  15994. detail::make_host_and_port_string("::1", 8080, false));
  15995. // IPv6 with non-default HTTPS port
  15996. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15997. // IPv6 full address with default port
  15998. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15999. detail::make_host_and_port_string(
  16000. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16001. // IPv6 full address with non-default port
  16002. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16003. detail::make_host_and_port_string(
  16004. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16005. // IPv6 localhost with non-default port
  16006. EXPECT_EQ("[::1]:3000",
  16007. detail::make_host_and_port_string("::1", 3000, false));
  16008. // IPv6 with zone ID (link-local address) with default port
  16009. EXPECT_EQ("[fe80::1%eth0]",
  16010. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16011. // IPv6 with zone ID (link-local address) with non-default port
  16012. EXPECT_EQ("[fe80::1%eth0]:8080",
  16013. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16014. // Edge case: Port 443 with is_ssl=false (should add port)
  16015. EXPECT_EQ("example.com:443",
  16016. detail::make_host_and_port_string("example.com", 443, false));
  16017. // Edge case: Port 80 with is_ssl=true (should add port)
  16018. EXPECT_EQ("example.com:80",
  16019. detail::make_host_and_port_string("example.com", 80, true));
  16020. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16021. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16022. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16023. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16024. // Security fix: Already bracketed IPv6 should not get double brackets
  16025. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16026. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16027. EXPECT_EQ("[::1]:8080",
  16028. detail::make_host_and_port_string("[::1]", 8080, false));
  16029. EXPECT_EQ("[2001:db8::1]:8080",
  16030. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16031. EXPECT_EQ("[fe80::1%eth0]",
  16032. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16033. EXPECT_EQ("[fe80::1%eth0]:8080",
  16034. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16035. // Edge case: Empty host (should return as-is)
  16036. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16037. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16038. // This is a known limitation but shouldn't crash
  16039. EXPECT_EQ("[host:name]",
  16040. detail::make_host_and_port_string("host:name", 80, false));
  16041. // Port number edge cases (no validation, but should not crash)
  16042. EXPECT_EQ("example.com:0",
  16043. detail::make_host_and_port_string("example.com", 0, false));
  16044. EXPECT_EQ("example.com:-1",
  16045. detail::make_host_and_port_string("example.com", -1, false));
  16046. EXPECT_EQ("example.com:65535",
  16047. detail::make_host_and_port_string("example.com", 65535, false));
  16048. EXPECT_EQ("example.com:65536",
  16049. detail::make_host_and_port_string("example.com", 65536, false));
  16050. }
  16051. #ifdef CPPHTTPLIB_SSL_ENABLED
  16052. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16053. httplib::SSLClient cli("roblox.com", 443);
  16054. cli.set_follow_location(true);
  16055. auto res = cli.Get("/");
  16056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16057. EXPECT_EQ(StatusCode::OK_200, res->status);
  16058. }
  16059. #endif
  16060. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16061. Server svr;
  16062. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16063. EXPECT_EQ(res.status, 400);
  16064. });
  16065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16066. auto se = detail::scope_exit([&] {
  16067. svr.stop();
  16068. thread.join();
  16069. ASSERT_FALSE(svr.is_running());
  16070. });
  16071. svr.wait_until_ready();
  16072. Client cli(HOST, PORT);
  16073. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16074. }
  16075. TEST(InvalidHeaderCharsTest, is_field_name) {
  16076. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16077. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16078. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16079. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16080. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16081. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16082. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16083. EXPECT_FALSE(detail::fields::is_field_name(""));
  16084. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16085. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16086. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16087. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16088. }
  16089. TEST(InvalidHeaderCharsTest, is_field_value) {
  16090. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16091. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16092. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16093. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16094. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16095. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16096. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16097. EXPECT_TRUE(detail::fields::is_field_value(""));
  16098. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16099. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16100. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16101. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16102. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16103. }
  16104. TEST(InvalidHeaderCharsTest, OnServer) {
  16105. Server svr;
  16106. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16107. std::string header = "Not Set";
  16108. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16109. res.set_header(header, "value");
  16110. res.set_content("Page Content Page Content", "text/plain");
  16111. });
  16112. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16113. std::string header = "Not Set";
  16114. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16115. res.set_header("X-Test", header);
  16116. res.set_content("Page Content Page Content", "text/plain");
  16117. });
  16118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16119. auto se = detail::scope_exit([&] {
  16120. svr.stop();
  16121. thread.join();
  16122. ASSERT_FALSE(svr.is_running());
  16123. });
  16124. svr.wait_until_ready();
  16125. Client cli(HOST, PORT);
  16126. {
  16127. auto res = cli.Get(
  16128. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16130. EXPECT_EQ("Page Content Page Content", res->body);
  16131. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16132. }
  16133. {
  16134. auto res = cli.Get(
  16135. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16137. EXPECT_EQ("Page Content Page Content", res->body);
  16138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16139. }
  16140. }
  16141. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16142. auto handled = false;
  16143. Server svr;
  16144. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16145. thread t = thread([&] { svr.listen(HOST, PORT); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. t.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. ASSERT_FALSE(handled);
  16151. });
  16152. svr.wait_until_ready();
  16153. auto req = "POST /test HTTP/1.1\r\n"
  16154. "Content-Length: x\r\n"
  16155. "\r\n";
  16156. std::string response;
  16157. ASSERT_TRUE(send_request(1, req, &response));
  16158. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16159. response.substr(0, response.find("\r\n")));
  16160. }
  16161. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16162. // case-insensitive, and a server that receives a 100-continue expectation in
  16163. // an HTTP/1.0 request MUST ignore it.
  16164. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16165. std::string response;
  16166. ASSERT_TRUE(send_request(1, req, &response, port));
  16167. *got_100 = response.find("100 Continue") != std::string::npos;
  16168. }
  16169. class ExpectTokenTest : public ::testing::Test {
  16170. protected:
  16171. void SetUp() override {
  16172. svr_.Post("/p", [](const Request &, Response &res) {
  16173. res.set_content("ok", "text/plain");
  16174. });
  16175. port_ = svr_.bind_to_any_port(HOST);
  16176. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16177. svr_.wait_until_ready();
  16178. }
  16179. void TearDown() override {
  16180. svr_.stop();
  16181. if (thread_.joinable()) { thread_.join(); }
  16182. }
  16183. std::string request(const char *version, const char *expect_value) const {
  16184. return std::string("POST /p ") + version +
  16185. "\r\n"
  16186. "Host: localhost\r\n"
  16187. "Content-Length: 2\r\n"
  16188. "Connection: close\r\n"
  16189. "Expect: " +
  16190. expect_value +
  16191. "\r\n"
  16192. "\r\n"
  16193. "hi";
  16194. }
  16195. Server svr_;
  16196. int port_ = 0;
  16197. thread thread_;
  16198. };
  16199. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16200. bool got_100 = false;
  16201. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16202. EXPECT_TRUE(got_100);
  16203. }
  16204. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16205. bool got_100 = true;
  16206. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16207. EXPECT_FALSE(got_100);
  16208. }
  16209. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16210. bool got_100 = false;
  16211. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16212. EXPECT_TRUE(got_100);
  16213. }
  16214. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16215. bool got_100 = false;
  16216. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16217. EXPECT_TRUE(got_100);
  16218. }
  16219. // `100 Continue` is sent only when the server starts reading the body, so a
  16220. // request rejected before that never invites the client to send it. The
  16221. // requests below carry the expectation but withhold the body, as a client
  16222. // waiting for `100 Continue` would.
  16223. // A POST that expects `100 Continue` and withholds its two-byte body.
  16224. static std::string expect_headers_only(const std::string &path) {
  16225. return "POST " + path +
  16226. " HTTP/1.1\r\n"
  16227. "Host: localhost\r\n"
  16228. "Content-Length: 2\r\n"
  16229. "Expect: 100-continue\r\n"
  16230. "\r\n";
  16231. }
  16232. class ExpectLazyContinueTest : public ::testing::Test {
  16233. protected:
  16234. void SetUp() override {
  16235. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16236. if (req.path == "/pre-routing") {
  16237. res.status = StatusCode::Unauthorized_401;
  16238. return Server::HandlerResponse::Handled;
  16239. }
  16240. return Server::HandlerResponse::Unhandled;
  16241. });
  16242. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16243. if (req.matched_route == "/pre-request") {
  16244. res.status = StatusCode::Forbidden_403;
  16245. return Server::HandlerResponse::Handled;
  16246. }
  16247. return Server::HandlerResponse::Unhandled;
  16248. });
  16249. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16250. res.set_content("ok", "text/plain");
  16251. });
  16252. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16253. res.set_content("ok", "text/plain");
  16254. });
  16255. svr_.Post("/reader-used", [](const Request &, Response &res,
  16256. const ContentReader &content_reader) {
  16257. std::string body;
  16258. content_reader([&](const char *data, size_t len) {
  16259. body.append(data, len);
  16260. return true;
  16261. });
  16262. res.set_content(body, "text/plain");
  16263. });
  16264. svr_.Post("/reader-unused",
  16265. [](const Request &, Response &res, const ContentReader &) {
  16266. res.set_content("ignored", "text/plain");
  16267. });
  16268. port_ = svr_.bind_to_any_port(HOST);
  16269. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16270. svr_.wait_until_ready();
  16271. }
  16272. void TearDown() override {
  16273. svr_.stop();
  16274. if (thread_.joinable()) { thread_.join(); }
  16275. }
  16276. // Sends `req` and reads until the server closes the connection. Returns
  16277. // false if the read had to wait for the client-side timeout instead.
  16278. bool send_until_closed(const std::string &req, std::string *resp) const {
  16279. auto start = std::chrono::steady_clock::now();
  16280. if (!send_request(3, req, resp, port_)) { return false; }
  16281. auto elapsed = std::chrono::steady_clock::now() - start;
  16282. return elapsed < std::chrono::seconds(2);
  16283. }
  16284. // The final response comes without `100 Continue`, and the server closes
  16285. // the connection since the body may or may not follow.
  16286. void expect_final_without_interim(const std::string &path,
  16287. const char *status_line) const {
  16288. std::string resp;
  16289. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16290. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16291. EXPECT_EQ(0u, resp.find(status_line));
  16292. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16293. }
  16294. Server svr_;
  16295. int port_ = 0;
  16296. thread thread_;
  16297. };
  16298. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16299. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16300. }
  16301. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16302. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16303. }
  16304. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16305. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16306. }
  16307. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16308. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16309. }
  16310. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16311. // The body follows once `100 Continue` has had time to arrive.
  16312. auto req = expect_headers_only("/reader-used");
  16313. req.insert(req.size() - 2, "Connection: close\r\n");
  16314. std::string resp;
  16315. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16316. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16317. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16318. EXPECT_NE(std::string::npos, resp.find("hi"));
  16319. }
  16320. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16321. // Large enough for the client to add `Expect: 100-continue` itself.
  16322. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16323. std::atomic<bool> body_sent{false};
  16324. Client cli(HOST, port_);
  16325. auto res = cli.Post(
  16326. "/pre-request", length,
  16327. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16328. body_sent = true;
  16329. std::string chunk(len, 'x');
  16330. sink.write(chunk.data(), chunk.size());
  16331. return true;
  16332. },
  16333. "application/octet-stream");
  16334. ASSERT_TRUE(res);
  16335. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16336. EXPECT_FALSE(body_sent);
  16337. }
  16338. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16339. Server svr;
  16340. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16341. return StatusCode::ExpectationFailed_417;
  16342. });
  16343. svr.Post("/p", [](const Request &, Response &res) {
  16344. res.set_content("ok", "text/plain");
  16345. });
  16346. auto port = svr.bind_to_any_port(HOST);
  16347. thread t = thread([&] { svr.listen_after_bind(); });
  16348. auto se = detail::scope_exit([&] {
  16349. svr.stop();
  16350. t.join();
  16351. });
  16352. svr.wait_until_ready();
  16353. std::string resp;
  16354. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16355. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16356. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16357. // Exactly one response: the route handler must not run after the 417.
  16358. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16359. }
  16360. #ifndef _WIN32
  16361. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16362. static constexpr char reject[] = "Unauthorized";
  16363. static constexpr char accept[] = "Upload accepted";
  16364. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16365. Server svr;
  16366. svr.set_expect_100_continue_handler(
  16367. [](const Request & /*req*/, Response &res) {
  16368. res.status = StatusCode::Unauthorized_401;
  16369. res.set_content(reject, "text/plain");
  16370. return res.status;
  16371. });
  16372. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16373. res.set_content(accept, "text/plain");
  16374. });
  16375. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16376. auto se = detail::scope_exit([&] {
  16377. svr.stop();
  16378. thread.join();
  16379. ASSERT_FALSE(svr.is_running());
  16380. });
  16381. svr.wait_until_ready();
  16382. {
  16383. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16384. curl_easy_init(), &curl_easy_cleanup};
  16385. ASSERT_NE(curl, nullptr);
  16386. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16387. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16388. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16389. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16390. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16391. &curl_slist_free_all};
  16392. ASSERT_NE(list, nullptr);
  16393. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16394. struct read_data {
  16395. size_t read_size;
  16396. size_t total_size;
  16397. } data = {0, total_size};
  16398. using read_callback_t =
  16399. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16400. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16401. void *userdata) -> size_t {
  16402. read_data *d = (read_data *)userdata;
  16403. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16404. std::fill_n(ptr, size * nmemb, 'A');
  16405. d->read_size += size * nmemb;
  16406. return size * nmemb;
  16407. };
  16408. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16409. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16410. std::vector<char> buffer;
  16411. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16412. using write_callback_t =
  16413. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16414. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16415. void *userdata) -> size_t {
  16416. std::vector<char> *buf = (std::vector<char> *)userdata;
  16417. buf->reserve(buf->size() + size * nmemb + 1);
  16418. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16419. return size * nmemb;
  16420. };
  16421. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16422. {
  16423. const auto res = curl_easy_perform(curl.get());
  16424. ASSERT_EQ(res, CURLE_OK);
  16425. }
  16426. {
  16427. auto response_code = long{};
  16428. const auto res =
  16429. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16430. ASSERT_EQ(res, CURLE_OK);
  16431. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16432. }
  16433. {
  16434. auto dl = curl_off_t{};
  16435. const auto res =
  16436. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16437. ASSERT_EQ(res, CURLE_OK);
  16438. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16439. }
  16440. {
  16441. buffer.push_back('\0');
  16442. ASSERT_STRCASEEQ(buffer.data(), reject);
  16443. }
  16444. }
  16445. }
  16446. #endif
  16447. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16448. // Regression test for #2458.
  16449. //
  16450. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16451. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16452. // ticket can make the client socket spuriously readable during the
  16453. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16454. // the client withholds the body and then blocks reading a response that never
  16455. // comes, failing with `Failed to read connection`.
  16456. //
  16457. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16458. // within the timeout. This raw OpenSSL server deliberately never sends
  16459. // `100 Continue`; the client must still deliver the body and receive 200.
  16460. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16461. signal(SIGPIPE, SIG_IGN);
  16462. const auto port = PORT + 4;
  16463. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16464. ASSERT_NE(srv, INVALID_SOCKET);
  16465. int opt = 1;
  16466. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16467. sockaddr_in addr{};
  16468. addr.sin_family = AF_INET;
  16469. addr.sin_port = htons(static_cast<uint16_t>(port));
  16470. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16471. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16472. ASSERT_EQ(0, ::listen(srv, 1));
  16473. std::atomic<size_t> server_body_bytes{0};
  16474. auto server_thread = std::thread([&] {
  16475. sockaddr_in cli_addr{};
  16476. socklen_t cli_len = sizeof(cli_addr);
  16477. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16478. if (cli == INVALID_SOCKET) { return; }
  16479. // Bound the lifetime of the server side so a buggy client (which never
  16480. // sends the body) cannot make this thread block forever on join.
  16481. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16482. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16483. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16484. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16485. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16486. SSL *ssl = SSL_new(ctx);
  16487. SSL_set_fd(ssl, static_cast<int>(cli));
  16488. if (SSL_accept(ssl) > 0) {
  16489. // Read the request headers. Reading here also flushes the TLS 1.3
  16490. // session tickets to the client. Deliberately do NOT send
  16491. // `100 Continue`.
  16492. std::string buf;
  16493. char tmp[1024];
  16494. while (buf.find("\r\n\r\n") == std::string::npos) {
  16495. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16496. if (n <= 0) { break; }
  16497. buf.append(tmp, static_cast<size_t>(n));
  16498. }
  16499. // A correct client sends the body now; count what arrives.
  16500. auto pos = buf.find("\r\n\r\n");
  16501. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16502. while (body < 4096) {
  16503. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16504. if (n <= 0) { break; }
  16505. body += static_cast<size_t>(n);
  16506. }
  16507. server_body_bytes = body;
  16508. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16509. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16510. SSL_shutdown(ssl);
  16511. }
  16512. SSL_free(ssl);
  16513. detail::close_socket(cli);
  16514. SSL_CTX_free(ctx);
  16515. });
  16516. auto se = detail::scope_exit([&] {
  16517. server_thread.join();
  16518. detail::close_socket(srv);
  16519. });
  16520. SSLClient cli("127.0.0.1", port);
  16521. cli.enable_server_certificate_verification(false);
  16522. cli.set_connection_timeout(5, 0);
  16523. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16524. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16525. std::string body(4096, 'A');
  16526. auto res = cli.Put("/api/test", body, "application/json");
  16527. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16528. EXPECT_EQ(StatusCode::OK_200, res->status);
  16529. EXPECT_EQ(body.size(), server_body_bytes.load());
  16530. }
  16531. #endif
  16532. template <typename S, typename C>
  16533. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16534. svr.Get("/stream", [&](const Request &, Response &res) {
  16535. auto data = new std::string("01234567890123456789");
  16536. res.set_content_provider(
  16537. data->size(), "text/plain",
  16538. [&, data](size_t offset, size_t length, DataSink &sink) {
  16539. const size_t DATA_CHUNK_SIZE = 4;
  16540. const auto &d = *data;
  16541. std::this_thread::sleep_for(std::chrono::seconds(1));
  16542. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16543. return true;
  16544. },
  16545. [data](bool success) {
  16546. EXPECT_FALSE(success);
  16547. delete data;
  16548. });
  16549. });
  16550. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16551. auto i = new size_t(0);
  16552. res.set_content_provider(
  16553. "text/plain",
  16554. [i](size_t, DataSink &sink) {
  16555. if (*i < 5) {
  16556. std::this_thread::sleep_for(std::chrono::seconds(1));
  16557. sink.write("abcd", 4);
  16558. (*i)++;
  16559. } else {
  16560. sink.done();
  16561. }
  16562. return true;
  16563. },
  16564. [i](bool success) {
  16565. EXPECT_FALSE(success);
  16566. delete i;
  16567. });
  16568. });
  16569. svr.Get("/chunked", [&](const Request &, Response &res) {
  16570. auto i = new size_t(0);
  16571. res.set_chunked_content_provider(
  16572. "text/plain",
  16573. [i](size_t, DataSink &sink) {
  16574. if (*i < 5) {
  16575. std::this_thread::sleep_for(std::chrono::seconds(1));
  16576. sink.os << "abcd";
  16577. (*i)++;
  16578. } else {
  16579. sink.done();
  16580. }
  16581. return true;
  16582. },
  16583. [i](bool success) {
  16584. EXPECT_FALSE(success);
  16585. delete i;
  16586. });
  16587. });
  16588. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16589. auto se = detail::scope_exit([&] {
  16590. svr.stop();
  16591. listen_thread.join();
  16592. ASSERT_FALSE(svr.is_running());
  16593. });
  16594. svr.wait_until_ready();
  16595. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16596. {
  16597. auto start = std::chrono::steady_clock::now();
  16598. auto res = cli.Get("/stream");
  16599. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16600. std::chrono::steady_clock::now() - start)
  16601. .count();
  16602. ASSERT_FALSE(res);
  16603. EXPECT_EQ(Error::Read, res.error());
  16604. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16605. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16606. }
  16607. {
  16608. auto start = std::chrono::steady_clock::now();
  16609. auto res = cli.Get("/stream_without_length");
  16610. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16611. std::chrono::steady_clock::now() - start)
  16612. .count();
  16613. ASSERT_FALSE(res);
  16614. EXPECT_EQ(Error::Read, res.error());
  16615. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16616. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16617. }
  16618. {
  16619. auto start = std::chrono::steady_clock::now();
  16620. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16621. EXPECT_EQ("abcd", string(data, data_length));
  16622. return true;
  16623. });
  16624. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16625. std::chrono::steady_clock::now() - start)
  16626. .count();
  16627. ASSERT_FALSE(res);
  16628. EXPECT_EQ(Error::Read, res.error());
  16629. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16630. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16631. }
  16632. }
  16633. TEST(MaxTimeoutTest, ContentStream) {
  16634. time_t timeout = 2000;
  16635. time_t threshold = 200;
  16636. Server svr;
  16637. Client cli("localhost", PORT);
  16638. max_timeout_test(svr, cli, timeout, threshold);
  16639. }
  16640. #ifdef CPPHTTPLIB_SSL_ENABLED
  16641. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16642. time_t timeout = 2000;
  16643. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16644. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16645. SSLClient cli("localhost", PORT);
  16646. cli.enable_server_certificate_verification(false);
  16647. max_timeout_test(svr, cli, timeout, threshold);
  16648. }
  16649. #endif
  16650. class EventDispatcher {
  16651. public:
  16652. EventDispatcher() {}
  16653. bool wait_event(DataSink *sink) {
  16654. unique_lock<mutex> lk(m_);
  16655. int id = id_;
  16656. // Wait with timeout to prevent hanging if client disconnects
  16657. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16658. [&] { return cid_ == id; })) {
  16659. return false; // Timeout occurred
  16660. }
  16661. sink->write(message_.data(), message_.size());
  16662. return true;
  16663. }
  16664. void send_event(const string &message) {
  16665. lock_guard<mutex> lk(m_);
  16666. cid_ = id_++;
  16667. message_ = message;
  16668. cv_.notify_all();
  16669. }
  16670. private:
  16671. mutex m_;
  16672. condition_variable cv_;
  16673. atomic_int id_{0};
  16674. atomic_int cid_{-1};
  16675. string message_;
  16676. };
  16677. TEST(ClientInThreadTest, Issue2068) {
  16678. EventDispatcher ed;
  16679. Server svr;
  16680. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16681. res.set_chunked_content_provider("text/event-stream",
  16682. [&](size_t /*offset*/, DataSink &sink) {
  16683. return ed.wait_event(&sink);
  16684. });
  16685. });
  16686. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16687. svr.wait_until_ready();
  16688. thread event_thread([&] {
  16689. int id = 0;
  16690. while (svr.is_running()) {
  16691. this_thread::sleep_for(chrono::milliseconds(500));
  16692. std::stringstream ss;
  16693. ss << "data: " << id << "\n\n";
  16694. ed.send_event(ss.str());
  16695. id++;
  16696. }
  16697. });
  16698. auto se = detail::scope_exit([&] {
  16699. svr.stop();
  16700. listen_thread.join();
  16701. event_thread.join();
  16702. ASSERT_FALSE(svr.is_running());
  16703. });
  16704. {
  16705. auto client = detail::make_unique<Client>(HOST, PORT);
  16706. client->set_read_timeout(std::chrono::minutes(10));
  16707. std::atomic<bool> stop{false};
  16708. std::thread t([&] {
  16709. client->Get("/event1",
  16710. [&](const char *, size_t) -> bool { return !stop; });
  16711. });
  16712. std::this_thread::sleep_for(std::chrono::seconds(2));
  16713. stop = true;
  16714. client->stop();
  16715. t.join();
  16716. // Reset client after thread has finished
  16717. client.reset();
  16718. }
  16719. }
  16720. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16721. auto handled = false;
  16722. Server svr;
  16723. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16724. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16725. auto se = detail::scope_exit([&] {
  16726. svr.stop();
  16727. t.join();
  16728. ASSERT_FALSE(svr.is_running());
  16729. ASSERT_FALSE(handled);
  16730. });
  16731. svr.wait_until_ready();
  16732. // Two Content-Length headers with different values — must be rejected
  16733. auto req = "POST /test HTTP/1.1\r\n"
  16734. "Content-Length: 5\r\n"
  16735. "Content-Length: 10\r\n"
  16736. "\r\n"
  16737. "hello";
  16738. std::string response;
  16739. ASSERT_TRUE(send_request(1, req, &response));
  16740. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16741. response.substr(0, response.find("\r\n")));
  16742. }
  16743. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16744. auto handled = false;
  16745. Server svr;
  16746. svr.Post("/test", [&](const Request &, Response &res) {
  16747. handled = true;
  16748. res.set_content("ok", "text/plain");
  16749. });
  16750. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16751. auto se = detail::scope_exit([&] {
  16752. svr.stop();
  16753. t.join();
  16754. ASSERT_FALSE(svr.is_running());
  16755. ASSERT_TRUE(handled);
  16756. });
  16757. svr.wait_until_ready();
  16758. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16759. auto req = "POST /test HTTP/1.1\r\n"
  16760. "Content-Length: 5\r\n"
  16761. "Content-Length: 5\r\n"
  16762. "\r\n"
  16763. "hello";
  16764. std::string response;
  16765. ASSERT_TRUE(send_request(1, req, &response));
  16766. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16767. }
  16768. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16769. Server svr;
  16770. svr.Get("/test", [](const Request &, Response &res) {
  16771. res.set_content("ok", "text/plain");
  16772. });
  16773. auto port = svr.bind_to_any_port(HOST);
  16774. thread t = thread([&] { svr.listen_after_bind(); });
  16775. auto se = detail::scope_exit([&] {
  16776. svr.stop();
  16777. t.join();
  16778. ASSERT_FALSE(svr.is_running());
  16779. });
  16780. svr.wait_until_ready();
  16781. auto status_line = [&](const std::string &host_lines) {
  16782. std::string res;
  16783. send_request(
  16784. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16785. &res, port);
  16786. return res.substr(0, res.find("\r\n"));
  16787. };
  16788. const char *accepted[] = {
  16789. "Host: localhost\r\n",
  16790. "Host: a.example:8080\r\n",
  16791. "Host: my_service\r\n",
  16792. "Host: [::1]:8080\r\n",
  16793. "Host: [fe80::1%25eth0]\r\n",
  16794. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16795. };
  16796. for (auto host_lines : accepted) {
  16797. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16798. }
  16799. const char *rejected[] = {
  16800. "Host: a.example\r\nHost: b.example\r\n",
  16801. "Host: a.example\r\nHost: a.example\r\n",
  16802. "Host: a@b.example\r\n",
  16803. "Host: a.example/b\r\n",
  16804. "Host: a.example\\b\r\n",
  16805. "Host: a.example?b\r\n",
  16806. "Host: a.example#b\r\n",
  16807. "Host: a.example b.example\r\n",
  16808. };
  16809. for (auto host_lines : rejected) {
  16810. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16811. << host_lines;
  16812. }
  16813. }
  16814. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16815. Server svr;
  16816. svr.Get("/", [](const Request &req, Response &res) {
  16817. EXPECT_EQ(2U, req.trailers.size());
  16818. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16819. // Denied
  16820. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16821. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16822. // Accepted
  16823. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16824. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16825. EXPECT_TRUE(req.has_trailer("X-World"));
  16826. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16827. res.set_content("ok", "text/plain");
  16828. });
  16829. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16830. auto se = detail::scope_exit([&] {
  16831. svr.stop();
  16832. t.join();
  16833. ASSERT_FALSE(svr.is_running());
  16834. });
  16835. svr.wait_until_ready();
  16836. const std::string req = "GET / HTTP/1.1\r\n"
  16837. "Transfer-Encoding: chunked\r\n"
  16838. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16839. "\r\n"
  16840. "0\r\n"
  16841. "Content-Length: 10\r\n"
  16842. "Host: internal.local\r\n"
  16843. "Content-Type: malicious/content\r\n"
  16844. "Cookie: any\r\n"
  16845. "Set-Cookie: any\r\n"
  16846. "X-Forwarded-For: attacker.com\r\n"
  16847. "X-Real-Ip: 1.1.1.1\r\n"
  16848. "X-Hello: hello\r\n"
  16849. "X-World: world\r\n"
  16850. "\r\n";
  16851. std::string res;
  16852. ASSERT_TRUE(send_request(1, req, &res));
  16853. }
  16854. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16855. // several field lines, and the combined value is what has to be parsed. A
  16856. // Trailer field split across lines therefore declares every name it lists;
  16857. // reading only the first line silently drops the trailers the later lines
  16858. // declare. The prohibited-trailer filter still applies to every line.
  16859. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16860. Server svr;
  16861. size_t observed_trailer_count = 0;
  16862. std::string observed_hello;
  16863. std::string observed_world;
  16864. bool observed_content_length = true;
  16865. svr.Get("/", [&](const Request &req, Response &res) {
  16866. observed_trailer_count = req.trailers.size();
  16867. observed_hello = req.get_trailer_value("X-Hello");
  16868. observed_world = req.get_trailer_value("X-World");
  16869. observed_content_length = req.has_trailer("Content-Length");
  16870. res.set_content("ok", "text/plain");
  16871. });
  16872. auto port = svr.bind_to_any_port(HOST);
  16873. thread t = thread([&]() { svr.listen_after_bind(); });
  16874. auto se = detail::scope_exit([&] {
  16875. svr.stop();
  16876. t.join();
  16877. ASSERT_FALSE(svr.is_running());
  16878. });
  16879. svr.wait_until_ready();
  16880. const std::string req = "GET / HTTP/1.1\r\n"
  16881. "Transfer-Encoding: chunked\r\n"
  16882. "Trailer: X-Hello\r\n"
  16883. "Trailer: X-World, Content-Length\r\n"
  16884. "\r\n"
  16885. "0\r\n"
  16886. "X-Hello: hello\r\n"
  16887. "X-World: world\r\n"
  16888. "Content-Length: 10\r\n"
  16889. "\r\n";
  16890. std::string res;
  16891. ASSERT_TRUE(send_request(1, req, &res, port));
  16892. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16893. // Accepted: both field lines contribute to the declared set
  16894. EXPECT_EQ(2U, observed_trailer_count);
  16895. EXPECT_EQ(observed_hello, "hello");
  16896. EXPECT_EQ(observed_world, "world");
  16897. // Denied: a prohibited name stays prohibited on a later field line
  16898. EXPECT_FALSE(observed_content_length);
  16899. }
  16900. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16901. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16902. // unbounded run of fields that are never declared, because the counter would
  16903. // only advance for declared fields.
  16904. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16905. Server svr;
  16906. bool handler_called = false;
  16907. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16908. handler_called = true;
  16909. res.set_content("ok", "text/plain");
  16910. });
  16911. auto port = svr.bind_to_any_port(HOST);
  16912. thread t = thread([&]() { svr.listen_after_bind(); });
  16913. auto se = detail::scope_exit([&] {
  16914. svr.stop();
  16915. t.join();
  16916. ASSERT_FALSE(svr.is_running());
  16917. });
  16918. svr.wait_until_ready();
  16919. // Declare nothing, then send far more undeclared trailer fields than the
  16920. // header-count limit. Parsing must stop and reject the request rather than
  16921. // read every line.
  16922. std::string req = "GET / HTTP/1.1\r\n"
  16923. "Transfer-Encoding: chunked\r\n"
  16924. "\r\n"
  16925. "0\r\n";
  16926. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16927. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16928. }
  16929. req += "\r\n";
  16930. std::string res;
  16931. ASSERT_TRUE(send_request(1, req, &res, port));
  16932. // The request is rejected before the handler runs.
  16933. EXPECT_FALSE(handler_called);
  16934. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16935. }
  16936. // The set of declared trailer names is capped so a peer cannot grow it without
  16937. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16938. // declared past the cap is not honored, even if the field is actually sent.
  16939. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16940. Server svr;
  16941. // One name inside the cap and one past it, so the test tracks the cap rather
  16942. // than a fixed count.
  16943. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16944. const std::string within_cap_name = "X-T-0";
  16945. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16946. bool observed_within_cap = false;
  16947. bool observed_past_cap = false;
  16948. svr.Get("/", [&](const Request &req, Response &res) {
  16949. observed_within_cap = req.has_trailer(within_cap_name);
  16950. observed_past_cap = req.has_trailer(past_cap_name);
  16951. res.set_content("ok", "text/plain");
  16952. });
  16953. auto port = svr.bind_to_any_port(HOST);
  16954. thread t = thread([&]() { svr.listen_after_bind(); });
  16955. auto se = detail::scope_exit([&] {
  16956. svr.stop();
  16957. t.join();
  16958. ASSERT_FALSE(svr.is_running());
  16959. });
  16960. svr.wait_until_ready();
  16961. // Declare more trailer names than the cap in a single Trailer field, then
  16962. // actually send the first (within the cap) and the last (past it).
  16963. std::string trailer_decl = "Trailer: ";
  16964. for (int i = 0; i < declared_count; i++) {
  16965. if (i != 0) { trailer_decl += ", "; }
  16966. trailer_decl += "X-T-" + std::to_string(i);
  16967. }
  16968. trailer_decl += "\r\n";
  16969. const std::string req = "GET / HTTP/1.1\r\n"
  16970. "Transfer-Encoding: chunked\r\n" +
  16971. trailer_decl +
  16972. "\r\n"
  16973. "0\r\n" +
  16974. within_cap_name + ": a\r\n" + past_cap_name +
  16975. ": b\r\n"
  16976. "\r\n";
  16977. std::string res;
  16978. ASSERT_TRUE(send_request(1, req, &res, port));
  16979. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16980. // A name within the cap is honored; one declared past the cap is dropped.
  16981. EXPECT_TRUE(observed_within_cap);
  16982. EXPECT_FALSE(observed_past_cap);
  16983. }
  16984. // A direct client that is not listed in trusted_proxies must not be able to
  16985. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16986. // the peer address on the actual TCP connection determines whether the
  16987. // header is honored.
  16988. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16989. Server svr;
  16990. // Deliberately does NOT include the loopback address the test client
  16991. // actually connects from, so the direct connection is not a trusted proxy.
  16992. svr.set_trusted_proxies({"203.0.113.66"});
  16993. std::string observed_remote_addr;
  16994. svr.Get("/ip", [&](const Request &req, Response &res) {
  16995. observed_remote_addr = req.remote_addr;
  16996. res.set_content("ok", "text/plain");
  16997. });
  16998. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16999. auto se = detail::scope_exit([&] {
  17000. svr.stop();
  17001. t.join();
  17002. ASSERT_FALSE(svr.is_running());
  17003. });
  17004. svr.wait_until_ready();
  17005. Client cli(HOST, PORT);
  17006. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17008. EXPECT_EQ(StatusCode::OK_200, res->status);
  17009. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17010. // ignored entirely and the real connection-level address retained.
  17011. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17012. observed_remote_addr == "127.0.0.1");
  17013. }
  17014. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17015. Server svr;
  17016. std::string observed_remote_addr;
  17017. std::string observed_xff;
  17018. svr.Get("/ip", [&](const Request &req, Response &res) {
  17019. observed_remote_addr = req.remote_addr;
  17020. observed_xff = req.get_header_value("X-Forwarded-For");
  17021. res.set_content("ok", "text/plain");
  17022. });
  17023. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17024. auto se = detail::scope_exit([&] {
  17025. svr.stop();
  17026. t.join();
  17027. ASSERT_FALSE(svr.is_running());
  17028. });
  17029. svr.wait_until_ready();
  17030. Client cli(HOST, PORT);
  17031. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17033. EXPECT_EQ(StatusCode::OK_200, res->status);
  17034. EXPECT_EQ(observed_xff, "203.0.113.66");
  17035. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17036. observed_remote_addr == "127.0.0.1");
  17037. }
  17038. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17039. Server svr;
  17040. svr.set_trusted_proxies({"203.0.113.66"});
  17041. std::string observed_remote_addr;
  17042. std::string observed_xff;
  17043. svr.Get("/ip", [&](const Request &req, Response &res) {
  17044. observed_remote_addr = req.remote_addr;
  17045. observed_xff = req.get_header_value("X-Forwarded-For");
  17046. res.set_content("ok", "text/plain");
  17047. });
  17048. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17049. auto se = detail::scope_exit([&] {
  17050. svr.stop();
  17051. t.join();
  17052. ASSERT_FALSE(svr.is_running());
  17053. });
  17054. svr.wait_until_ready();
  17055. Client cli(HOST, PORT);
  17056. auto res = cli.Get("/ip");
  17057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17058. EXPECT_EQ(StatusCode::OK_200, res->status);
  17059. EXPECT_EQ(observed_xff, "");
  17060. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17061. observed_remote_addr == "127.0.0.1");
  17062. }
  17063. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17064. Server svr;
  17065. // Include the loopback address the test client actually connects from, so
  17066. // the direct connection itself is recognized as the trusted proxy hop.
  17067. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17068. std::string observed_remote_addr;
  17069. std::string observed_xff;
  17070. svr.Get("/ip", [&](const Request &req, Response &res) {
  17071. observed_remote_addr = req.remote_addr;
  17072. observed_xff = req.get_header_value("X-Forwarded-For");
  17073. res.set_content("ok", "text/plain");
  17074. });
  17075. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17076. auto se = detail::scope_exit([&] {
  17077. svr.stop();
  17078. t.join();
  17079. ASSERT_FALSE(svr.is_running());
  17080. });
  17081. svr.wait_until_ready();
  17082. Client cli(HOST, PORT);
  17083. auto res = cli.Get(
  17084. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17086. EXPECT_EQ(StatusCode::OK_200, res->status);
  17087. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17088. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17089. }
  17090. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17091. Server svr;
  17092. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17093. std::string observed_remote_addr;
  17094. std::string observed_xff;
  17095. svr.Get("/ip", [&](const Request &req, Response &res) {
  17096. observed_remote_addr = req.remote_addr;
  17097. observed_xff = req.get_header_value("X-Forwarded-For");
  17098. res.set_content("ok", "text/plain");
  17099. });
  17100. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17101. auto se = detail::scope_exit([&] {
  17102. svr.stop();
  17103. t.join();
  17104. ASSERT_FALSE(svr.is_running());
  17105. });
  17106. svr.wait_until_ready();
  17107. Client cli(HOST, PORT);
  17108. auto res = cli.Get(
  17109. "/ip",
  17110. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17112. EXPECT_EQ(StatusCode::OK_200, res->status);
  17113. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17114. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17115. }
  17116. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17117. Server svr;
  17118. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17119. std::string observed_remote_addr;
  17120. std::string observed_xff;
  17121. svr.Get("/ip", [&](const Request &req, Response &res) {
  17122. observed_remote_addr = req.remote_addr;
  17123. observed_xff = req.get_header_value("X-Forwarded-For");
  17124. res.set_content("ok", "text/plain");
  17125. });
  17126. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17127. auto se = detail::scope_exit([&] {
  17128. svr.stop();
  17129. t.join();
  17130. ASSERT_FALSE(svr.is_running());
  17131. });
  17132. svr.wait_until_ready();
  17133. Client cli(HOST, PORT);
  17134. auto res = cli.Get(
  17135. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17137. EXPECT_EQ(StatusCode::OK_200, res->status);
  17138. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17139. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17140. // and must not be selected.
  17141. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17142. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17143. }
  17144. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17145. Server svr;
  17146. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17147. std::string observed_remote_addr;
  17148. svr.Get("/ip", [&](const Request &req, Response &res) {
  17149. observed_remote_addr = req.remote_addr;
  17150. res.set_content("ok", "text/plain");
  17151. });
  17152. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17153. auto se = detail::scope_exit([&] {
  17154. svr.stop();
  17155. t.join();
  17156. ASSERT_FALSE(svr.is_running());
  17157. });
  17158. svr.wait_until_ready();
  17159. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17160. // a forged address and the trusted proxy's own address; the forged value must
  17161. // not win over the address the trusted proxy actually recorded.
  17162. Client cli(HOST, PORT);
  17163. auto res = cli.Get(
  17164. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17166. EXPECT_EQ(StatusCode::OK_200, res->status);
  17167. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17168. }
  17169. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17170. Server svr;
  17171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17172. std::string observed_remote_addr;
  17173. std::string observed_xff;
  17174. svr.Get("/ip", [&](const Request &req, Response &res) {
  17175. observed_remote_addr = req.remote_addr;
  17176. observed_xff = req.get_header_value("X-Forwarded-For");
  17177. res.set_content("ok", "text/plain");
  17178. });
  17179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17180. auto se = detail::scope_exit([&] {
  17181. svr.stop();
  17182. t.join();
  17183. ASSERT_FALSE(svr.is_running());
  17184. });
  17185. svr.wait_until_ready();
  17186. Client cli(HOST, PORT);
  17187. auto res = cli.Get(
  17188. "/ip",
  17189. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17191. EXPECT_EQ(StatusCode::OK_200, res->status);
  17192. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17193. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17194. }
  17195. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17196. Server svr;
  17197. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17198. std::string observed_remote_addr;
  17199. std::string observed_xff;
  17200. svr.Get("/ip", [&](const Request &req, Response &res) {
  17201. observed_remote_addr = req.remote_addr;
  17202. observed_xff = req.get_header_value("X-Forwarded-For");
  17203. res.set_content("ok", "text/plain");
  17204. });
  17205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17206. auto se = detail::scope_exit([&] {
  17207. svr.stop();
  17208. t.join();
  17209. ASSERT_FALSE(svr.is_running());
  17210. });
  17211. svr.wait_until_ready();
  17212. std::string raw_req =
  17213. "GET /ip HTTP/1.1\r\n"
  17214. "Host: localhost\r\n"
  17215. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17216. "Connection: close\r\n"
  17217. "\r\n";
  17218. std::string out;
  17219. ASSERT_TRUE(send_request(5, raw_req, &out));
  17220. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17221. // Header parser trims surrounding whitespace of the header value
  17222. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17223. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17224. }
  17225. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17226. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17227. // their own X-Forwarded-For as a separate field line rather than extending the
  17228. // one the client sent, so every occurrence has to be taken into account.
  17229. // Reading only the first one hands back the address the client chose.
  17230. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17231. Server svr;
  17232. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17233. std::string observed_remote_addr;
  17234. size_t observed_xff_count = 0;
  17235. svr.Get("/ip", [&](const Request &req, Response &res) {
  17236. observed_remote_addr = req.remote_addr;
  17237. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17238. res.set_content("ok", "text/plain");
  17239. });
  17240. auto port = svr.bind_to_any_port(HOST);
  17241. thread t = thread([&]() { svr.listen_after_bind(); });
  17242. auto se = detail::scope_exit([&] {
  17243. svr.stop();
  17244. t.join();
  17245. ASSERT_FALSE(svr.is_running());
  17246. });
  17247. svr.wait_until_ready();
  17248. // The client supplies the first field line; the trusted proxy appends the
  17249. // address it observed as a second one.
  17250. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17251. "Host: localhost\r\n"
  17252. "X-Forwarded-For: 1.2.3.4\r\n"
  17253. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17254. "Connection: close\r\n"
  17255. "\r\n";
  17256. std::string out;
  17257. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17258. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17259. EXPECT_EQ(observed_xff_count, 2U);
  17260. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17261. // The same chain spread over one field line per hop derives the same client
  17262. // address, i.e. the split and the comma-joined representations agree.
  17263. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17264. "Host: localhost\r\n"
  17265. "X-Forwarded-For: 1.2.3.4\r\n"
  17266. "X-Forwarded-For: 198.51.100.23\r\n"
  17267. "X-Forwarded-For: 192.0.2.45\r\n"
  17268. "Connection: close\r\n"
  17269. "\r\n";
  17270. out.clear();
  17271. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17272. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17273. EXPECT_EQ(observed_xff_count, 3U);
  17274. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17275. }
  17276. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17277. // crash the server (it used to call front() on an empty vector inside
  17278. // get_client_ip). The connection-level remote address must be retained instead.
  17279. static void run_malformed_xff_test(const std::string &xff_value) {
  17280. Server svr;
  17281. svr.set_trusted_proxies({"192.0.2.45"});
  17282. std::string observed_remote_addr;
  17283. svr.Get("/ip", [&](const Request &req, Response &res) {
  17284. observed_remote_addr = req.remote_addr;
  17285. res.set_content("ok", "text/plain");
  17286. });
  17287. int port = 0;
  17288. thread t = thread([&]() {
  17289. port = svr.bind_to_any_port(HOST);
  17290. svr.listen_after_bind();
  17291. });
  17292. auto se = detail::scope_exit([&] {
  17293. svr.stop();
  17294. t.join();
  17295. ASSERT_FALSE(svr.is_running());
  17296. });
  17297. svr.wait_until_ready();
  17298. Client cli(HOST, port);
  17299. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17301. EXPECT_EQ(StatusCode::OK_200, res->status);
  17302. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17303. observed_remote_addr == "127.0.0.1");
  17304. }
  17305. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17306. run_malformed_xff_test("");
  17307. }
  17308. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17309. run_malformed_xff_test(",");
  17310. }
  17311. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17312. run_malformed_xff_test(", , ,");
  17313. }
  17314. // The same rule applies to Accept: a request whose acceptable types are spread
  17315. // over several field lines must be negotiated against all of them.
  17316. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17317. // case-insensitive connection options. Comparing the whole field value against
  17318. // one option misses a client that sends several of them, and misses every
  17319. // casing but the one written in the comparison.
  17320. //
  17321. // Sends req, reads the response, then reuses the same socket for a second
  17322. // request to find out whether the server kept the connection.
  17323. static void probe_connection_reuse(int port, const std::string &req,
  17324. bool *announced_close, bool *reusable) {
  17325. auto error = Error::Success;
  17326. auto sock = detail::create_client_socket(
  17327. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17328. /*connection_timeout_sec=*/5, 0,
  17329. /*read_timeout_sec=*/1, 0,
  17330. /*write_timeout_sec=*/5, 0, std::string(), error);
  17331. ASSERT_NE(sock, INVALID_SOCKET);
  17332. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17333. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17334. "Host: localhost\r\n"
  17335. "Connection: close\r\n"
  17336. "\r\n";
  17337. std::string first_response;
  17338. std::string second_response;
  17339. detail::process_client_socket(
  17340. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17341. [&](Stream &strm) {
  17342. if (strm.write(req.data(), req.size()) !=
  17343. static_cast<ssize_t>(req.size())) {
  17344. return false;
  17345. }
  17346. char buf[512];
  17347. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17348. // Headers plus the two-byte body of the handler below
  17349. while (reader.getline()) {
  17350. first_response += reader.ptr();
  17351. if (first_response.find("ok") != std::string::npos) { break; }
  17352. }
  17353. if (strm.write(second.data(), second.size()) !=
  17354. static_cast<ssize_t>(second.size())) {
  17355. return true;
  17356. }
  17357. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17358. while (reader2.getline()) {
  17359. second_response += reader2.ptr();
  17360. if (second_response.find("ok") != std::string::npos) { break; }
  17361. }
  17362. return true;
  17363. });
  17364. *announced_close =
  17365. first_response.find("Connection: close") != std::string::npos;
  17366. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17367. }
  17368. class ConnectionTokenTest : public ::testing::Test {
  17369. protected:
  17370. void SetUp() override {
  17371. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17372. res.set_content("ok", "text/plain");
  17373. });
  17374. port_ = svr_.bind_to_any_port(HOST);
  17375. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17376. svr_.wait_until_ready();
  17377. }
  17378. void TearDown() override {
  17379. svr_.stop();
  17380. if (thread_.joinable()) { thread_.join(); }
  17381. }
  17382. Server svr_;
  17383. int port_ = 0;
  17384. thread thread_;
  17385. };
  17386. // "close" alongside another option still closes the connection, and the
  17387. // response says so rather than leaving the peer to discover it.
  17388. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17389. bool announced_close = false;
  17390. bool reusable = true;
  17391. probe_connection_reuse(port_,
  17392. "GET /keepalive HTTP/1.1\r\n"
  17393. "Host: localhost\r\n"
  17394. "Connection: keep-alive, close\r\n"
  17395. "\r\n",
  17396. &announced_close, &reusable);
  17397. EXPECT_TRUE(announced_close);
  17398. EXPECT_FALSE(reusable);
  17399. }
  17400. // "close" split over two field lines is the same list, so it is honored too.
  17401. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17402. bool announced_close = false;
  17403. bool reusable = true;
  17404. probe_connection_reuse(port_,
  17405. "GET /keepalive HTTP/1.1\r\n"
  17406. "Host: localhost\r\n"
  17407. "Connection: keep-alive\r\n"
  17408. "Connection: close\r\n"
  17409. "\r\n",
  17410. &announced_close, &reusable);
  17411. EXPECT_TRUE(announced_close);
  17412. EXPECT_FALSE(reusable);
  17413. }
  17414. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17415. // keep-alive in the spelling everyone actually sends keeps its connection.
  17416. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17417. bool announced_close = false;
  17418. bool reusable = false;
  17419. probe_connection_reuse(port_,
  17420. "GET /keepalive HTTP/1.0\r\n"
  17421. "Host: localhost\r\n"
  17422. "Connection: keep-alive\r\n"
  17423. "\r\n",
  17424. &announced_close, &reusable);
  17425. EXPECT_FALSE(announced_close);
  17426. EXPECT_TRUE(reusable);
  17427. }
  17428. // A token the value merely contains is not the token itself.
  17429. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17430. bool announced_close = false;
  17431. bool reusable = false;
  17432. probe_connection_reuse(port_,
  17433. "GET /keepalive HTTP/1.1\r\n"
  17434. "Host: localhost\r\n"
  17435. "Connection: notclose\r\n"
  17436. "\r\n",
  17437. &announced_close, &reusable);
  17438. EXPECT_FALSE(announced_close);
  17439. EXPECT_TRUE(reusable);
  17440. }
  17441. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17442. Server svr;
  17443. std::vector<std::string> observed_types;
  17444. svr.Get("/", [&](const Request &req, Response &res) {
  17445. observed_types = req.accept_content_types;
  17446. res.set_content("ok", "text/plain");
  17447. });
  17448. auto port = svr.bind_to_any_port(HOST);
  17449. thread t = thread([&]() { svr.listen_after_bind(); });
  17450. auto se = detail::scope_exit([&] {
  17451. svr.stop();
  17452. t.join();
  17453. ASSERT_FALSE(svr.is_running());
  17454. });
  17455. svr.wait_until_ready();
  17456. Client cli(HOST, port);
  17457. Headers headers;
  17458. headers.emplace("Accept", "text/plain;q=0.5");
  17459. headers.emplace("Accept", "application/json");
  17460. auto res = cli.Get("/", headers);
  17461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17462. EXPECT_EQ(StatusCode::OK_200, res->status);
  17463. // Sorted by q-value, so the second field line's type comes first
  17464. ASSERT_EQ(2U, observed_types.size());
  17465. EXPECT_EQ("application/json", observed_types[0]);
  17466. EXPECT_EQ("text/plain", observed_types[1]);
  17467. }
  17468. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17469. // empty field line must not contribute a bare comma to the combined value.
  17470. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17471. Server svr;
  17472. std::vector<std::string> observed_types;
  17473. svr.Get("/", [&](const Request &req, Response &res) {
  17474. observed_types = req.accept_content_types;
  17475. res.set_content("ok", "text/plain");
  17476. });
  17477. auto port = svr.bind_to_any_port(HOST);
  17478. thread t = thread([&]() { svr.listen_after_bind(); });
  17479. auto se = detail::scope_exit([&] {
  17480. svr.stop();
  17481. t.join();
  17482. ASSERT_FALSE(svr.is_running());
  17483. });
  17484. svr.wait_until_ready();
  17485. // Empty first field line, then a real one
  17486. std::string raw_req = "GET / HTTP/1.1\r\n"
  17487. "Host: localhost\r\n"
  17488. "Accept:\r\n"
  17489. "Accept: application/json\r\n"
  17490. "Connection: close\r\n"
  17491. "\r\n";
  17492. std::string out;
  17493. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17494. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17495. ASSERT_EQ(1U, observed_types.size());
  17496. EXPECT_EQ("application/json", observed_types[0]);
  17497. }
  17498. // The skip in get_combined_header_value() is what keeps an empty field line
  17499. // from contributing a bare comma. Only a trailing empty field line exercises
  17500. // it: a leading one is already covered by the "combined is still empty" check,
  17501. // and parse_accept_header() now ignores the empty element either way, so the
  17502. // request-level test above can no longer tell the two apart.
  17503. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17504. Headers headers;
  17505. headers.emplace("Accept", "text/html");
  17506. headers.emplace("Accept", "");
  17507. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17508. headers.clear();
  17509. headers.emplace("Accept", "");
  17510. headers.emplace("Accept", "application/json");
  17511. EXPECT_EQ("application/json",
  17512. detail::get_combined_header_value(headers, "Accept"));
  17513. }
  17514. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17515. // An encoding offered on a later Accept-Encoding field line is still offered.
  17516. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17517. Server svr;
  17518. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17519. res.set_content(std::string(1024, 'x'), "text/plain");
  17520. });
  17521. auto port = svr.bind_to_any_port(HOST);
  17522. thread t = thread([&]() { svr.listen_after_bind(); });
  17523. auto se = detail::scope_exit([&] {
  17524. svr.stop();
  17525. t.join();
  17526. ASSERT_FALSE(svr.is_running());
  17527. });
  17528. svr.wait_until_ready();
  17529. Client cli(HOST, port);
  17530. cli.set_decompress(false);
  17531. Headers headers;
  17532. headers.emplace("Accept-Encoding", "identity");
  17533. headers.emplace("Accept-Encoding", "gzip");
  17534. auto res = cli.Get("/", headers);
  17535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17536. EXPECT_EQ(StatusCode::OK_200, res->status);
  17537. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17538. }
  17539. #endif
  17540. #ifndef _WIN32
  17541. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17542. Server svr;
  17543. svr.Post("/post", [&](const Request &req, Response &res) {
  17544. res.set_content(req.body, "text/plain");
  17545. });
  17546. svr.Put("/put", [&](const Request &req, Response &res) {
  17547. res.set_content(req.body, "text/plain");
  17548. });
  17549. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17550. res.set_content(req.body, "text/plain");
  17551. });
  17552. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17553. res.set_content(req.body, "text/plain");
  17554. });
  17555. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17556. auto se = detail::scope_exit([&] {
  17557. svr.stop();
  17558. t.join();
  17559. ASSERT_FALSE(svr.is_running());
  17560. });
  17561. svr.wait_until_ready();
  17562. std::string resp;
  17563. // POST without Content-Length
  17564. ASSERT_TRUE(send_request(5,
  17565. "POST /post HTTP/1.1\r\n"
  17566. "Host: localhost\r\n"
  17567. "Connection: close\r\n"
  17568. "\r\n",
  17569. &resp));
  17570. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17571. // PUT without Content-Length
  17572. resp.clear();
  17573. ASSERT_TRUE(send_request(5,
  17574. "PUT /put HTTP/1.1\r\n"
  17575. "Host: localhost\r\n"
  17576. "Connection: close\r\n"
  17577. "\r\n",
  17578. &resp));
  17579. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17580. // PATCH without Content-Length
  17581. resp.clear();
  17582. ASSERT_TRUE(send_request(5,
  17583. "PATCH /patch HTTP/1.1\r\n"
  17584. "Host: localhost\r\n"
  17585. "Connection: close\r\n"
  17586. "\r\n",
  17587. &resp));
  17588. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17589. // DELETE without Content-Length
  17590. resp.clear();
  17591. ASSERT_TRUE(send_request(5,
  17592. "DELETE /delete HTTP/1.1\r\n"
  17593. "Host: localhost\r\n"
  17594. "Connection: close\r\n"
  17595. "\r\n",
  17596. &resp));
  17597. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17598. }
  17599. #endif
  17600. //==============================================================================
  17601. // open_stream() Tests
  17602. //==============================================================================
  17603. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17604. std::string result;
  17605. char buf[8192];
  17606. ssize_t n;
  17607. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17608. result.append(buf, static_cast<size_t>(n));
  17609. }
  17610. return result;
  17611. }
  17612. // Mock stream for unit tests
  17613. class MockStream : public Stream {
  17614. public:
  17615. std::string data;
  17616. size_t pos = 0;
  17617. ssize_t error_after = -1; // -1 = no error
  17618. explicit MockStream(const std::string &d, ssize_t err = -1)
  17619. : data(d), error_after(err) {}
  17620. bool is_readable() const override { return true; }
  17621. bool wait_readable() const override { return true; }
  17622. bool wait_writable() const override { return true; }
  17623. ssize_t read(char *ptr, size_t size) override {
  17624. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17625. if (pos >= data.size()) return 0;
  17626. size_t limit =
  17627. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17628. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17629. std::memcpy(ptr, data.data() + pos, to_read);
  17630. pos += to_read;
  17631. return static_cast<ssize_t>(to_read);
  17632. }
  17633. ssize_t write(const char *, size_t) override { return -1; }
  17634. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17635. ip = "127.0.0.1";
  17636. port = 0;
  17637. }
  17638. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17639. ip = "127.0.0.1";
  17640. port = 0;
  17641. }
  17642. socket_t socket() const override { return INVALID_SOCKET; }
  17643. time_t duration() const override { return 0; }
  17644. };
  17645. TEST(StreamHandleTest, Basic) {
  17646. ClientImpl::StreamHandle handle;
  17647. EXPECT_FALSE(handle.is_valid());
  17648. handle.response = detail::make_unique<Response>();
  17649. handle.error = Error::Connection;
  17650. EXPECT_FALSE(handle.is_valid());
  17651. handle.error = Error::Success;
  17652. EXPECT_TRUE(handle.is_valid());
  17653. }
  17654. TEST(BodyReaderTest, Basic) {
  17655. MockStream stream("Hello, World!");
  17656. detail::BodyReader reader;
  17657. reader.stream = &stream;
  17658. reader.content_length = 13;
  17659. char buf[32];
  17660. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17661. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17662. EXPECT_TRUE(reader.eof);
  17663. }
  17664. TEST(BodyReaderTest, NoStream) {
  17665. detail::BodyReader reader;
  17666. char buf[32];
  17667. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17668. EXPECT_EQ(Error::Connection, reader.last_error);
  17669. }
  17670. TEST(BodyReaderTest, Error) {
  17671. MockStream stream("Hello, World!", 5);
  17672. detail::BodyReader reader;
  17673. reader.stream = &stream;
  17674. reader.content_length = 13;
  17675. char buf[32];
  17676. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17677. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17678. EXPECT_EQ(Error::Read, reader.last_error);
  17679. }
  17680. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17681. // Mock-based StreamHandle tests relying on private internals are removed.
  17682. class OpenStreamTest : public ::testing::Test {
  17683. protected:
  17684. void SetUp() override {
  17685. svr_.Get("/hello", [](const Request &, Response &res) {
  17686. res.set_content("Hello World!", "text/plain");
  17687. });
  17688. svr_.Get("/large", [](const Request &, Response &res) {
  17689. res.set_content(std::string(10000, 'X'), "text/plain");
  17690. });
  17691. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17692. res.set_content("Hello World!", "image/jpeg");
  17693. res.set_header("Content-Encoding", "UTF-8");
  17694. });
  17695. svr_.Get("/chunked", [](const Request &, Response &res) {
  17696. res.set_chunked_content_provider("text/plain",
  17697. [](size_t offset, DataSink &sink) {
  17698. if (offset < 15) {
  17699. sink.write("chunk", 5);
  17700. return true;
  17701. }
  17702. sink.done();
  17703. return true;
  17704. });
  17705. });
  17706. svr_.Get("/compressible", [](const Request &, Response &res) {
  17707. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17708. DataSink &sink) {
  17709. if (offset < 100 * 1024) {
  17710. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17711. sink.write(chunk.data(), chunk.size());
  17712. return true;
  17713. }
  17714. sink.done();
  17715. return true;
  17716. });
  17717. });
  17718. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17719. [](const Request & /*req*/, Response &res) {
  17720. auto i = new int(0);
  17721. res.set_header("Trailer", "Content-Length, X-Allowed");
  17722. res.set_chunked_content_provider(
  17723. "text/plain",
  17724. [i](size_t /*offset*/, DataSink &sink) {
  17725. switch (*i) {
  17726. case 0: sink.os << "123"; break;
  17727. case 1: sink.os << "456"; break;
  17728. case 2: sink.os << "789"; break;
  17729. case 3: {
  17730. sink.done_with_trailer(
  17731. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17732. } break;
  17733. }
  17734. (*i)++;
  17735. return true;
  17736. },
  17737. [i](bool success) {
  17738. EXPECT_TRUE(success);
  17739. delete i;
  17740. });
  17741. });
  17742. // Echo headers endpoint for header-related tests
  17743. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17744. std::string body;
  17745. for (const auto &h : req.headers) {
  17746. body.append(h.first);
  17747. body.push_back(':');
  17748. body.append(h.second);
  17749. body.push_back('\n');
  17750. }
  17751. res.set_content(body, "text/plain");
  17752. });
  17753. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17754. std::string body;
  17755. for (const auto &h : req.headers) {
  17756. body.append(h.first);
  17757. body.push_back(':');
  17758. body.append(h.second);
  17759. body.push_back('\n');
  17760. }
  17761. res.set_content(body, "text/plain");
  17762. });
  17763. port_ = svr_.bind_to_any_port("127.0.0.1");
  17764. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17765. svr_.wait_until_ready();
  17766. }
  17767. void TearDown() override {
  17768. svr_.stop();
  17769. if (thread_.joinable()) thread_.join();
  17770. }
  17771. Server svr_;
  17772. std::thread thread_;
  17773. int port_ = 0;
  17774. };
  17775. TEST_F(OpenStreamTest, Basic) {
  17776. Client cli("127.0.0.1", port_);
  17777. auto handle = cli.open_stream("GET", "/hello");
  17778. EXPECT_TRUE(handle.is_valid());
  17779. EXPECT_EQ("Hello World!", read_all(handle));
  17780. }
  17781. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17782. Client cli("127.0.0.1", port_);
  17783. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17784. ASSERT_TRUE(handle.is_valid());
  17785. EXPECT_EQ("Hello World!", read_all(handle));
  17786. }
  17787. TEST_F(OpenStreamTest, SmallBuffer) {
  17788. Client cli("127.0.0.1", port_);
  17789. auto handle = cli.open_stream("GET", "/hello");
  17790. std::string result;
  17791. char buf[4];
  17792. ssize_t n;
  17793. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17794. result.append(buf, static_cast<size_t>(n));
  17795. EXPECT_EQ("Hello World!", result);
  17796. }
  17797. TEST_F(OpenStreamTest, DefaultHeaders) {
  17798. Client cli("127.0.0.1", port_);
  17799. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17800. {
  17801. auto handle = cli.open_stream("GET", "/echo-headers");
  17802. ASSERT_TRUE(handle.is_valid());
  17803. auto body = read_all(handle);
  17804. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17805. std::string::npos);
  17806. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17807. std::string::npos);
  17808. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17809. }
  17810. // open_stream POST with body and no explicit content_type should NOT add
  17811. // text/plain Content-Type (behavior differs from non-streaming path), but
  17812. // should include Content-Length
  17813. {
  17814. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17815. ASSERT_TRUE(handle.is_valid());
  17816. auto body = read_all(handle);
  17817. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17818. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17819. }
  17820. // open_stream POST with explicit Content-Type should preserve it
  17821. {
  17822. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17823. {{"Content-Type", "application/custom"}},
  17824. "{}", "application/custom");
  17825. ASSERT_TRUE(handle.is_valid());
  17826. auto body = read_all(handle);
  17827. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17828. }
  17829. // User-specified User-Agent must not be overwritten for stream API
  17830. {
  17831. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17832. {{"User-Agent", "MyAgent/1.2"}});
  17833. ASSERT_TRUE(handle.is_valid());
  17834. auto body = read_all(handle);
  17835. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17836. }
  17837. }
  17838. TEST_F(OpenStreamTest, Large) {
  17839. Client cli("127.0.0.1", port_);
  17840. auto handle = cli.open_stream("GET", "/large");
  17841. EXPECT_EQ(10000u, read_all(handle).size());
  17842. }
  17843. TEST_F(OpenStreamTest, ConnectionError) {
  17844. Client cli("127.0.0.1", 9999);
  17845. auto handle = cli.open_stream("GET", "/hello");
  17846. EXPECT_FALSE(handle.is_valid());
  17847. }
  17848. TEST_F(OpenStreamTest, Chunked) {
  17849. Client cli("127.0.0.1", port_);
  17850. auto handle = cli.open_stream("GET", "/chunked");
  17851. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17852. "Transfer-Encoding") == "chunked");
  17853. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17854. }
  17855. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17856. Client cli("127.0.0.1", port_);
  17857. auto handle =
  17858. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17859. ASSERT_TRUE(handle.is_valid());
  17860. // Consume body to allow trailers to be received/parsed
  17861. auto body = read_all(handle);
  17862. // Explicitly parse trailers (ensure trailers are available for assertion)
  17863. handle.parse_trailers_if_needed();
  17864. EXPECT_EQ(std::string("123456789"), body);
  17865. // The response should include a Trailer header declaring both names
  17866. ASSERT_TRUE(handle.response);
  17867. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17868. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17869. handle.response->get_header_value("Trailer"));
  17870. // Prohibited trailer must not be present
  17871. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17872. // Allowed trailer should be present
  17873. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17874. EXPECT_EQ(std::string("yes"),
  17875. handle.response->get_trailer_value("X-Allowed"));
  17876. // Verify trailers are NOT present as regular headers
  17877. EXPECT_EQ(std::string(""),
  17878. handle.response->get_header_value("Content-Length"));
  17879. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17880. }
  17881. static std::thread serve_single_response(std::promise<int> &port_promise,
  17882. const std::string &response) {
  17883. return std::thread([&port_promise, response] {
  17884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17885. default_socket_options(srv);
  17886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17888. sockaddr_in addr{};
  17889. addr.sin_family = AF_INET;
  17890. addr.sin_port = htons(0); // Let OS assign a free port
  17891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17892. int opt = 1;
  17893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17894. #ifdef _WIN32
  17895. reinterpret_cast<const char *>(&opt),
  17896. #else
  17897. &opt,
  17898. #endif
  17899. sizeof(opt));
  17900. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17901. ::listen(srv, 1) != 0) {
  17902. port_promise.set_value(-1);
  17903. detail::close_socket(srv);
  17904. return;
  17905. }
  17906. socklen_t addr_len = sizeof(addr);
  17907. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17908. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17909. sockaddr_in cli_addr{};
  17910. socklen_t cli_len = sizeof(cli_addr);
  17911. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17912. if (cli != INVALID_SOCKET) {
  17913. // Read the complete HTTP request (until the blank line that terminates
  17914. // headers) before sending the response. If the server closes the socket
  17915. // while the client's request data is still unread in the kernel receive
  17916. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17917. // connection on both sides: it discards the client's receive buffer
  17918. // (which already holds our response) and causes any in-progress write on
  17919. // the client to fail with ECONNRESET. Reading all request data first
  17920. // ensures close() emits a graceful FIN.
  17921. {
  17922. char rbuf[256];
  17923. std::string req;
  17924. while (req.find("\r\n\r\n") == std::string::npos) {
  17925. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17926. if (n <= 0) { break; }
  17927. req.append(rbuf, static_cast<size_t>(n));
  17928. }
  17929. }
  17930. ::send(cli,
  17931. #ifdef _WIN32
  17932. static_cast<const char *>(response.c_str()),
  17933. static_cast<int>(response.size()),
  17934. #else
  17935. response.c_str(), response.size(),
  17936. #endif
  17937. 0);
  17938. detail::close_socket(cli);
  17939. }
  17940. detail::close_socket(srv);
  17941. });
  17942. }
  17943. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17944. #ifndef _WIN32
  17945. signal(SIGPIPE, SIG_IGN);
  17946. #endif
  17947. std::promise<int> port_promise;
  17948. auto port_future = port_promise.get_future();
  17949. auto server_thread =
  17950. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17951. "Content-Type: text/plain\r\n"
  17952. "Content-Length: not-a-number\r\n"
  17953. "Connection: close\r\n"
  17954. "\r\n"
  17955. "hello");
  17956. auto port = port_future.get();
  17957. ASSERT_GT(port, 0);
  17958. Client cli("127.0.0.1", port);
  17959. auto handle = cli.open_stream("GET", "/");
  17960. EXPECT_FALSE(handle.is_valid());
  17961. server_thread.join();
  17962. }
  17963. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17964. #ifndef _WIN32
  17965. signal(SIGPIPE, SIG_IGN);
  17966. #endif
  17967. std::promise<int> port_promise;
  17968. auto port_future = port_promise.get_future();
  17969. auto server_thread = serve_single_response(
  17970. port_promise, "HTTP/1.1 200 OK\r\n"
  17971. "Content-Type: text/plain\r\n"
  17972. "Content-Length: 99999999999999999999999999\r\n"
  17973. "Connection: close\r\n"
  17974. "\r\n"
  17975. "hello");
  17976. auto port = port_future.get();
  17977. ASSERT_GT(port, 0);
  17978. // Historically std::stoull would throw std::out_of_range here and crash
  17979. // the process, then parsing silently clamped to a bogus framing length and
  17980. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17981. // so the stream fails to open, matching the not-a-number case above. The
  17982. // process still must NOT terminate.
  17983. Client cli("127.0.0.1", port);
  17984. auto handle = cli.open_stream("GET", "/");
  17985. EXPECT_FALSE(handle.is_valid());
  17986. server_thread.join();
  17987. }
  17988. // Serves `response` to the single request `fn` makes with a fresh client.
  17989. template <typename Fn>
  17990. static void with_single_response(const std::string &response, Fn fn) {
  17991. #ifndef _WIN32
  17992. signal(SIGPIPE, SIG_IGN);
  17993. #endif
  17994. std::promise<int> port_promise;
  17995. auto port_future = port_promise.get_future();
  17996. auto server_thread = serve_single_response(port_promise, response);
  17997. auto se = detail::scope_exit([&] { server_thread.join(); });
  17998. auto port = port_future.get();
  17999. ASSERT_GT(port, 0);
  18000. Client cli("127.0.0.1", port);
  18001. fn(cli);
  18002. }
  18003. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18004. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18005. // the chunked coding and drop Content-Length, so a front-end that trusts
  18006. // Content-Length would disagree about where the body ends (response
  18007. // smuggling). The client must reject such a response.
  18008. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18009. for (const char *te : {"chunked", "gzip, chunked"}) {
  18010. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18011. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18012. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18013. "5\r\nhello\r\n0\r\n\r\n";
  18014. with_single_response(response, [&](Client &cli) {
  18015. auto res = cli.Get("/");
  18016. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18017. EXPECT_EQ(Error::Read, res.error()) << te;
  18018. });
  18019. with_single_response(response, [&](Client &cli) {
  18020. auto handle = cli.open_stream("GET", "/");
  18021. EXPECT_FALSE(handle.is_valid()) << te;
  18022. EXPECT_EQ(Error::Read, handle.error) << te;
  18023. });
  18024. }
  18025. }
  18026. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18027. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18028. // closing the connection (unlike a request, which must be rejected).
  18029. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18030. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18031. "Transfer-Encoding: chunked\r\n"
  18032. "Connection: close\r\n"
  18033. "\r\n"
  18034. "5\r\nhello\r\n0\r\n\r\n",
  18035. "HTTP/1.1 200 OK\r\n"
  18036. "Transfer-Encoding: gzip\r\n"
  18037. "Connection: close\r\n"
  18038. "\r\n"
  18039. "hello"}) {
  18040. with_single_response(response, [&](Client &cli) {
  18041. auto res = cli.Get("/");
  18042. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18043. EXPECT_EQ("hello", res->body);
  18044. });
  18045. with_single_response(response, [&](Client &cli) {
  18046. auto handle = cli.open_stream("GET", "/");
  18047. ASSERT_TRUE(handle.is_valid()) << response;
  18048. EXPECT_EQ("hello", read_all(handle));
  18049. });
  18050. }
  18051. }
  18052. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18053. // framing headers describe nothing to read and must not be rejected.
  18054. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18055. const std::string framing = "Content-Length: 5\r\n"
  18056. "Transfer-Encoding: chunked\r\n"
  18057. "Connection: close\r\n"
  18058. "\r\n";
  18059. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18060. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18061. });
  18062. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18063. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18064. });
  18065. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18066. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18067. with_single_response(response, [&](Client &cli) {
  18068. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18069. });
  18070. with_single_response(response, [&](Client &cli) {
  18071. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18072. });
  18073. }
  18074. }
  18075. // A payload max length of 0 means no limit, however the body is framed.
  18076. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18077. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18078. "Transfer-Encoding: chunked\r\n"
  18079. "\r\n"
  18080. "5\r\nhello\r\n0\r\n\r\n",
  18081. "HTTP/1.1 200 OK\r\n"
  18082. "Connection: close\r\n"
  18083. "\r\n"
  18084. "hello"}) {
  18085. with_single_response(response, [&](Client &cli) {
  18086. cli.set_payload_max_length(0);
  18087. auto res = cli.Get("/");
  18088. ASSERT_TRUE(res) << response;
  18089. EXPECT_EQ("hello", res->body) << response;
  18090. });
  18091. }
  18092. }
  18093. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18094. Server svr;
  18095. svr.set_payload_max_length(0);
  18096. svr.Post("/echo", [](const Request &req, Response &res) {
  18097. res.set_content(req.body, "text/plain");
  18098. });
  18099. auto port = svr.bind_to_any_port(HOST);
  18100. thread t = thread([&] { svr.listen_after_bind(); });
  18101. auto se = detail::scope_exit([&] {
  18102. svr.stop();
  18103. t.join();
  18104. ASSERT_FALSE(svr.is_running());
  18105. });
  18106. svr.wait_until_ready();
  18107. Client cli(HOST, port);
  18108. auto res = cli.Post(
  18109. "/echo",
  18110. [](size_t /*offset*/, DataSink &sink) {
  18111. sink.write("hello", 5);
  18112. sink.done();
  18113. return true;
  18114. },
  18115. "text/plain");
  18116. ASSERT_TRUE(res);
  18117. EXPECT_EQ(StatusCode::OK_200, res->status);
  18118. EXPECT_EQ("hello", res->body);
  18119. }
  18120. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18121. TEST_F(OpenStreamTest, Gzip) {
  18122. Client cli("127.0.0.1", port_);
  18123. auto handle = cli.open_stream("GET", "/compressible", {},
  18124. {{"Accept-Encoding", "gzip"}});
  18125. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18126. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18127. }
  18128. #endif
  18129. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18130. TEST_F(OpenStreamTest, Brotli) {
  18131. Client cli("127.0.0.1", port_);
  18132. auto handle =
  18133. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18134. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18135. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18136. }
  18137. #endif
  18138. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18139. TEST_F(OpenStreamTest, Zstd) {
  18140. Client cli("127.0.0.1", port_);
  18141. auto handle = cli.open_stream("GET", "/compressible", {},
  18142. {{"Accept-Encoding", "zstd"}});
  18143. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18144. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18145. }
  18146. #endif
  18147. #ifdef CPPHTTPLIB_SSL_ENABLED
  18148. class SSLOpenStreamTest : public ::testing::Test {
  18149. protected:
  18150. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18151. void SetUp() override {
  18152. svr_.Get("/hello", [](const Request &, Response &res) {
  18153. res.set_content("Hello SSL World!", "text/plain");
  18154. });
  18155. svr_.Get("/chunked", [](const Request &, Response &res) {
  18156. res.set_chunked_content_provider("text/plain",
  18157. [](size_t offset, DataSink &sink) {
  18158. if (offset < 15) {
  18159. sink.write("chunk", 5);
  18160. return true;
  18161. }
  18162. sink.done();
  18163. return true;
  18164. });
  18165. });
  18166. svr_.Post("/echo", [](const Request &req, Response &res) {
  18167. res.set_content(req.body, req.get_header_value("Content-Type"));
  18168. });
  18169. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18170. std::string body = req.body;
  18171. res.set_chunked_content_provider(
  18172. "text/plain", [body](size_t offset, DataSink &sink) {
  18173. if (offset < body.size()) {
  18174. sink.write(body.data() + offset, body.size() - offset);
  18175. }
  18176. sink.done();
  18177. return true;
  18178. });
  18179. });
  18180. port_ = svr_.bind_to_any_port("127.0.0.1");
  18181. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18182. svr_.wait_until_ready();
  18183. }
  18184. void TearDown() override {
  18185. svr_.stop();
  18186. if (thread_.joinable()) thread_.join();
  18187. }
  18188. SSLServer svr_;
  18189. std::thread thread_;
  18190. int port_ = 0;
  18191. };
  18192. TEST_F(SSLOpenStreamTest, Basic) {
  18193. SSLClient cli("127.0.0.1", port_);
  18194. cli.enable_server_certificate_verification(false);
  18195. auto handle = cli.open_stream("GET", "/hello");
  18196. ASSERT_TRUE(handle.is_valid());
  18197. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18198. }
  18199. TEST_F(SSLOpenStreamTest, Chunked) {
  18200. SSLClient cli("127.0.0.1", port_);
  18201. cli.enable_server_certificate_verification(false);
  18202. auto handle = cli.open_stream("GET", "/chunked");
  18203. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18204. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18205. "Transfer-Encoding") == "chunked");
  18206. auto body = read_all(handle);
  18207. EXPECT_EQ("chunkchunkchunk", body);
  18208. }
  18209. TEST_F(SSLOpenStreamTest, Post) {
  18210. SSLClient cli("127.0.0.1", port_);
  18211. cli.enable_server_certificate_verification(false);
  18212. auto handle =
  18213. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18214. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18215. EXPECT_EQ(200, handle.response->status);
  18216. auto body = read_all(handle);
  18217. EXPECT_EQ("Hello SSL POST", body);
  18218. }
  18219. TEST_F(SSLOpenStreamTest, PostChunked) {
  18220. SSLClient cli("127.0.0.1", port_);
  18221. cli.enable_server_certificate_verification(false);
  18222. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18223. "Chunked SSL Data", "text/plain");
  18224. ASSERT_TRUE(handle.is_valid());
  18225. EXPECT_EQ(200, handle.response->status);
  18226. auto body = read_all(handle);
  18227. EXPECT_EQ("Chunked SSL Data", body);
  18228. }
  18229. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18230. // Content-Length is terminated by the server closing the connection. When the
  18231. // SSL peer sends a close_notify after the body, the client must treat it as a
  18232. // clean EOF and return a successful response rather than an error.
  18233. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18235. ASSERT_TRUE(svr.is_valid());
  18236. svr.set_keep_alive_max_count(1);
  18237. const std::string expected_body = "Hello from connection-close response!";
  18238. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18239. res.set_content_provider("text/plain",
  18240. [&](size_t offset, DataSink &sink) -> bool {
  18241. if (offset < expected_body.size()) {
  18242. sink.write(expected_body.data() + offset,
  18243. expected_body.size() - offset);
  18244. }
  18245. sink.done();
  18246. return true;
  18247. });
  18248. });
  18249. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. listen_thread.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. SSLClient cli(HOST, PORT);
  18257. cli.enable_server_certificate_verification(false);
  18258. auto res = cli.Get("/no-content-length");
  18259. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18260. EXPECT_EQ(StatusCode::OK_200, res->status);
  18261. EXPECT_EQ(expected_body, res->body);
  18262. }
  18263. #endif // CPPHTTPLIB_SSL_ENABLED
  18264. //==============================================================================
  18265. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18266. // results for various scenarios.
  18267. //==============================================================================
  18268. TEST(ParityTest, GetVsOpenStream) {
  18269. Server svr;
  18270. const std::string path = "/parity";
  18271. const std::string content = "Parity test content: hello world";
  18272. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18273. res.set_content(content, "text/plain");
  18274. });
  18275. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18276. auto se = detail::scope_exit([&] {
  18277. svr.stop();
  18278. t.join();
  18279. ASSERT_FALSE(svr.is_running());
  18280. });
  18281. svr.wait_until_ready();
  18282. Client cli(HOST, PORT);
  18283. // Non-stream path
  18284. auto r1 = cli.Get(path);
  18285. ASSERT_TRUE(r1);
  18286. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18287. // Stream path
  18288. auto h = cli.open_stream("GET", path);
  18289. ASSERT_TRUE(h.is_valid());
  18290. EXPECT_EQ(r1->body, read_all(h));
  18291. }
  18292. // Helper to compress data with provided compressor type T
  18293. template <typename Compressor>
  18294. static std::string compress_payload_for_parity(const std::string &in) {
  18295. std::string out;
  18296. Compressor compressor;
  18297. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18298. [&](const char *data, size_t n) {
  18299. out.append(data, n);
  18300. return true;
  18301. });
  18302. EXPECT_TRUE(ok);
  18303. return out;
  18304. }
  18305. // Helper function for compression parity tests
  18306. template <typename Compressor>
  18307. static void test_compression_parity(const std::string &original,
  18308. const std::string &path,
  18309. const std::string &encoding) {
  18310. const std::string compressed =
  18311. compress_payload_for_parity<Compressor>(original);
  18312. Server svr;
  18313. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18314. res.set_content(compressed, "application/octet-stream");
  18315. res.set_header("Content-Encoding", encoding);
  18316. });
  18317. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18318. auto se = detail::scope_exit([&] {
  18319. svr.stop();
  18320. t.join();
  18321. ASSERT_FALSE(svr.is_running());
  18322. });
  18323. svr.wait_until_ready();
  18324. Client cli(HOST, PORT);
  18325. // Non-streaming
  18326. {
  18327. auto res = cli.Get(path);
  18328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18329. EXPECT_EQ(StatusCode::OK_200, res->status);
  18330. EXPECT_EQ(original, res->body);
  18331. }
  18332. // Streaming
  18333. {
  18334. auto h = cli.open_stream("GET", path);
  18335. ASSERT_TRUE(h.is_valid());
  18336. EXPECT_EQ(original, read_all(h));
  18337. }
  18338. }
  18339. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18340. TEST(ParityTest, Gzip) {
  18341. test_compression_parity<detail::gzip_compressor>(
  18342. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18343. }
  18344. #endif
  18345. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18346. TEST(ParityTest, Brotli) {
  18347. test_compression_parity<detail::brotli_compressor>(
  18348. "Hello, brotli parity test payload", "/parity-br", "br");
  18349. }
  18350. #endif
  18351. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18352. TEST(ParityTest, Zstd) {
  18353. test_compression_parity<detail::zstd_compressor>(
  18354. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18355. }
  18356. #endif
  18357. //==============================================================================
  18358. // New Stream API Tests
  18359. //==============================================================================
  18360. inline std::string read_body(httplib::stream::Result &result) {
  18361. std::string body;
  18362. while (result.next()) {
  18363. body.append(result.data(), result.size());
  18364. }
  18365. return body;
  18366. }
  18367. TEST(ClientConnectionTest, Basic) {
  18368. httplib::ClientConnection conn;
  18369. EXPECT_FALSE(conn.is_open());
  18370. conn.sock = 1;
  18371. EXPECT_TRUE(conn.is_open());
  18372. httplib::ClientConnection conn2(std::move(conn));
  18373. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18374. conn2.sock = INVALID_SOCKET;
  18375. }
  18376. // Unified test server for all stream::* tests
  18377. class StreamApiTest : public ::testing::Test {
  18378. protected:
  18379. void SetUp() override {
  18380. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18381. res.set_content("Hello World!", "text/plain");
  18382. });
  18383. svr_.Get("/echo-params",
  18384. [](const httplib::Request &req, httplib::Response &res) {
  18385. std::string r;
  18386. for (const auto &p : req.params) {
  18387. if (!r.empty()) r += "&";
  18388. r += p.first + "=" + p.second;
  18389. }
  18390. res.set_content(r, "text/plain");
  18391. });
  18392. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18393. res.set_content(req.body, req.get_header_value("Content-Type"));
  18394. });
  18395. svr_.Post("/echo-headers",
  18396. [](const httplib::Request &req, httplib::Response &res) {
  18397. std::string r;
  18398. for (const auto &h : req.headers)
  18399. r += h.first + ": " + h.second + "\n";
  18400. res.set_content(r, "text/plain");
  18401. });
  18402. svr_.Post("/echo-params",
  18403. [](const httplib::Request &req, httplib::Response &res) {
  18404. std::string r = "params:";
  18405. for (const auto &p : req.params)
  18406. r += p.first + "=" + p.second + ";";
  18407. res.set_content(r + " body:" + req.body, "text/plain");
  18408. });
  18409. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18410. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18411. });
  18412. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18413. res.set_content("PUT:" + req.body, "text/plain");
  18414. });
  18415. svr_.Patch("/echo",
  18416. [](const httplib::Request &req, httplib::Response &res) {
  18417. res.set_content("PATCH:" + req.body, "text/plain");
  18418. });
  18419. svr_.Delete(
  18420. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18421. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18422. "text/plain");
  18423. });
  18424. svr_.Get("/head-test",
  18425. [](const httplib::Request &, httplib::Response &res) {
  18426. res.set_content("body for HEAD", "text/plain");
  18427. });
  18428. svr_.Options("/options",
  18429. [](const httplib::Request &, httplib::Response &res) {
  18430. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18431. });
  18432. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18433. svr_.wait_until_ready();
  18434. }
  18435. void TearDown() override {
  18436. svr_.stop();
  18437. if (thread_.joinable()) thread_.join();
  18438. }
  18439. httplib::Server svr_;
  18440. std::thread thread_;
  18441. };
  18442. // stream::Get tests
  18443. TEST_F(StreamApiTest, GetBasic) {
  18444. httplib::Client cli(HOST, PORT);
  18445. auto result = httplib::stream::Get(cli, "/hello");
  18446. ASSERT_TRUE(result.is_valid());
  18447. EXPECT_EQ(200, result.status());
  18448. EXPECT_EQ("Hello World!", read_body(result));
  18449. }
  18450. TEST_F(StreamApiTest, GetWithParams) {
  18451. httplib::Client cli(HOST, PORT);
  18452. httplib::Params params{{"foo", "bar"}};
  18453. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18454. ASSERT_TRUE(result.is_valid());
  18455. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18456. }
  18457. TEST_F(StreamApiTest, GetConnectionError) {
  18458. httplib::Client cli(HOST, 9999);
  18459. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18460. }
  18461. TEST_F(StreamApiTest, Get404) {
  18462. httplib::Client cli(HOST, PORT);
  18463. auto result = httplib::stream::Get(cli, "/nonexistent");
  18464. EXPECT_TRUE(result.is_valid());
  18465. EXPECT_EQ(404, result.status());
  18466. }
  18467. // stream::Post tests
  18468. TEST_F(StreamApiTest, PostBasic) {
  18469. httplib::Client cli(HOST, PORT);
  18470. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18471. "application/json");
  18472. ASSERT_TRUE(result.is_valid());
  18473. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18474. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18475. }
  18476. TEST_F(StreamApiTest, PostWithHeaders) {
  18477. httplib::Client cli(HOST, PORT);
  18478. httplib::Headers headers{{"X-Custom", "value"}};
  18479. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18480. "text/plain");
  18481. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18482. }
  18483. TEST_F(StreamApiTest, PostWithParams) {
  18484. httplib::Client cli(HOST, PORT);
  18485. httplib::Params params{{"k", "v"}};
  18486. auto result =
  18487. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18488. auto body = read_body(result);
  18489. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18490. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18491. }
  18492. TEST_F(StreamApiTest, PostLarge) {
  18493. httplib::Client cli(HOST, PORT);
  18494. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18495. size_t total = 0;
  18496. while (result.next()) {
  18497. total += result.size();
  18498. }
  18499. EXPECT_EQ(100u * 1024u, total);
  18500. }
  18501. // stream::Put/Patch tests
  18502. TEST_F(StreamApiTest, PutAndPatch) {
  18503. httplib::Client cli(HOST, PORT);
  18504. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18505. EXPECT_EQ("PUT:test", read_body(put));
  18506. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18507. EXPECT_EQ("PATCH:test", read_body(patch));
  18508. }
  18509. // stream::Delete tests
  18510. TEST_F(StreamApiTest, Delete) {
  18511. httplib::Client cli(HOST, PORT);
  18512. auto del1 = httplib::stream::Delete(cli, "/resource");
  18513. EXPECT_EQ("Deleted", read_body(del1));
  18514. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18515. EXPECT_EQ("Deleted:data", read_body(del2));
  18516. }
  18517. // stream::Head/Options tests
  18518. TEST_F(StreamApiTest, HeadAndOptions) {
  18519. httplib::Client cli(HOST, PORT);
  18520. auto head = httplib::stream::Head(cli, "/head-test");
  18521. EXPECT_TRUE(head.is_valid());
  18522. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18523. auto opts = httplib::stream::Options(cli, "/options");
  18524. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18525. }
  18526. // SSL stream::* tests
  18527. #ifdef CPPHTTPLIB_SSL_ENABLED
  18528. class SSLStreamApiTest : public ::testing::Test {
  18529. protected:
  18530. void SetUp() override {
  18531. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18532. res.set_content("Hello SSL!", "text/plain");
  18533. });
  18534. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18535. res.set_content(req.body, "text/plain");
  18536. });
  18537. port_ = svr_.bind_to_any_port("127.0.0.1");
  18538. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18539. svr_.wait_until_ready();
  18540. }
  18541. void TearDown() override {
  18542. svr_.stop();
  18543. if (thread_.joinable()) thread_.join();
  18544. }
  18545. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18546. std::thread thread_;
  18547. int port_ = 0;
  18548. };
  18549. TEST_F(SSLStreamApiTest, GetAndPost) {
  18550. httplib::SSLClient cli("127.0.0.1", port_);
  18551. cli.enable_server_certificate_verification(false);
  18552. auto get = httplib::stream::Get(cli, "/hello");
  18553. EXPECT_EQ("Hello SSL!", read_body(get));
  18554. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18555. EXPECT_EQ("test", read_body(post));
  18556. }
  18557. #endif
  18558. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18559. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18560. // BodyReader
  18561. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18562. // Test that read timeout during streaming is detected
  18563. // Use a large content-length response where server delays mid-stream
  18564. Server svr;
  18565. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18566. // Send a large response with delay in the middle
  18567. res.set_content_provider(
  18568. 1000, // content_length
  18569. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18570. if (offset < 100) {
  18571. // Send first 100 bytes immediately
  18572. std::string data(100, 'A');
  18573. sink.write(data.c_str(), data.size());
  18574. return true;
  18575. }
  18576. // Then delay longer than client timeout
  18577. std::this_thread::sleep_for(std::chrono::seconds(3));
  18578. std::string data(900, 'B');
  18579. sink.write(data.c_str(), data.size());
  18580. return true;
  18581. });
  18582. });
  18583. auto port = 8091;
  18584. std::thread t([&]() { svr.listen("localhost", port); });
  18585. svr.wait_until_ready();
  18586. Client cli("localhost", port);
  18587. cli.set_read_timeout(1, 0); // 1 second timeout
  18588. auto handle = cli.open_stream("GET", "/slow-stream");
  18589. ASSERT_TRUE(handle.is_valid());
  18590. char buf[256];
  18591. ssize_t total = 0;
  18592. ssize_t n;
  18593. bool got_error = false;
  18594. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18595. total += n;
  18596. }
  18597. if (n < 0) {
  18598. got_error = true;
  18599. // Should be timeout or read error
  18600. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18601. handle.get_read_error() == Error::Read)
  18602. << "Actual error: " << to_string(handle.get_read_error());
  18603. }
  18604. // Either we got an error, or we got less data than expected
  18605. EXPECT_TRUE(got_error || total < 1000)
  18606. << "Expected timeout but got all " << total << " bytes";
  18607. svr.stop();
  18608. t.join();
  18609. }
  18610. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18611. // Test connection closed detection via BodyReader
  18612. Server svr;
  18613. std::atomic<bool> close_now{false};
  18614. svr.Get("/will-close", [&](const Request &, Response &res) {
  18615. res.set_content_provider(
  18616. 10000, // Large content_length that we won't fully send
  18617. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18618. if (offset < 100) {
  18619. std::string data(100, 'X');
  18620. sink.write(data.c_str(), data.size());
  18621. return true;
  18622. }
  18623. // Wait for signal then abort
  18624. while (!close_now) {
  18625. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18626. }
  18627. return false; // Abort - server will close connection
  18628. });
  18629. });
  18630. auto port = 8092;
  18631. std::thread t([&]() { svr.listen("localhost", port); });
  18632. svr.wait_until_ready();
  18633. Client cli("localhost", port);
  18634. auto handle = cli.open_stream("GET", "/will-close");
  18635. ASSERT_TRUE(handle.is_valid());
  18636. char buf[256];
  18637. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18638. EXPECT_GT(n, 0) << "First read should succeed";
  18639. // Signal server to close
  18640. close_now = true;
  18641. // Keep reading until error or EOF
  18642. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18643. // Keep reading
  18644. }
  18645. // Should get an error since content_length wasn't satisfied
  18646. if (n < 0) {
  18647. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18648. handle.get_read_error() == Error::Read)
  18649. << "Actual error: " << to_string(handle.get_read_error());
  18650. }
  18651. svr.stop();
  18652. t.join();
  18653. }
  18654. #ifdef CPPHTTPLIB_SSL_ENABLED
  18655. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18656. // Test that read timeout during SSL streaming is detected
  18657. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18658. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18659. res.set_content_provider(
  18660. 1000, "text/plain",
  18661. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18662. if (offset < 100) {
  18663. std::string data(100, 'A');
  18664. sink.write(data.c_str(), data.size());
  18665. return true;
  18666. }
  18667. std::this_thread::sleep_for(std::chrono::seconds(3));
  18668. std::string data(900, 'B');
  18669. sink.write(data.c_str(), data.size());
  18670. return true;
  18671. });
  18672. });
  18673. auto port = 8093;
  18674. std::thread t([&]() { svr.listen("localhost", port); });
  18675. svr.wait_until_ready();
  18676. SSLClient cli("localhost", port);
  18677. cli.enable_server_certificate_verification(false);
  18678. cli.set_read_timeout(1, 0); // 1 second timeout
  18679. auto handle = cli.open_stream("GET", "/slow-stream");
  18680. ASSERT_TRUE(handle.is_valid());
  18681. char buf[256];
  18682. ssize_t total = 0;
  18683. ssize_t n;
  18684. bool got_error = false;
  18685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18686. total += n;
  18687. }
  18688. if (n < 0) {
  18689. got_error = true;
  18690. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18691. handle.get_read_error() == Error::Read)
  18692. << "Actual error: " << to_string(handle.get_read_error());
  18693. }
  18694. EXPECT_TRUE(got_error || total < 1000)
  18695. << "Expected timeout but got all " << total << " bytes";
  18696. svr.stop();
  18697. t.join();
  18698. }
  18699. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18700. // Test SSL connection closed detection
  18701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18702. std::atomic<bool> close_now{false};
  18703. svr.Get("/will-close", [&](const Request &, Response &res) {
  18704. res.set_content_provider(
  18705. 10000, "text/plain",
  18706. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18707. if (offset < 100) {
  18708. std::string data(100, 'X');
  18709. sink.write(data.c_str(), data.size());
  18710. return true;
  18711. }
  18712. while (!close_now) {
  18713. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18714. }
  18715. return false;
  18716. });
  18717. });
  18718. auto port = 8094;
  18719. std::thread t([&]() { svr.listen("localhost", port); });
  18720. svr.wait_until_ready();
  18721. SSLClient cli("localhost", port);
  18722. cli.enable_server_certificate_verification(false);
  18723. auto handle = cli.open_stream("GET", "/will-close");
  18724. ASSERT_TRUE(handle.is_valid());
  18725. char buf[256];
  18726. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18727. EXPECT_GT(n, 0);
  18728. // Signal server to close
  18729. close_now = true;
  18730. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18731. // Keep reading
  18732. }
  18733. if (n < 0) {
  18734. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18735. handle.get_read_error() == Error::Read)
  18736. << "Actual error: " << to_string(handle.get_read_error());
  18737. }
  18738. svr.stop();
  18739. t.join();
  18740. }
  18741. #endif
  18742. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18743. using namespace httplib;
  18744. // Create a test file
  18745. const char *fname = "etag_testfile.txt";
  18746. const char *content = "etag-content";
  18747. {
  18748. std::ofstream ofs(fname);
  18749. ofs << content;
  18750. ASSERT_TRUE(ofs.good());
  18751. }
  18752. Server svr;
  18753. svr.set_mount_point("/static", ".");
  18754. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18755. svr.wait_until_ready();
  18756. Client cli(HOST, PORT);
  18757. // First request: should get 200 with ETag header
  18758. auto res1 = cli.Get("/static/etag_testfile.txt");
  18759. ASSERT_TRUE(res1);
  18760. ASSERT_EQ(200, res1->status);
  18761. ASSERT_TRUE(res1->has_header("ETag"));
  18762. std::string etag = res1->get_header_value("ETag");
  18763. EXPECT_FALSE(etag.empty());
  18764. // Verify ETag format: W/"hex-hex"
  18765. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18766. EXPECT_EQ('W', etag[0]);
  18767. EXPECT_EQ('/', etag[1]);
  18768. EXPECT_EQ('"', etag[2]);
  18769. EXPECT_EQ('"', etag.back());
  18770. // Exact match: expect 304 Not Modified
  18771. Headers h2 = {{"If-None-Match", etag}};
  18772. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18773. ASSERT_TRUE(res2);
  18774. EXPECT_EQ(304, res2->status);
  18775. // Wildcard match: expect 304 Not Modified
  18776. Headers h3 = {{"If-None-Match", "*"}};
  18777. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18778. ASSERT_TRUE(res3);
  18779. EXPECT_EQ(304, res3->status);
  18780. // Non-matching ETag: expect 200
  18781. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18782. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18783. ASSERT_TRUE(res4);
  18784. EXPECT_EQ(200, res4->status);
  18785. // Multiple ETags with one matching: expect 304
  18786. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18787. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18788. ASSERT_TRUE(res5);
  18789. EXPECT_EQ(304, res5->status);
  18790. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18791. // that equivalent to the single comma-separated list above, so the match on
  18792. // the second line must still be found.
  18793. Headers h6;
  18794. h6.emplace("If-None-Match", "W/\"other\"");
  18795. h6.emplace("If-None-Match", etag);
  18796. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18797. ASSERT_TRUE(res6);
  18798. EXPECT_EQ(304, res6->status);
  18799. svr.stop();
  18800. t.join();
  18801. std::remove(fname);
  18802. }
  18803. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18804. using namespace httplib;
  18805. Server svr;
  18806. svr.set_mount_point("/static", ".");
  18807. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18808. svr.wait_until_ready();
  18809. Client cli(HOST, PORT);
  18810. // Send If-None-Match: * to a non-existent file
  18811. Headers h = {{"If-None-Match", "*"}};
  18812. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18814. EXPECT_EQ(404, res->status);
  18815. svr.stop();
  18816. t.join();
  18817. }
  18818. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18819. using namespace httplib;
  18820. // Create a test file
  18821. const char *fname = "etag_boundary_testfile.txt";
  18822. const char *content = "boundary-test";
  18823. {
  18824. std::ofstream ofs(fname);
  18825. ofs << content;
  18826. ASSERT_TRUE(ofs.good());
  18827. }
  18828. Server svr;
  18829. svr.set_mount_point("/static", ".");
  18830. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18831. svr.wait_until_ready();
  18832. Client cli(HOST, PORT);
  18833. // Get the actual ETag
  18834. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18835. ASSERT_TRUE(res1);
  18836. ASSERT_EQ(200, res1->status);
  18837. ASSERT_TRUE(res1->has_header("ETag"));
  18838. std::string etag = res1->get_header_value("ETag");
  18839. // Test 1: Very long ETag value (longer than actual ETag)
  18840. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18841. Headers h1 = {{"If-None-Match", "W/"
  18842. "\"very-long-etag-value-that-is-much-longer-"
  18843. "than-the-actual-etag-value\""}};
  18844. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18845. ASSERT_TRUE(res2);
  18846. EXPECT_EQ(200, res2->status); // Should not match
  18847. // Test 2: Long string followed by wildcard
  18848. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18849. // string)
  18850. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18851. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18852. ASSERT_TRUE(res3);
  18853. EXPECT_EQ(304, res3->status); // Should match on "*"
  18854. // Test 3: Wildcard followed by long string
  18855. // Should match on "*" immediately and return 304
  18856. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18857. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18858. ASSERT_TRUE(res4);
  18859. EXPECT_EQ(304, res4->status); // Should match on "*"
  18860. // Test 4: Multiple long non-matching values
  18861. // Should NOT match and return 200 (test that all comparisons are safe)
  18862. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18863. "W/\"second-long-non-matching-value\", "
  18864. "W/\"third-long-non-matching-value\""}};
  18865. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18866. ASSERT_TRUE(res5);
  18867. EXPECT_EQ(200, res5->status); // Should not match
  18868. // Test 5: Single character that is not "*" (edge case)
  18869. Headers h5 = {{"If-None-Match", "X"}};
  18870. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18871. ASSERT_TRUE(res6);
  18872. EXPECT_EQ(200, res6->status); // Should not match
  18873. svr.stop();
  18874. t.join();
  18875. std::remove(fname);
  18876. }
  18877. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18878. using namespace httplib;
  18879. // Create a test file
  18880. const char *fname = "ims_testfile.txt";
  18881. const char *content = "if-modified-since-test";
  18882. {
  18883. std::ofstream ofs(fname);
  18884. ofs << content;
  18885. ASSERT_TRUE(ofs.good());
  18886. }
  18887. Server svr;
  18888. svr.set_mount_point("/static", ".");
  18889. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18890. svr.wait_until_ready();
  18891. Client cli(HOST, PORT);
  18892. // First request: should get 200 with Last-Modified header
  18893. auto res1 = cli.Get("/static/ims_testfile.txt");
  18894. ASSERT_TRUE(res1);
  18895. ASSERT_EQ(200, res1->status);
  18896. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18897. std::string last_modified = res1->get_header_value("Last-Modified");
  18898. EXPECT_FALSE(last_modified.empty());
  18899. // If-Modified-Since with same time: expect 304
  18900. Headers h2 = {{"If-Modified-Since", last_modified}};
  18901. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18902. ASSERT_TRUE(res2);
  18903. EXPECT_EQ(304, res2->status);
  18904. // If-Modified-Since with future time: expect 304
  18905. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18906. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18907. ASSERT_TRUE(res3);
  18908. EXPECT_EQ(304, res3->status);
  18909. // If-Modified-Since with past time: expect 200
  18910. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18911. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18912. ASSERT_TRUE(res4);
  18913. EXPECT_EQ(200, res4->status);
  18914. // If-None-Match takes precedence over If-Modified-Since
  18915. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18916. ASSERT_TRUE(res1->has_header("ETag"));
  18917. std::string etag = res1->get_header_value("ETag");
  18918. Headers h5 = {{"If-None-Match", etag},
  18919. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18920. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18921. ASSERT_TRUE(res5);
  18922. EXPECT_EQ(304, res5->status);
  18923. svr.stop();
  18924. t.join();
  18925. std::remove(fname);
  18926. }
  18927. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18928. using namespace httplib;
  18929. Server svr;
  18930. // Endpoint that returns compressible content
  18931. svr.Get("/compressible", [](const Request &, Response &res) {
  18932. // Return a large enough body to trigger compression
  18933. std::string body(1000, 'a');
  18934. res.set_content(body, "text/plain");
  18935. });
  18936. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18937. svr.wait_until_ready();
  18938. Client cli(HOST, PORT);
  18939. // Request with gzip support: should get Vary header when compressed
  18940. cli.set_compress(true);
  18941. auto res1 = cli.Get("/compressible");
  18942. ASSERT_TRUE(res1);
  18943. EXPECT_EQ(200, res1->status);
  18944. // If Content-Encoding is set, Vary should also be set
  18945. if (res1->has_header("Content-Encoding")) {
  18946. EXPECT_TRUE(res1->has_header("Vary"));
  18947. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18948. }
  18949. // Request without Accept-Encoding header: should not have compression
  18950. Headers h_no_compress;
  18951. auto res2 = cli.Get("/compressible", h_no_compress);
  18952. ASSERT_TRUE(res2);
  18953. EXPECT_EQ(200, res2->status);
  18954. // Verify Vary header is present when compression is applied
  18955. // (the exact behavior depends on server configuration)
  18956. svr.stop();
  18957. t.join();
  18958. }
  18959. TEST(ETagTest, IfRangeWithETag) {
  18960. using namespace httplib;
  18961. // Create a test file with known content
  18962. const char *fname = "if_range_testfile.txt";
  18963. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18964. {
  18965. std::ofstream ofs(fname);
  18966. ofs << content;
  18967. ASSERT_TRUE(ofs.good());
  18968. }
  18969. Server svr;
  18970. svr.set_mount_point("/static", ".");
  18971. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18972. svr.wait_until_ready();
  18973. Client cli(HOST, PORT);
  18974. // First request: get ETag
  18975. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18976. ASSERT_TRUE(res1);
  18977. ASSERT_EQ(200, res1->status);
  18978. ASSERT_TRUE(res1->has_header("ETag"));
  18979. std::string etag = res1->get_header_value("ETag");
  18980. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18981. // Since our server generates weak ETags (W/"..."), If-Range with our
  18982. // ETag should NOT result in partial content - it should return full content.
  18983. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18984. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18985. ASSERT_TRUE(res2);
  18986. // Weak ETag in If-Range -> full content (200), not partial (206)
  18987. EXPECT_EQ(200, res2->status);
  18988. EXPECT_EQ(content, res2->body);
  18989. EXPECT_FALSE(res2->has_header("Content-Range"));
  18990. // Range request with non-matching If-Range (ETag): should get 200 (full
  18991. // content)
  18992. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18993. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18994. ASSERT_TRUE(res3);
  18995. EXPECT_EQ(200, res3->status);
  18996. EXPECT_EQ(content, res3->body);
  18997. EXPECT_FALSE(res3->has_header("Content-Range"));
  18998. // Range request with strong ETag (hypothetical - our server doesn't generate
  18999. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19000. // should return full content)
  19001. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19002. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19003. ASSERT_TRUE(res4);
  19004. EXPECT_EQ(200, res4->status);
  19005. EXPECT_EQ(content, res4->body);
  19006. EXPECT_FALSE(res4->has_header("Content-Range"));
  19007. svr.stop();
  19008. t.join();
  19009. std::remove(fname);
  19010. }
  19011. TEST(ETagTest, IfRangeWithDate) {
  19012. using namespace httplib;
  19013. // Create a test file
  19014. const char *fname = "if_range_date_testfile.txt";
  19015. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19016. {
  19017. std::ofstream ofs(fname);
  19018. ofs << content;
  19019. ASSERT_TRUE(ofs.good());
  19020. }
  19021. Server svr;
  19022. svr.set_mount_point("/static", ".");
  19023. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19024. svr.wait_until_ready();
  19025. Client cli(HOST, PORT);
  19026. // First request: get Last-Modified
  19027. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19028. ASSERT_TRUE(res1);
  19029. ASSERT_EQ(200, res1->status);
  19030. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19031. std::string last_modified = res1->get_header_value("Last-Modified");
  19032. // Range request with matching If-Range (date): should get 206
  19033. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19034. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19035. ASSERT_TRUE(res2);
  19036. EXPECT_EQ(206, res2->status);
  19037. EXPECT_EQ("FGHIJ", res2->body);
  19038. // Range request with old If-Range date: should get 200 (full content)
  19039. Headers h3 = {{"Range", "bytes=5-9"},
  19040. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19041. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19042. ASSERT_TRUE(res3);
  19043. EXPECT_EQ(200, res3->status);
  19044. EXPECT_EQ(content, res3->body);
  19045. // Range request with future If-Range date: should get 206
  19046. Headers h4 = {{"Range", "bytes=0-4"},
  19047. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19048. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19049. ASSERT_TRUE(res4);
  19050. EXPECT_EQ(206, res4->status);
  19051. EXPECT_EQ("ABCDE", res4->body);
  19052. svr.stop();
  19053. t.join();
  19054. std::remove(fname);
  19055. }
  19056. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19057. using namespace httplib;
  19058. const char *fname = "etag_malformed.txt";
  19059. const char *content = "malformed-etag";
  19060. {
  19061. std::ofstream ofs(fname);
  19062. ofs << content;
  19063. ASSERT_TRUE(ofs.good());
  19064. }
  19065. Server svr;
  19066. svr.set_mount_point("/static", ".");
  19067. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19068. svr.wait_until_ready();
  19069. Client cli(HOST, PORT);
  19070. // baseline: should get 200 and an ETag
  19071. auto res1 = cli.Get("/static/etag_malformed.txt");
  19072. ASSERT_TRUE(res1);
  19073. ASSERT_EQ(200, res1->status);
  19074. ASSERT_TRUE(res1->has_header("ETag"));
  19075. // Malformed ETag value (missing quotes) should be treated as non-matching
  19076. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19077. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19078. ASSERT_TRUE(res_bad);
  19079. EXPECT_EQ(200, res_bad->status);
  19080. // Whitespace-only header value should be considered invalid / non-matching
  19081. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19082. "Host: localhost\r\n"
  19083. "If-None-Match: \r\n"
  19084. "Connection: close\r\n"
  19085. "\r\n";
  19086. std::string out;
  19087. ASSERT_TRUE(send_request(5, raw_req, &out));
  19088. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19089. svr.stop();
  19090. t.join();
  19091. std::remove(fname);
  19092. }
  19093. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19094. using namespace httplib;
  19095. const char *fname = "ims_invalid_format.txt";
  19096. const char *content = "ims-bad-format";
  19097. {
  19098. std::ofstream ofs(fname);
  19099. ofs << content;
  19100. ASSERT_TRUE(ofs.good());
  19101. }
  19102. Server svr;
  19103. svr.set_mount_point("/static", ".");
  19104. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19105. svr.wait_until_ready();
  19106. Client cli(HOST, PORT);
  19107. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19108. ASSERT_TRUE(res1);
  19109. ASSERT_EQ(200, res1->status);
  19110. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19111. // If-Modified-Since with invalid format should not result in 304
  19112. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19113. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19114. ASSERT_TRUE(res_bad);
  19115. EXPECT_EQ(200, res_bad->status);
  19116. // If-Range with invalid date format should be treated as mismatch -> full
  19117. // content (200)
  19118. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19119. {"If-Range", "invalid-date"}};
  19120. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19121. ASSERT_TRUE(res_ifrange);
  19122. EXPECT_EQ(200, res_ifrange->status);
  19123. svr.stop();
  19124. t.join();
  19125. std::remove(fname);
  19126. }
  19127. TEST(ETagTest, IfRangeWithMalformedETag) {
  19128. using namespace httplib;
  19129. const char *fname = "ifrange_malformed.txt";
  19130. const std::string content = "0123456789";
  19131. {
  19132. std::ofstream ofs(fname);
  19133. ofs << content;
  19134. ASSERT_TRUE(ofs.good());
  19135. }
  19136. Server svr;
  19137. svr.set_mount_point("/static", ".");
  19138. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. // First request: get ETag
  19142. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19143. ASSERT_TRUE(res1);
  19144. ASSERT_EQ(200, res1->status);
  19145. ASSERT_TRUE(res1->has_header("ETag"));
  19146. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19147. // full content (200)
  19148. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19149. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19150. ASSERT_TRUE(res2);
  19151. EXPECT_EQ(200, res2->status);
  19152. EXPECT_EQ(content, res2->body);
  19153. svr.stop();
  19154. t.join();
  19155. std::remove(fname);
  19156. }
  19157. TEST(ETagTest, ExtremeLargeDateValues) {
  19158. using namespace httplib;
  19159. const char *fname = "ims_extreme_date.txt";
  19160. const char *content = "ims-extreme-date";
  19161. {
  19162. std::ofstream ofs(fname);
  19163. ofs << content;
  19164. ASSERT_TRUE(ofs.good());
  19165. }
  19166. Server svr;
  19167. svr.set_mount_point("/static", ".");
  19168. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19169. svr.wait_until_ready();
  19170. Client cli(HOST, PORT);
  19171. auto res1 = cli.Get(std::string("/static/") + fname);
  19172. ASSERT_TRUE(res1);
  19173. ASSERT_EQ(200, res1->status);
  19174. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19175. // Extremely large year that may overflow date parsing routines.
  19176. Headers h_large_date = {
  19177. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19178. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19179. ASSERT_TRUE(res_bad);
  19180. // Expect server to treat this as invalid/mismatch and return full content
  19181. EXPECT_EQ(200, res_bad->status);
  19182. // If-Range with extremely large date should be treated as mismatch -> full
  19183. // content (200)
  19184. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19185. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19186. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19187. ASSERT_TRUE(res_ifrange);
  19188. EXPECT_EQ(200, res_ifrange->status);
  19189. svr.stop();
  19190. t.join();
  19191. std::remove(fname);
  19192. }
  19193. TEST(ETagTest, NegativeFileModificationTime) {
  19194. using namespace httplib;
  19195. const char *fname = "ims_negative_mtime.txt";
  19196. const std::string content = "negative-mtime";
  19197. {
  19198. std::ofstream ofs(fname);
  19199. ofs << content;
  19200. ASSERT_TRUE(ofs.good());
  19201. }
  19202. // Try to set file mtime to a negative value. This may fail on some
  19203. // platforms/filesystems; if it fails, the test will still verify server
  19204. // behaves safely by performing a regular conditional request.
  19205. #if defined(__APPLE__) || defined(__linux__)
  19206. bool set_negative = false;
  19207. do {
  19208. struct timeval times[2];
  19209. // access time: now
  19210. times[0].tv_sec = time(nullptr);
  19211. times[0].tv_usec = 0;
  19212. // modification time: negative (e.g., -1)
  19213. times[1].tv_sec = -1;
  19214. times[1].tv_usec = 0;
  19215. if (utimes(fname, times) == 0) { set_negative = true; }
  19216. } while (0);
  19217. #else
  19218. bool set_negative = false;
  19219. #endif
  19220. Server svr;
  19221. svr.set_mount_point("/static", ".");
  19222. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19223. svr.wait_until_ready();
  19224. Client cli(HOST, PORT);
  19225. auto res1 = cli.Get(std::string("/static/") + fname);
  19226. ASSERT_TRUE(res1);
  19227. ASSERT_EQ(200, res1->status);
  19228. bool has_last_modified = res1->has_header("Last-Modified");
  19229. std::string last_modified;
  19230. if (has_last_modified) {
  19231. last_modified = res1->get_header_value("Last-Modified");
  19232. }
  19233. if (set_negative) {
  19234. // If we successfully set a negative mtime, ensure server returns a
  19235. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19236. // with an old date and ensure server handles it without crash.
  19237. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19238. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19239. ASSERT_TRUE(res2);
  19240. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19241. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19242. } else {
  19243. // Could not set negative mtime on this platform; fall back to verifying
  19244. // that normal invalid/malformed dates are treated safely (non-304).
  19245. Headers h_bad_date = {
  19246. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19247. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19248. ASSERT_TRUE(res_bad);
  19249. EXPECT_EQ(200, res_bad->status);
  19250. }
  19251. svr.stop();
  19252. t.join();
  19253. std::remove(fname);
  19254. }
  19255. //==============================================================================
  19256. // Integration Tests with Server
  19257. //==============================================================================
  19258. class SSEIntegrationTest : public ::testing::Test {
  19259. protected:
  19260. void SetUp() override {
  19261. stop_server_.store(false);
  19262. events_.clear();
  19263. server_ = httplib::detail::make_unique<Server>();
  19264. setup_server();
  19265. start_server();
  19266. }
  19267. void TearDown() override {
  19268. stop_server_.store(true);
  19269. event_cv_.notify_all();
  19270. server_->stop();
  19271. if (server_thread_.joinable()) { server_thread_.join(); }
  19272. }
  19273. void setup_server() {
  19274. // Simple SSE endpoint
  19275. server_->Get("/events", [this](const Request &req, Response &res) {
  19276. auto last_id = req.get_header_value("Last-Event-ID");
  19277. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19278. res.set_chunked_content_provider(
  19279. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19280. std::unique_lock<std::mutex> lock(event_mutex_);
  19281. if (event_cv_.wait_for(
  19282. lock, std::chrono::milliseconds(200), [this] {
  19283. return !events_.empty() || stop_server_.load();
  19284. })) {
  19285. if (stop_server_.load()) { return false; }
  19286. if (!events_.empty()) {
  19287. std::string event = events_.front();
  19288. events_.erase(events_.begin());
  19289. sink.write(event.data(), event.size());
  19290. return true;
  19291. }
  19292. }
  19293. return !stop_server_.load();
  19294. });
  19295. });
  19296. // Endpoint that returns error
  19297. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19298. res.status = 500;
  19299. res.set_content("Internal Server Error", "text/plain");
  19300. });
  19301. // Endpoint for custom event types
  19302. server_->Get("/custom-events", [](const Request &, Response &res) {
  19303. res.set_chunked_content_provider(
  19304. "text/event-stream", [](size_t offset, DataSink &sink) {
  19305. if (offset == 0) {
  19306. std::string event = "event: update\ndata: updated\n\n"
  19307. "event: delete\ndata: deleted\n\n";
  19308. sink.write(event.data(), event.size());
  19309. }
  19310. return false; // End stream after sending
  19311. });
  19312. });
  19313. }
  19314. void start_server() {
  19315. port_ = server_->bind_to_any_port(HOST);
  19316. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19317. // Wait for server to start
  19318. while (!server_->is_running()) {
  19319. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19320. }
  19321. }
  19322. int get_port() const { return port_; }
  19323. void send_event(const std::string &event) {
  19324. std::lock_guard<std::mutex> lock(event_mutex_);
  19325. events_.push_back(event);
  19326. event_cv_.notify_all();
  19327. }
  19328. std::unique_ptr<Server> server_;
  19329. std::thread server_thread_;
  19330. std::mutex event_mutex_;
  19331. std::condition_variable event_cv_;
  19332. std::vector<std::string> events_;
  19333. std::atomic<bool> stop_server_{false};
  19334. std::string last_received_event_id_;
  19335. int port_ = 0;
  19336. };
  19337. //==============================================================================
  19338. // SSE Parsing Tests
  19339. //==============================================================================
  19340. class SSEParsingTest : public SSEIntegrationTest {
  19341. protected:
  19342. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19343. // A trailing sentinel event tells when the whole stream has been parsed.
  19344. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19345. auto body = stream + "event: end\ndata: end\n\n";
  19346. server_->Get("/parse", [body](const Request &, Response &res) {
  19347. res.set_content(body, "text/event-stream");
  19348. });
  19349. return collect("/parse");
  19350. }
  19351. // Runs SSEClient against path until an "end" event arrives and returns the
  19352. // messages dispatched before it
  19353. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19354. Client client(HOST, get_port());
  19355. sse::SSEClient sse(client, path);
  19356. std::mutex mutex;
  19357. std::condition_variable cv;
  19358. std::vector<sse::SSEMessage> messages;
  19359. auto done = false;
  19360. sse.on_message([&](const sse::SSEMessage &msg) {
  19361. std::lock_guard<std::mutex> lock(mutex);
  19362. // Ignore a replay from a reconnect that races with stop()
  19363. if (!done) { messages.push_back(msg); }
  19364. });
  19365. sse.on_event("end", [&](const sse::SSEMessage &) {
  19366. std::lock_guard<std::mutex> lock(mutex);
  19367. done = true;
  19368. cv.notify_all();
  19369. });
  19370. sse.set_reconnect_interval(100);
  19371. sse.start_async();
  19372. {
  19373. std::unique_lock<std::mutex> lock(mutex);
  19374. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19375. }
  19376. sse.stop();
  19377. EXPECT_TRUE(done);
  19378. return messages;
  19379. }
  19380. };
  19381. TEST_F(SSEParsingTest, SingleLineData) {
  19382. auto msgs = parse("data: hello\n\n");
  19383. ASSERT_EQ(msgs.size(), 1u);
  19384. EXPECT_EQ(msgs[0].data, "hello");
  19385. EXPECT_EQ(msgs[0].event, "message");
  19386. }
  19387. TEST_F(SSEParsingTest, MultiLineData) {
  19388. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19389. ASSERT_EQ(msgs.size(), 1u);
  19390. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19391. }
  19392. TEST_F(SSEParsingTest, CustomEventType) {
  19393. auto msgs = parse("event: update\ndata: payload\n\n");
  19394. ASSERT_EQ(msgs.size(), 1u);
  19395. EXPECT_EQ(msgs[0].event, "update");
  19396. EXPECT_EQ(msgs[0].data, "payload");
  19397. }
  19398. TEST_F(SSEParsingTest, EventIdHandling) {
  19399. auto msgs = parse("id: 12345\ndata: test\n\n");
  19400. ASSERT_EQ(msgs.size(), 1u);
  19401. EXPECT_EQ(msgs[0].id, "12345");
  19402. }
  19403. TEST_F(SSEParsingTest, EmptyEventId) {
  19404. auto msgs = parse("id:\ndata: test\n\n");
  19405. ASSERT_EQ(msgs.size(), 1u);
  19406. EXPECT_EQ(msgs[0].id, "");
  19407. }
  19408. TEST_F(SSEParsingTest, CommentsIgnored) {
  19409. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19410. ASSERT_EQ(msgs.size(), 1u);
  19411. EXPECT_EQ(msgs[0].data, "hello");
  19412. EXPECT_EQ(msgs[0].event, "message");
  19413. }
  19414. TEST_F(SSEParsingTest, ColonInValue) {
  19415. auto msgs = parse("data: hello:world:test\n\n");
  19416. ASSERT_EQ(msgs.size(), 1u);
  19417. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19418. }
  19419. TEST_F(SSEParsingTest, FieldNameOnly) {
  19420. // A line without a colon is a field name with an empty value
  19421. auto msgs = parse("data\n\n");
  19422. ASSERT_EQ(msgs.size(), 1u);
  19423. EXPECT_EQ(msgs[0].data, "");
  19424. }
  19425. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19426. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19427. ASSERT_EQ(msgs.size(), 1u);
  19428. EXPECT_EQ(msgs[0].event, "update");
  19429. EXPECT_EQ(msgs[0].data, "hello");
  19430. }
  19431. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19432. auto msgs = parse("data\r\n\r\n");
  19433. ASSERT_EQ(msgs.size(), 1u);
  19434. EXPECT_EQ(msgs[0].data, "");
  19435. }
  19436. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19437. auto msgs = parse("event: update\rdata: hello\r\r");
  19438. ASSERT_EQ(msgs.size(), 1u);
  19439. EXPECT_EQ(msgs[0].event, "update");
  19440. EXPECT_EQ(msgs[0].data, "hello");
  19441. }
  19442. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19443. // Chunk boundaries fall inside every \r\n and right before the first one
  19444. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19445. "\n\r", "\nevent: end\ndata: end\n\n"};
  19446. server_->Get("/split", [chunks](const Request &, Response &res) {
  19447. auto i = std::make_shared<size_t>(0);
  19448. res.set_chunked_content_provider(
  19449. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19450. if (*i == chunks.size()) {
  19451. sink.done();
  19452. } else {
  19453. sink.write(chunks[*i].data(), chunks[*i].size());
  19454. (*i)++;
  19455. }
  19456. return true;
  19457. });
  19458. });
  19459. auto msgs = collect("/split");
  19460. ASSERT_EQ(msgs.size(), 1u);
  19461. EXPECT_EQ(msgs[0].event, "update");
  19462. EXPECT_EQ(msgs[0].data, "hello");
  19463. }
  19464. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19465. // Only a BOM at the start of the stream is ignored
  19466. auto msgs = parse("\xEF\xBB\xBF"
  19467. "data: first\n\n"
  19468. "\xEF\xBB\xBF"
  19469. "data: second\n\n");
  19470. ASSERT_EQ(msgs.size(), 1u);
  19471. EXPECT_EQ(msgs[0].data, "first");
  19472. }
  19473. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19474. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19475. ASSERT_EQ(msgs.size(), 1u);
  19476. EXPECT_EQ(msgs[0].data, "hello");
  19477. EXPECT_EQ(msgs[0].event, "message");
  19478. }
  19479. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19480. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19481. ASSERT_EQ(msgs.size(), 2u);
  19482. EXPECT_EQ(msgs[0].data, "hello");
  19483. EXPECT_EQ(msgs[1].data, "hello");
  19484. }
  19485. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19486. // An event without data is not dispatched, and its type must not leak
  19487. // into the next event
  19488. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19489. ASSERT_EQ(msgs.size(), 1u);
  19490. EXPECT_EQ(msgs[0].event, "message");
  19491. EXPECT_EQ(msgs[0].data, "hello");
  19492. }
  19493. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19494. // The first connection sends only an id; the second echoes back the
  19495. // Last-Event-ID it was reconnected with
  19496. std::atomic<int> connection_count{0};
  19497. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19498. if (connection_count++ == 0) {
  19499. res.set_content("id: 42\n\n", "text/event-stream");
  19500. } else {
  19501. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19502. "\n\nevent: end\ndata: end\n\n",
  19503. "text/event-stream");
  19504. }
  19505. });
  19506. auto msgs = collect("/id-only");
  19507. ASSERT_EQ(msgs.size(), 1u);
  19508. EXPECT_EQ(msgs[0].data, "42");
  19509. }
  19510. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19511. // The first connection sets an id and then clears it with an empty one; the
  19512. // second reports whether it was reconnected with a Last-Event-ID
  19513. std::atomic<int> connection_count{0};
  19514. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19515. if (connection_count++ == 0) {
  19516. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19517. "text/event-stream");
  19518. } else {
  19519. res.set_content(
  19520. std::string("data: ") +
  19521. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19522. "\n\nevent: end\ndata: end\n\n",
  19523. "text/event-stream");
  19524. }
  19525. });
  19526. auto msgs = collect("/id-clear");
  19527. ASSERT_EQ(msgs.size(), 3u);
  19528. EXPECT_EQ(msgs[0].id, "1");
  19529. EXPECT_EQ(msgs[1].id, "");
  19530. EXPECT_EQ(msgs[2].data, "not sent");
  19531. }
  19532. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19533. // The first connection sets an id and then sends ids that cannot be carried
  19534. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19535. // with
  19536. std::atomic<int> connection_count{0};
  19537. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19538. if (connection_count++ == 0) {
  19539. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19540. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19541. "text/event-stream");
  19542. } else {
  19543. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19544. "\n\nevent: end\ndata: end\n\n",
  19545. "text/event-stream");
  19546. }
  19547. });
  19548. auto msgs = collect("/id-unsendable");
  19549. ASSERT_EQ(msgs.size(), 1u);
  19550. EXPECT_EQ(msgs[0].data, "42");
  19551. }
  19552. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19553. auto msgs = parse("event: notification\nid: evt-42\n"
  19554. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19555. ASSERT_EQ(msgs.size(), 1u);
  19556. EXPECT_EQ(msgs[0].event, "notification");
  19557. EXPECT_EQ(msgs[0].id, "evt-42");
  19558. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19559. }
  19560. TEST(SSEMessageTest, Clear) {
  19561. sse::SSEMessage msg;
  19562. msg.event = "custom";
  19563. msg.data = "some data";
  19564. msg.id = "123";
  19565. msg.clear();
  19566. EXPECT_EQ(msg.event, "message");
  19567. EXPECT_EQ(msg.data, "");
  19568. EXPECT_EQ(msg.id, "");
  19569. }
  19570. //==============================================================================
  19571. // SSE Integration Tests
  19572. //==============================================================================
  19573. // Test: Successful connection and on_open callback
  19574. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19575. // Add a simple endpoint that sends one event and closes
  19576. server_->Get("/simple-event", [](const Request &, Response &res) {
  19577. res.set_chunked_content_provider(
  19578. "text/event-stream", [](size_t offset, DataSink &sink) {
  19579. if (offset == 0) {
  19580. std::string event = "data: hello\n\n";
  19581. sink.write(event.data(), event.size());
  19582. }
  19583. return false; // Close stream after sending
  19584. });
  19585. });
  19586. Client client("localhost", get_port());
  19587. sse::SSEClient sse(client, "/simple-event");
  19588. std::atomic<bool> open_called{false};
  19589. std::atomic<bool> message_received{false};
  19590. sse.on_open([&open_called]() { open_called.store(true); });
  19591. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19592. if (msg.data == "hello") { message_received.store(true); }
  19593. });
  19594. sse.set_reconnect_interval(100);
  19595. sse.set_max_reconnect_attempts(1);
  19596. // Start async
  19597. sse.start_async();
  19598. // Wait for message to be processed
  19599. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19600. sse.stop();
  19601. EXPECT_TRUE(open_called.load());
  19602. EXPECT_TRUE(message_received.load());
  19603. }
  19604. // Test: on_message callback
  19605. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19606. // Endpoint that sends multiple events then closes
  19607. server_->Get("/multi-event", [](const Request &, Response &res) {
  19608. res.set_chunked_content_provider(
  19609. "text/event-stream", [](size_t offset, DataSink &sink) {
  19610. if (offset == 0) {
  19611. std::string events = "data: message1\n\ndata: message2\n\n";
  19612. sink.write(events.data(), events.size());
  19613. }
  19614. return false;
  19615. });
  19616. });
  19617. Client client("localhost", get_port());
  19618. sse::SSEClient sse(client, "/multi-event");
  19619. std::vector<std::string> received_messages;
  19620. std::mutex messages_mutex;
  19621. sse.on_message([&](const sse::SSEMessage &msg) {
  19622. std::lock_guard<std::mutex> lock(messages_mutex);
  19623. received_messages.push_back(msg.data);
  19624. });
  19625. sse.set_reconnect_interval(100);
  19626. sse.set_max_reconnect_attempts(1);
  19627. sse.start_async();
  19628. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19629. sse.stop();
  19630. std::lock_guard<std::mutex> lock(messages_mutex);
  19631. EXPECT_GE(received_messages.size(), 2u);
  19632. if (received_messages.size() >= 2) {
  19633. EXPECT_EQ(received_messages[0], "message1");
  19634. EXPECT_EQ(received_messages[1], "message2");
  19635. }
  19636. }
  19637. // Test: on_event for specific types
  19638. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19639. Client client("localhost", get_port());
  19640. sse::SSEClient sse(client, "/custom-events");
  19641. std::atomic<bool> update_received{false};
  19642. std::atomic<bool> delete_received{false};
  19643. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19644. if (msg.data == "updated") { update_received.store(true); }
  19645. });
  19646. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19647. if (msg.data == "deleted") { delete_received.store(true); }
  19648. });
  19649. sse.set_max_reconnect_attempts(1);
  19650. sse.start_async();
  19651. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19652. sse.stop();
  19653. EXPECT_TRUE(update_received.load());
  19654. EXPECT_TRUE(delete_received.load());
  19655. }
  19656. // Test: on_error callback on connection failure
  19657. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19658. // Connect to a non-existent port
  19659. Client client("localhost", 59999);
  19660. sse::SSEClient sse(client, "/events");
  19661. std::atomic<bool> error_called{false};
  19662. Error received_error = Error::Success;
  19663. sse.on_error([&](Error err) {
  19664. error_called.store(true);
  19665. received_error = err;
  19666. });
  19667. sse.set_reconnect_interval(50);
  19668. sse.set_max_reconnect_attempts(1);
  19669. sse.start_async();
  19670. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19671. sse.stop();
  19672. EXPECT_TRUE(error_called.load());
  19673. EXPECT_NE(received_error, Error::Success);
  19674. }
  19675. // Test: Last-Event-ID header sent on reconnect
  19676. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19677. // Endpoint that sends event with ID
  19678. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19679. res.set_chunked_content_provider(
  19680. "text/event-stream", [](size_t offset, DataSink &sink) {
  19681. if (offset == 0) {
  19682. std::string event = "id: evt-123\ndata: test\n\n";
  19683. sink.write(event.data(), event.size());
  19684. }
  19685. return false;
  19686. });
  19687. });
  19688. Client client("localhost", get_port());
  19689. sse::SSEClient sse(client, "/event-with-id");
  19690. std::atomic<bool> id_received{false};
  19691. sse.on_message([&](const sse::SSEMessage &msg) {
  19692. if (!msg.id.empty()) { id_received.store(true); }
  19693. });
  19694. sse.set_reconnect_interval(100);
  19695. sse.set_max_reconnect_attempts(1);
  19696. sse.start_async();
  19697. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19698. sse.stop();
  19699. EXPECT_TRUE(id_received.load());
  19700. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19701. }
  19702. // Test: Manual stop
  19703. TEST_F(SSEIntegrationTest, ManualStop) {
  19704. // Endpoint that sends one event and stays open briefly
  19705. std::atomic<bool> handler_running{true};
  19706. server_->Get("/stay-open", [&handler_running](const Request &,
  19707. Response &res) {
  19708. res.set_chunked_content_provider(
  19709. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19710. if (offset == 0) {
  19711. std::string event = "data: connected\n\n";
  19712. sink.write(event.data(), event.size());
  19713. }
  19714. // Keep connection open while handler_running is true
  19715. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19716. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19717. }
  19718. return false;
  19719. });
  19720. });
  19721. Client client("localhost", get_port());
  19722. sse::SSEClient sse(client, "/stay-open");
  19723. std::atomic<bool> connected{false};
  19724. sse.on_open([&connected]() { connected.store(true); });
  19725. sse.set_reconnect_interval(100);
  19726. sse.set_max_reconnect_attempts(1);
  19727. sse.start_async();
  19728. // Wait for connection to establish
  19729. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19730. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19731. }
  19732. EXPECT_TRUE(connected.load());
  19733. EXPECT_TRUE(sse.is_connected());
  19734. // Signal handler to stop
  19735. handler_running.store(false);
  19736. // Stop SSE client
  19737. sse.stop();
  19738. EXPECT_FALSE(sse.is_connected());
  19739. }
  19740. // Test: SSEClient with custom headers
  19741. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19742. // Setup a server endpoint that checks for custom header
  19743. std::atomic<bool> header_received{false};
  19744. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19745. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19746. header_received.store(true);
  19747. }
  19748. res.set_chunked_content_provider("text/event-stream",
  19749. [](size_t, DataSink &) { return false; });
  19750. });
  19751. Client client("localhost", get_port());
  19752. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19753. sse::SSEClient sse(client, "/header-check", headers);
  19754. sse.set_max_reconnect_attempts(1);
  19755. sse.start_async();
  19756. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19757. sse.stop();
  19758. EXPECT_TRUE(header_received.load());
  19759. }
  19760. // Test: Reconnect interval configuration
  19761. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19762. Client client("localhost", get_port());
  19763. sse::SSEClient sse(client, "/events");
  19764. auto &result = sse.set_reconnect_interval(500);
  19765. // Builder pattern should return reference to self
  19766. EXPECT_EQ(&result, &sse);
  19767. }
  19768. // Test: Max reconnect attempts
  19769. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19770. // Connect to non-existent port to force reconnects
  19771. Client client("localhost", 59998);
  19772. sse::SSEClient sse(client, "/events");
  19773. std::atomic<int> error_count{0};
  19774. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19775. sse.set_reconnect_interval(50);
  19776. sse.set_max_reconnect_attempts(2);
  19777. auto start = std::chrono::steady_clock::now();
  19778. sse.start(); // Blocking call
  19779. auto end = std::chrono::steady_clock::now();
  19780. // Should have stopped after 2 failed attempts
  19781. EXPECT_GE(error_count.load(), 2);
  19782. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19783. auto duration =
  19784. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19785. #ifdef _WIN32
  19786. // Windows is much slower for socket connection failures
  19787. EXPECT_LT(duration.count(), 7000);
  19788. #else
  19789. EXPECT_LT(duration.count(), 1000);
  19790. #endif
  19791. }
  19792. // Test: Multi-line data in integration
  19793. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19794. // Endpoint with multi-line data
  19795. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19796. res.set_chunked_content_provider(
  19797. "text/event-stream", [](size_t offset, DataSink &sink) {
  19798. if (offset == 0) {
  19799. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19800. sink.write(event.data(), event.size());
  19801. }
  19802. return false;
  19803. });
  19804. });
  19805. Client client("localhost", get_port());
  19806. sse::SSEClient sse(client, "/multiline-data");
  19807. std::string received_data;
  19808. std::mutex data_mutex;
  19809. sse.on_message([&](const sse::SSEMessage &msg) {
  19810. std::lock_guard<std::mutex> lock(data_mutex);
  19811. received_data = msg.data;
  19812. });
  19813. sse.set_reconnect_interval(100);
  19814. sse.set_max_reconnect_attempts(1);
  19815. sse.start_async();
  19816. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19817. sse.stop();
  19818. std::lock_guard<std::mutex> lock(data_mutex);
  19819. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19820. }
  19821. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19822. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19823. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19824. DataSink &sink) {
  19825. if (offset == 0) {
  19826. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19827. sink.write(events.data(), events.size());
  19828. }
  19829. return false;
  19830. });
  19831. });
  19832. Client client("localhost", get_port());
  19833. sse::SSEClient sse(client, "/empty-data-lines");
  19834. std::mutex mutex;
  19835. std::condition_variable cv;
  19836. std::vector<std::string> received;
  19837. sse.on_message([&](const sse::SSEMessage &msg) {
  19838. std::lock_guard<std::mutex> lock(mutex);
  19839. received.push_back(msg.data);
  19840. cv.notify_all();
  19841. });
  19842. sse.set_max_reconnect_attempts(1);
  19843. sse.start_async();
  19844. {
  19845. std::unique_lock<std::mutex> lock(mutex);
  19846. cv.wait_for(lock, std::chrono::seconds(2),
  19847. [&] { return received.size() >= 3; });
  19848. }
  19849. sse.stop();
  19850. ASSERT_GE(received.size(), 3u);
  19851. EXPECT_EQ(received[0], "");
  19852. EXPECT_EQ(received[1], "\nhello");
  19853. EXPECT_EQ(received[2], "");
  19854. }
  19855. // Test: Auto-reconnect after server disconnection
  19856. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19857. std::atomic<int> connection_count{0};
  19858. std::atomic<int> message_count{0};
  19859. // Endpoint that sends one event and closes, forcing reconnect
  19860. server_->Get("/reconnect-test",
  19861. [&connection_count](const Request &, Response &res) {
  19862. connection_count.fetch_add(1);
  19863. res.set_chunked_content_provider(
  19864. "text/event-stream", [](size_t offset, DataSink &sink) {
  19865. if (offset == 0) {
  19866. std::string event = "data: hello\n\n";
  19867. sink.write(event.data(), event.size());
  19868. }
  19869. return false; // Close connection after sending
  19870. });
  19871. });
  19872. Client client("localhost", get_port());
  19873. sse::SSEClient sse(client, "/reconnect-test");
  19874. sse.on_message([&message_count](const sse::SSEMessage &) {
  19875. message_count.fetch_add(1);
  19876. });
  19877. sse.set_reconnect_interval(100);
  19878. sse.set_max_reconnect_attempts(3);
  19879. sse.start_async();
  19880. // Wait long enough for multiple reconnects
  19881. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19882. sse.stop();
  19883. // Should have connected multiple times (initial + reconnects)
  19884. EXPECT_GE(connection_count.load(), 2);
  19885. // Should have received messages from multiple connections
  19886. EXPECT_GE(message_count.load(), 2);
  19887. }
  19888. // Test: A retry field that is not all ASCII digits is ignored
  19889. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19890. std::atomic<int> connection_count{0};
  19891. server_->Get("/bad-retry",
  19892. [&connection_count](const Request &, Response &res) {
  19893. connection_count.fetch_add(1);
  19894. res.set_chunked_content_provider(
  19895. "text/event-stream", [](size_t offset, DataSink &sink) {
  19896. if (offset == 0) {
  19897. std::string event = "retry: -1\ndata: hello\n\n";
  19898. sink.write(event.data(), event.size());
  19899. }
  19900. return false;
  19901. });
  19902. });
  19903. Client client("localhost", get_port());
  19904. sse::SSEClient sse(client, "/bad-retry");
  19905. sse.set_reconnect_interval(10000);
  19906. sse.start_async();
  19907. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19908. sse.stop();
  19909. EXPECT_EQ(connection_count.load(), 1);
  19910. }
  19911. // Test: A retry field of all ASCII digits sets the reconnection time
  19912. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19913. std::mutex mutex;
  19914. std::condition_variable cv;
  19915. std::vector<std::chrono::steady_clock::time_point> connected_at;
  19916. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  19917. {
  19918. std::lock_guard<std::mutex> lock(mutex);
  19919. connected_at.push_back(std::chrono::steady_clock::now());
  19920. cv.notify_all();
  19921. }
  19922. res.set_chunked_content_provider(
  19923. "text/event-stream", [](size_t offset, DataSink &sink) {
  19924. if (offset == 0) {
  19925. std::string event = "retry: 0\ndata: hello\n\n";
  19926. sink.write(event.data(), event.size());
  19927. }
  19928. return false;
  19929. });
  19930. });
  19931. Client client("localhost", get_port());
  19932. sse::SSEClient sse(client, "/zero-retry");
  19933. sse.set_reconnect_interval(10000);
  19934. sse.start_async();
  19935. {
  19936. std::unique_lock<std::mutex> lock(mutex);
  19937. cv.wait_for(lock, std::chrono::seconds(5),
  19938. [&] { return connected_at.size() >= 2; });
  19939. }
  19940. sse.stop();
  19941. // The server-supplied interval is applied, but never below 100ms, so
  19942. // "retry: 0" does not cause a busy reconnect loop
  19943. std::lock_guard<std::mutex> lock(mutex);
  19944. ASSERT_GE(connected_at.size(), 2u);
  19945. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  19946. connected_at[1] - connected_at[0])
  19947. .count();
  19948. EXPECT_GE(interval_ms, 100);
  19949. }
  19950. // Test: Last-Event-ID sent on reconnect
  19951. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19952. std::atomic<int> connection_count{0};
  19953. std::vector<std::string> received_last_event_ids;
  19954. std::mutex id_mutex;
  19955. // Endpoint that checks Last-Event-ID header and sends event with ID
  19956. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19957. int conn = connection_count.fetch_add(1);
  19958. // Capture the Last-Event-ID header from each connection
  19959. {
  19960. std::lock_guard<std::mutex> lock(id_mutex);
  19961. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19962. }
  19963. res.set_chunked_content_provider(
  19964. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19965. if (offset == 0) {
  19966. std::string event =
  19967. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19968. sink.write(event.data(), event.size());
  19969. }
  19970. return false;
  19971. });
  19972. });
  19973. Client client("localhost", get_port());
  19974. sse::SSEClient sse(client, "/reconnect-with-id");
  19975. sse.set_reconnect_interval(100);
  19976. sse.set_max_reconnect_attempts(3);
  19977. sse.start_async();
  19978. // Wait for at least 2 connections
  19979. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19980. sse.stop();
  19981. // Verify behavior
  19982. std::lock_guard<std::mutex> lock(id_mutex);
  19983. EXPECT_GE(received_last_event_ids.size(), 2u);
  19984. // First connection should have no Last-Event-ID
  19985. if (!received_last_event_ids.empty()) {
  19986. EXPECT_EQ(received_last_event_ids[0], "");
  19987. }
  19988. // Second connection should have Last-Event-ID from first connection
  19989. if (received_last_event_ids.size() >= 2) {
  19990. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19991. }
  19992. }
  19993. // Test: set_headers updates headers used on reconnect
  19994. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19995. std::vector<std::string> received_tokens;
  19996. std::mutex token_mutex;
  19997. // Endpoint that captures Authorization header
  19998. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19999. {
  20000. std::lock_guard<std::mutex> lock(token_mutex);
  20001. received_tokens.push_back(req.get_header_value("Authorization"));
  20002. }
  20003. res.set_chunked_content_provider(
  20004. "text/event-stream", [](size_t offset, DataSink &sink) {
  20005. if (offset == 0) {
  20006. std::string event = "data: hello\n\n";
  20007. sink.write(event.data(), event.size());
  20008. }
  20009. return false; // Close connection to trigger reconnect
  20010. });
  20011. });
  20012. Client client("localhost", get_port());
  20013. Headers headers = {{"Authorization", "Bearer old-token"}};
  20014. sse::SSEClient sse(client, "/auth-check", headers);
  20015. // Update headers on each successful connection
  20016. sse.on_open(
  20017. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20018. sse.set_reconnect_interval(100);
  20019. sse.set_max_reconnect_attempts(3);
  20020. sse.start_async();
  20021. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20022. sse.stop();
  20023. std::lock_guard<std::mutex> lock(token_mutex);
  20024. ASSERT_GE(received_tokens.size(), 2u);
  20025. // First connection uses original header
  20026. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20027. // Second connection uses updated header from set_headers
  20028. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20029. }
  20030. // Test: 401 allows reconnection (so on_error can refresh headers)
  20031. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20032. std::atomic<int> connection_count{0};
  20033. // Endpoint: returns 401 on first attempt, 200 on second
  20034. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20035. int conn = connection_count.fetch_add(1);
  20036. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20037. res.status = StatusCode::Unauthorized_401;
  20038. res.set_content("Unauthorized", "text/plain");
  20039. return;
  20040. }
  20041. res.set_chunked_content_provider(
  20042. "text/event-stream", [](size_t offset, DataSink &sink) {
  20043. if (offset == 0) {
  20044. std::string event = "data: authenticated\n\n";
  20045. sink.write(event.data(), event.size());
  20046. }
  20047. return false;
  20048. });
  20049. });
  20050. Client client("localhost", get_port());
  20051. Headers headers = {{"Authorization", "Bearer expired"}};
  20052. sse::SSEClient sse(client, "/auth-retry", headers);
  20053. std::atomic<bool> message_received{false};
  20054. // Refresh token on error
  20055. sse.on_error(
  20056. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20057. sse.on_message([&](const sse::SSEMessage &msg) {
  20058. if (msg.data == "authenticated") { message_received.store(true); }
  20059. });
  20060. sse.set_reconnect_interval(100);
  20061. sse.set_max_reconnect_attempts(3);
  20062. sse.start_async();
  20063. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20064. sse.stop();
  20065. // Should have reconnected after 401 and succeeded with new token
  20066. EXPECT_GE(connection_count.load(), 2);
  20067. EXPECT_TRUE(message_received.load());
  20068. }
  20069. TEST(Issue2318Test, EmptyHostString) {
  20070. {
  20071. httplib::Client cli_empty("", PORT);
  20072. auto res = cli_empty.Get("/");
  20073. ASSERT_FALSE(res);
  20074. EXPECT_EQ(httplib::Error::Connection, res.error());
  20075. }
  20076. {
  20077. httplib::Client cli(" ", PORT);
  20078. auto res = cli.Get("/");
  20079. ASSERT_FALSE(res);
  20080. EXPECT_EQ(httplib::Error::Connection, res.error());
  20081. }
  20082. }
  20083. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20084. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20085. Server svr;
  20086. // Set a small payload limit (1KB)
  20087. svr.set_payload_max_length(1024);
  20088. svr.Post("/test", [&](const Request &req, Response &res) {
  20089. res.set_content("Body size: " + std::to_string(req.body.size()),
  20090. "text/plain");
  20091. });
  20092. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20093. auto se = detail::scope_exit([&] {
  20094. svr.stop();
  20095. listen_thread.join();
  20096. });
  20097. svr.wait_until_ready();
  20098. // Create data that compresses well but exceeds limit when decompressed
  20099. // 8KB of repeated null bytes compresses to a very small size
  20100. std::string original_data(8 * 1024, '\0');
  20101. // Compress the data using gzip
  20102. std::string compressed_data;
  20103. detail::gzip_compressor compressor;
  20104. compressor.compress(original_data.data(), original_data.size(), true,
  20105. [&](const char *data, size_t size) {
  20106. compressed_data.append(data, size);
  20107. return true;
  20108. });
  20109. // Verify compression worked (compressed should be much smaller)
  20110. ASSERT_LT(compressed_data.size(), original_data.size());
  20111. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20112. // Send compressed data with Content-Encoding: gzip
  20113. Client cli(HOST, PORT);
  20114. Headers headers = {{"Content-Encoding", "gzip"}};
  20115. auto res =
  20116. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20117. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20119. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20120. }
  20121. #endif
  20122. // ============================================================================
  20123. // OpenSSL-Specific Tests
  20124. // ============================================================================
  20125. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20126. X509 *readCertificate(const std::string &strFileName) {
  20127. std::ifstream inStream(strFileName);
  20128. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20129. std::istreambuf_iterator<char>());
  20130. if (strCertPEM.empty()) return (nullptr);
  20131. BIO *pbCert = BIO_new(BIO_s_mem());
  20132. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20133. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20134. BIO_free(pbCert);
  20135. return (pCert);
  20136. }
  20137. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20138. std::ifstream inStream(strFileName);
  20139. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20140. std::istreambuf_iterator<char>());
  20141. if (strPrivateKeyPEM.empty()) return (nullptr);
  20142. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20143. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20144. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20145. BIO_free(pbPrivKey);
  20146. return (pPrivateKey);
  20147. }
  20148. TEST(BindServerTest, UpdateCerts) {
  20149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20150. int port = svr.bind_to_any_port("0.0.0.0");
  20151. ASSERT_TRUE(svr.is_valid());
  20152. ASSERT_TRUE(port > 0);
  20153. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20154. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20155. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20156. ASSERT_TRUE(cert != nullptr);
  20157. ASSERT_TRUE(ca_cert != nullptr);
  20158. ASSERT_TRUE(key != nullptr);
  20159. X509_STORE *cert_store = X509_STORE_new();
  20160. X509_STORE_add_cert(cert_store, ca_cert);
  20161. // svr.update_certs(cert, key, cert_store); // deprecated
  20162. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20163. CLIENT_CA_CERT_FILE);
  20164. ASSERT_TRUE(svr.is_valid());
  20165. svr.stop();
  20166. X509_STORE_free(cert_store);
  20167. X509_free(cert);
  20168. X509_free(ca_cert);
  20169. EVP_PKEY_free(key);
  20170. }
  20171. // Test that update_certs() updates client CA list correctly
  20172. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20173. // Start with file-based constructor
  20174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20175. ASSERT_TRUE(svr.is_valid());
  20176. // Initially no client CA list should be set
  20177. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20178. ASSERT_TRUE(ssl_ctx != nullptr);
  20179. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20180. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20181. EXPECT_EQ(0, count_before);
  20182. // Now update with client CA (PEM string)
  20183. std::string cert_pem, key_pem, ca_pem;
  20184. read_file(SERVER_CERT_FILE, cert_pem);
  20185. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20186. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20187. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20188. ASSERT_TRUE(svr.is_valid());
  20189. // Now client CA list should be set
  20190. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20191. ASSERT_TRUE(ca_list_after != nullptr);
  20192. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20193. }
  20194. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20195. // Test that the file-path SSLServer constructor properly sets the client CA
  20196. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20198. ASSERT_TRUE(svr.is_valid());
  20199. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20200. ASSERT_TRUE(ssl_ctx != nullptr);
  20201. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20202. ASSERT_TRUE(ca_list != nullptr);
  20203. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20204. }
  20205. #endif
  20206. // ============================================================================
  20207. // MbedTLS-Specific Tests
  20208. // ============================================================================
  20209. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20210. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20211. using namespace httplib::tls;
  20212. // Track if callback was invoked
  20213. bool callback_invoked = false;
  20214. // The callback receives void* ctx which is actually MbedTlsContext*
  20215. // We can access the mbedtls_ssl_config via the context
  20216. auto setup_callback = [&callback_invoked](void *ctx) {
  20217. callback_invoked = true;
  20218. // Cast to MbedTlsContext* to access the ssl config
  20219. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20220. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20221. // Use static variables to hold certificate data (simplified for test)
  20222. static mbedtls_x509_crt own_cert;
  20223. static mbedtls_pk_context own_key;
  20224. static mbedtls_x509_crt ca_chain;
  20225. static bool initialized = false;
  20226. if (!initialized) {
  20227. mbedtls_x509_crt_init(&own_cert);
  20228. mbedtls_pk_init(&own_key);
  20229. mbedtls_x509_crt_init(&ca_chain);
  20230. // Load server certificate
  20231. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20232. return false;
  20233. }
  20234. // Load server private key.
  20235. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20236. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20237. #if MBEDTLS_VERSION_MAJOR == 3
  20238. ,
  20239. mbedtls_ctr_drbg_random, nullptr
  20240. #endif
  20241. ) != 0) {
  20242. return false;
  20243. }
  20244. // Load CA chain for client verification
  20245. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20246. return false;
  20247. }
  20248. initialized = true;
  20249. }
  20250. // Configure the SSL config
  20251. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20252. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20253. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20254. // Set minimum TLS version using mbedTLS native API
  20255. #if MBEDTLS_VERSION_MAJOR >= 3
  20256. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20257. #else
  20258. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20259. MBEDTLS_SSL_MINOR_VERSION_3);
  20260. #endif
  20261. return true;
  20262. };
  20263. SSLServer svr(setup_callback);
  20264. ASSERT_TRUE(svr.is_valid());
  20265. ASSERT_TRUE(callback_invoked);
  20266. svr.Get("/test", [&](const Request &req, Response &res) {
  20267. res.set_content("test", "text/plain");
  20268. auto cert = req.peer_cert();
  20269. ASSERT_TRUE(static_cast<bool>(cert));
  20270. auto common_name = cert.subject_cn();
  20271. EXPECT_EQ("Common Name", common_name);
  20272. });
  20273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20274. auto se = detail::scope_exit([&] {
  20275. svr.stop();
  20276. t.join();
  20277. ASSERT_FALSE(svr.is_running());
  20278. });
  20279. svr.wait_until_ready();
  20280. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20281. cli.enable_server_certificate_verification(false);
  20282. cli.set_connection_timeout(30);
  20283. auto res = cli.Get("/test");
  20284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20285. ASSERT_EQ(StatusCode::OK_200, res->status);
  20286. }
  20287. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20288. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20289. // keep-alive SSL session, which reads through that config in
  20290. // mbedtls_ssl_close_notify.
  20291. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20292. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20293. ASSERT_TRUE(svr.is_valid());
  20294. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20295. res.set_content("test", "text/plain");
  20296. });
  20297. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20298. auto se = detail::scope_exit([&] {
  20299. svr.stop();
  20300. t.join();
  20301. ASSERT_FALSE(svr.is_running());
  20302. });
  20303. svr.wait_until_ready();
  20304. {
  20305. SSLClient cli(HOST, PORT);
  20306. cli.enable_server_certificate_verification(false);
  20307. cli.set_keep_alive(true);
  20308. auto res = cli.Get("/test");
  20309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20310. ASSERT_EQ(StatusCode::OK_200, res->status);
  20311. // cli is destructed here with the keep-alive SSL session still open.
  20312. }
  20313. }
  20314. #endif
  20315. // WebSocket Tests
  20316. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20317. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20318. // defining the meaning of these bits has been negotiated.
  20319. auto make_frame = [](uint8_t first_byte) {
  20320. std::string frame;
  20321. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20322. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20323. frame += "Hello";
  20324. return frame;
  20325. };
  20326. // RSV1 set (0x40)
  20327. {
  20328. detail::BufferStream strm;
  20329. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20330. ws::Opcode opcode;
  20331. std::string payload;
  20332. bool fin;
  20333. EXPECT_EQ(
  20334. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20335. ws::impl::FrameRead::Fail);
  20336. }
  20337. // RSV2 set (0x20)
  20338. {
  20339. detail::BufferStream strm;
  20340. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20341. ws::Opcode opcode;
  20342. std::string payload;
  20343. bool fin;
  20344. EXPECT_EQ(
  20345. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20346. ws::impl::FrameRead::Fail);
  20347. }
  20348. // RSV3 set (0x10)
  20349. {
  20350. detail::BufferStream strm;
  20351. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20352. ws::Opcode opcode;
  20353. std::string payload;
  20354. bool fin;
  20355. EXPECT_EQ(
  20356. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20357. ws::impl::FrameRead::Fail);
  20358. }
  20359. // No RSV bits set - should succeed
  20360. {
  20361. detail::BufferStream strm;
  20362. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20363. ws::Opcode opcode;
  20364. std::string payload;
  20365. bool fin;
  20366. EXPECT_EQ(
  20367. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20368. ws::impl::FrameRead::Ok);
  20369. EXPECT_EQ(ws::Opcode::Text, opcode);
  20370. EXPECT_EQ("Hello", payload);
  20371. EXPECT_TRUE(fin);
  20372. }
  20373. }
  20374. TEST(WebSocketTest, ControlFrameValidation) {
  20375. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20376. // payload length <= 125.
  20377. // Ping with FIN=0 - must be rejected
  20378. {
  20379. detail::BufferStream strm;
  20380. std::string frame;
  20381. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20382. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20383. strm.write(frame.data(), frame.size());
  20384. ws::Opcode opcode;
  20385. std::string payload;
  20386. bool fin;
  20387. EXPECT_EQ(
  20388. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20389. ws::impl::FrameRead::Fail);
  20390. }
  20391. // Close with FIN=0 - must be rejected
  20392. {
  20393. detail::BufferStream strm;
  20394. std::string frame;
  20395. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20396. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20397. strm.write(frame.data(), frame.size());
  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. // Ping with payload_len=126 (extended length) - must be rejected
  20406. {
  20407. detail::BufferStream strm;
  20408. std::string frame;
  20409. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20410. frame += static_cast<char>(126); // payload_len=126 (>125)
  20411. frame += static_cast<char>(0x00); // extended length high byte
  20412. frame += static_cast<char>(126); // extended length low byte
  20413. frame += std::string(126, 'x');
  20414. strm.write(frame.data(), frame.size());
  20415. ws::Opcode opcode;
  20416. std::string payload;
  20417. bool fin;
  20418. EXPECT_EQ(
  20419. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20420. ws::impl::FrameRead::Fail);
  20421. }
  20422. // Ping with FIN=1 and payload_len=125 - should succeed
  20423. {
  20424. detail::BufferStream strm;
  20425. std::string frame;
  20426. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20427. frame += static_cast<char>(125); // payload_len=125
  20428. frame += std::string(125, 'x');
  20429. strm.write(frame.data(), frame.size());
  20430. ws::Opcode opcode;
  20431. std::string payload;
  20432. bool fin;
  20433. EXPECT_EQ(
  20434. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20435. ws::impl::FrameRead::Ok);
  20436. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20437. EXPECT_EQ(125u, payload.size());
  20438. EXPECT_TRUE(fin);
  20439. }
  20440. }
  20441. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20442. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20443. // length MUST be 0.
  20444. // MSB set - must be rejected
  20445. {
  20446. detail::BufferStream strm;
  20447. std::string frame;
  20448. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20449. frame += static_cast<char>(127); // 64-bit extended length
  20450. frame += static_cast<char>(0x80); // MSB set (invalid)
  20451. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20452. strm.write(frame.data(), frame.size());
  20453. ws::Opcode opcode;
  20454. std::string payload;
  20455. bool fin;
  20456. EXPECT_EQ(
  20457. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20458. ws::impl::FrameRead::Fail);
  20459. }
  20460. // MSB clear - should pass length parsing (will be rejected by max_len,
  20461. // but that's a different check; use a small length to verify)
  20462. {
  20463. detail::BufferStream strm;
  20464. std::string frame;
  20465. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20466. frame += static_cast<char>(127); // 64-bit extended length
  20467. frame += std::string(7, '\0'); // high bytes = 0
  20468. frame += static_cast<char>(0x03); // length = 3
  20469. frame += "abc";
  20470. strm.write(frame.data(), frame.size());
  20471. ws::Opcode opcode;
  20472. std::string payload;
  20473. bool fin;
  20474. EXPECT_EQ(
  20475. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20476. ws::impl::FrameRead::Ok);
  20477. EXPECT_EQ(ws::Opcode::Text, opcode);
  20478. EXPECT_EQ("abc", payload);
  20479. }
  20480. }
  20481. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20482. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20483. // Valid UTF-8
  20484. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20485. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20486. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20487. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20488. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20489. // Invalid UTF-8
  20490. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20491. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20492. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20493. EXPECT_FALSE(
  20494. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20495. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20496. }
  20497. TEST(WebSocketTest, ConnectAndDisconnect) {
  20498. Server svr;
  20499. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20500. std::string msg;
  20501. while (ws.read(msg)) {}
  20502. });
  20503. auto port = svr.bind_to_any_port(HOST);
  20504. std::thread t([&]() { svr.listen_after_bind(); });
  20505. svr.wait_until_ready();
  20506. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20507. auto res = client.connect();
  20508. ASSERT_TRUE(res);
  20509. EXPECT_EQ(Error::Success, res.error());
  20510. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20511. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20512. EXPECT_TRUE(client.is_open());
  20513. client.close();
  20514. EXPECT_FALSE(client.is_open());
  20515. svr.stop();
  20516. t.join();
  20517. }
  20518. TEST(WebSocketTest, ValidURL) {
  20519. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20520. EXPECT_TRUE(ws1.is_valid());
  20521. ws::WebSocketClient ws2("ws://example.com/path");
  20522. EXPECT_TRUE(ws2.is_valid());
  20523. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20524. EXPECT_TRUE(ws3.is_valid());
  20525. #ifdef CPPHTTPLIB_SSL_ENABLED
  20526. ws::WebSocketClient wss1("wss://example.com/path");
  20527. EXPECT_TRUE(wss1.is_valid());
  20528. ws::WebSocketClient wss2("wss://example.com:443/path");
  20529. EXPECT_TRUE(wss2.is_valid());
  20530. #endif
  20531. }
  20532. TEST(WebSocketTest, InvalidURL) {
  20533. // No scheme
  20534. ws::WebSocketClient ws1("localhost:8080/path");
  20535. EXPECT_FALSE(ws1.is_valid());
  20536. // No path
  20537. ws::WebSocketClient ws2("ws://localhost:8080");
  20538. EXPECT_FALSE(ws2.is_valid());
  20539. // Empty string
  20540. ws::WebSocketClient ws3("");
  20541. EXPECT_FALSE(ws3.is_valid());
  20542. // Missing host
  20543. ws::WebSocketClient ws4("ws://:8080/path");
  20544. EXPECT_FALSE(ws4.is_valid());
  20545. // Port number overflow — should not crash
  20546. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20547. EXPECT_FALSE(ws5.is_valid());
  20548. // Port out of range
  20549. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20550. EXPECT_FALSE(ws6.is_valid());
  20551. }
  20552. TEST(WebSocketTest, UnsupportedScheme) {
  20553. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20554. ws::WebSocketClient ws1("http://localhost:8080/path");
  20555. EXPECT_FALSE(ws1.is_valid());
  20556. ws::WebSocketClient ws2("https://localhost:8080/path");
  20557. EXPECT_FALSE(ws2.is_valid());
  20558. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20559. EXPECT_FALSE(ws3.is_valid());
  20560. #else
  20561. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20562. std::invalid_argument);
  20563. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20564. std::invalid_argument);
  20565. #endif
  20566. }
  20567. TEST(WebSocketTest, ConnectWhenInvalid) {
  20568. ws::WebSocketClient ws("not a valid url");
  20569. EXPECT_FALSE(ws.is_valid());
  20570. auto res = ws.connect();
  20571. EXPECT_FALSE(res);
  20572. EXPECT_EQ(Error::Connection, res.error());
  20573. EXPECT_EQ(-1, res.status());
  20574. }
  20575. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20576. // Grab a port that is free, then close it again so nothing listens there
  20577. Server svr;
  20578. auto port = svr.bind_to_any_port(HOST);
  20579. svr.stop();
  20580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20581. auto res = client.connect();
  20582. ASSERT_FALSE(res);
  20583. EXPECT_EQ(Error::Connection, res.error());
  20584. EXPECT_EQ(-1, res.status());
  20585. }
  20586. TEST(WebSocketTest, DefaultPort) {
  20587. ws::WebSocketClient ws1("ws://example.com/path");
  20588. EXPECT_TRUE(ws1.is_valid());
  20589. // ws:// defaults to port 80 (verified by successful parse)
  20590. #ifdef CPPHTTPLIB_SSL_ENABLED
  20591. ws::WebSocketClient ws2("wss://example.com/path");
  20592. EXPECT_TRUE(ws2.is_valid());
  20593. // wss:// defaults to port 443 (verified by successful parse)
  20594. #endif
  20595. }
  20596. TEST(WebSocketTest, IPv6LiteralAddress) {
  20597. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20598. EXPECT_TRUE(ws1.is_valid());
  20599. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20600. EXPECT_TRUE(ws2.is_valid());
  20601. }
  20602. TEST(WebSocketTest, ComplexPath) {
  20603. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20604. EXPECT_TRUE(ws1.is_valid());
  20605. ws::WebSocketClient ws2("ws://localhost:8080/");
  20606. EXPECT_TRUE(ws2.is_valid());
  20607. }
  20608. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20609. Server svr;
  20610. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20611. std::string msg;
  20612. while (ws.read(msg)) {}
  20613. });
  20614. auto port = svr.bind_to_any_port(HOST);
  20615. std::thread t([&]() { svr.listen_after_bind(); });
  20616. svr.wait_until_ready();
  20617. auto another_host = "example.com";
  20618. auto wrong_ip = "192.0.2.1";
  20619. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20620. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20621. ASSERT_TRUE(client.connect());
  20622. EXPECT_TRUE(client.is_open());
  20623. client.close();
  20624. svr.stop();
  20625. t.join();
  20626. }
  20627. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20628. Server svr;
  20629. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20630. std::string msg;
  20631. while (ws.read(msg)) {}
  20632. });
  20633. auto port = svr.bind_to_any_port(HOST);
  20634. std::thread t([&]() { svr.listen_after_bind(); });
  20635. svr.wait_until_ready();
  20636. auto wrong_ip = "192.0.2.1";
  20637. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20638. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20639. client.set_connection_timeout(1);
  20640. client.set_read_timeout(1);
  20641. client.set_write_timeout(1);
  20642. EXPECT_FALSE(client.connect());
  20643. EXPECT_FALSE(client.is_open());
  20644. svr.stop();
  20645. t.join();
  20646. }
  20647. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20648. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20649. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20650. // (RFC 6761) is only a map key and the Host header value.
  20651. auto host = "target.invalid";
  20652. Server svr;
  20653. std::string received_host;
  20654. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20655. received_host = req.get_header_value("Host");
  20656. std::string msg;
  20657. while (ws.read(msg)) {}
  20658. });
  20659. auto port = svr.bind_to_any_port(HOST);
  20660. std::thread t([&]() { svr.listen_after_bind(); });
  20661. // ASSERT_* below returns from the test body, which would leave t joinable
  20662. // and make ~thread call std::terminate.
  20663. auto se = detail::scope_exit([&] {
  20664. svr.stop();
  20665. if (t.joinable()) { t.join(); }
  20666. });
  20667. svr.wait_until_ready();
  20668. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20669. std::to_string(port) + "/ws");
  20670. client.set_hostname_addr_map({{host, HOST}});
  20671. ASSERT_TRUE(client.connect());
  20672. EXPECT_TRUE(client.is_open());
  20673. client.close();
  20674. svr.stop();
  20675. t.join();
  20676. // The mapping only redirects the connection; the identity stays host_.
  20677. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20678. }
  20679. class WebSocketIntegrationTest : public ::testing::Test {
  20680. protected:
  20681. void SetUp() override {
  20682. server_ = httplib::detail::make_unique<Server>();
  20683. setup_server();
  20684. start_server();
  20685. }
  20686. void TearDown() override {
  20687. server_->stop();
  20688. if (server_thread_.joinable()) { server_thread_.join(); }
  20689. }
  20690. void setup_server() {
  20691. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20692. std::string msg;
  20693. ws::ReadResult ret;
  20694. while ((ret = ws.read(msg))) {
  20695. if (ret == ws::Binary) {
  20696. ws.send(msg.data(), msg.size());
  20697. } else {
  20698. ws.send(msg);
  20699. }
  20700. }
  20701. });
  20702. server_->WebSocket("/ws-echo-string",
  20703. [](const Request &, ws::WebSocket &ws) {
  20704. std::string msg;
  20705. while (ws.read(msg)) {
  20706. ws.send("echo: " + msg);
  20707. }
  20708. });
  20709. server_->WebSocket(
  20710. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20711. // Echo back request metadata
  20712. ws.send("path:" + req.path);
  20713. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20714. std::string msg;
  20715. while (ws.read(msg)) {}
  20716. });
  20717. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20718. std::string msg;
  20719. ws.read(msg); // wait for a message
  20720. ws.close();
  20721. });
  20722. server_->WebSocket("/ws-close-status",
  20723. [](const Request &, ws::WebSocket &ws) {
  20724. std::string msg;
  20725. ws.read(msg); // wait for a message
  20726. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20727. });
  20728. server_->WebSocket(
  20729. "/ws-subprotocol",
  20730. [](const Request &, ws::WebSocket &ws) {
  20731. std::string msg;
  20732. while (ws.read(msg)) {
  20733. ws.send(msg);
  20734. }
  20735. },
  20736. [](const std::vector<std::string> &protocols) -> std::string {
  20737. for (const auto &p : protocols) {
  20738. if (p == "graphql-ws") { return p; }
  20739. }
  20740. return "";
  20741. });
  20742. server_->WebSocket(
  20743. "/ws-subprotocol-unoffered",
  20744. [](const Request &, ws::WebSocket &ws) {
  20745. std::string msg;
  20746. while (ws.read(msg)) {
  20747. ws.send(msg);
  20748. }
  20749. },
  20750. [](const std::vector<std::string> &) -> std::string {
  20751. return "admin";
  20752. });
  20753. }
  20754. void start_server() {
  20755. port_ = server_->bind_to_any_port(HOST);
  20756. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20757. server_->wait_until_ready();
  20758. }
  20759. std::unique_ptr<Server> server_;
  20760. std::thread server_thread_;
  20761. int port_ = 0;
  20762. };
  20763. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20764. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20765. "/ws-echo");
  20766. ASSERT_TRUE(client.connect());
  20767. ASSERT_TRUE(client.is_open());
  20768. ASSERT_TRUE(client.send("Hello WebSocket"));
  20769. std::string msg;
  20770. EXPECT_EQ(ws::Text, client.read(msg));
  20771. EXPECT_EQ("Hello WebSocket", msg);
  20772. client.close();
  20773. }
  20774. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20776. "/ws-echo");
  20777. ASSERT_TRUE(client.connect());
  20778. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20779. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20780. std::string msg;
  20781. EXPECT_EQ(ws::Binary, client.read(msg));
  20782. EXPECT_EQ(binary_data, msg);
  20783. client.close();
  20784. }
  20785. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20786. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20787. "/ws-echo");
  20788. ASSERT_TRUE(client.connect());
  20789. for (int i = 0; i < 10; i++) {
  20790. auto text = "message " + std::to_string(i);
  20791. ASSERT_TRUE(client.send(text));
  20792. std::string msg;
  20793. ASSERT_TRUE(client.read(msg));
  20794. EXPECT_EQ(text, msg);
  20795. }
  20796. client.close();
  20797. }
  20798. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20799. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20800. "/ws-close");
  20801. ASSERT_TRUE(client.connect());
  20802. // Send a message to trigger the server to close
  20803. ASSERT_TRUE(client.send("trigger close"));
  20804. // The server will close, so read should return false
  20805. std::string msg;
  20806. EXPECT_FALSE(client.read(msg));
  20807. EXPECT_FALSE(client.is_open());
  20808. }
  20809. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20810. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20811. "/ws-echo");
  20812. ASSERT_TRUE(client.connect());
  20813. // 128KB message
  20814. std::string large_data(128 * 1024, 'X');
  20815. ASSERT_TRUE(client.send(large_data));
  20816. std::string msg;
  20817. ASSERT_TRUE(client.read(msg));
  20818. EXPECT_EQ(large_data, msg);
  20819. client.close();
  20820. }
  20821. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20823. "/ws-echo");
  20824. ASSERT_TRUE(client.connect());
  20825. const int num_threads = 4;
  20826. std::vector<std::thread> threads;
  20827. std::atomic<int> send_count{0};
  20828. for (int t = 0; t < num_threads; t++) {
  20829. threads.emplace_back([&client, &send_count, t]() {
  20830. for (int i = 0; i < 5; i++) {
  20831. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20832. if (client.send(text)) { send_count++; }
  20833. }
  20834. });
  20835. }
  20836. for (auto &th : threads) {
  20837. th.join();
  20838. }
  20839. int received = 0;
  20840. std::string msg;
  20841. while (received < send_count.load()) {
  20842. if (!client.read(msg)) { break; }
  20843. received++;
  20844. }
  20845. EXPECT_EQ(send_count.load(), received);
  20846. client.close();
  20847. }
  20848. TEST_F(WebSocketIntegrationTest, ReadString) {
  20849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20850. "/ws-echo-string");
  20851. ASSERT_TRUE(client.connect());
  20852. ASSERT_TRUE(client.send("hello"));
  20853. std::string msg;
  20854. ASSERT_TRUE(client.read(msg));
  20855. EXPECT_EQ("echo: hello", msg);
  20856. ASSERT_TRUE(client.send("world"));
  20857. ASSERT_TRUE(client.read(msg));
  20858. EXPECT_EQ("echo: world", msg);
  20859. client.close();
  20860. }
  20861. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20862. Headers headers = {{"X-Test-Header", "test-value"}};
  20863. ws::WebSocketClient client(
  20864. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20865. ASSERT_TRUE(client.connect());
  20866. std::string msg;
  20867. ASSERT_TRUE(client.read(msg));
  20868. EXPECT_EQ("path:/ws-request-info", msg);
  20869. ASSERT_TRUE(client.read(msg));
  20870. EXPECT_EQ("header:test-value", msg);
  20871. client.close();
  20872. }
  20873. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20874. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20875. "/ws-echo");
  20876. client.set_read_timeout(1, 0); // 1 second
  20877. ASSERT_TRUE(client.connect());
  20878. // Don't send anything — server echo handler waits for a message, so read()
  20879. // should time out. The connection survives it: nothing was consumed.
  20880. std::string msg;
  20881. EXPECT_EQ(client.read(msg), ws::Timeout);
  20882. EXPECT_TRUE(client.is_open());
  20883. // And it is still usable afterwards.
  20884. EXPECT_TRUE(client.send("after timeout"));
  20885. EXPECT_EQ(client.read(msg), ws::Text);
  20886. EXPECT_EQ(msg, "after timeout");
  20887. }
  20888. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20890. "/ws-echo");
  20891. client.set_read_timeout(1, 0);
  20892. ASSERT_TRUE(client.connect());
  20893. ASSERT_TRUE(client.send("first"));
  20894. std::string msg;
  20895. ASSERT_EQ(client.read(msg), ws::Text);
  20896. ASSERT_EQ(msg, "first");
  20897. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20898. // not be used with a read timeout: it would reprocess the previous message.
  20899. EXPECT_EQ(client.read(msg), ws::Timeout);
  20900. EXPECT_EQ(msg, "first");
  20901. }
  20902. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20903. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20904. "/ws-echo");
  20905. ASSERT_TRUE(client.connect());
  20906. // Setting it once the connection is open reaches the live stream, not just
  20907. // the seed for the next connect().
  20908. client.set_read_timeout(1, 0);
  20909. std::string msg;
  20910. EXPECT_EQ(client.read(msg), ws::Timeout);
  20911. EXPECT_TRUE(client.is_open());
  20912. }
  20913. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20915. "/ws-echo");
  20916. client.set_read_timeout(5, 0);
  20917. ASSERT_TRUE(client.connect());
  20918. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20919. // The server should reject it and close the connection.
  20920. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20921. client.send(oversized);
  20922. // The server's read() should have failed due to payload limit,
  20923. // so our read() should return false (connection closed).
  20924. std::string msg;
  20925. EXPECT_FALSE(client.read(msg));
  20926. }
  20927. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20928. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20929. "/ws-echo");
  20930. client.set_read_timeout(10, 0);
  20931. ASSERT_TRUE(client.connect());
  20932. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20933. // This should succeed.
  20934. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20935. ASSERT_TRUE(client.send(at_limit));
  20936. std::string msg;
  20937. ASSERT_TRUE(client.read(msg));
  20938. EXPECT_EQ(at_limit.size(), msg.size());
  20939. client.close();
  20940. }
  20941. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20943. "/nonexistent");
  20944. auto res = client.connect();
  20945. EXPECT_FALSE(res);
  20946. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20947. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20948. EXPECT_FALSE(client.is_open());
  20949. }
  20950. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20952. "/ws-echo");
  20953. ASSERT_TRUE(client.connect());
  20954. ASSERT_TRUE(client.send(""));
  20955. std::string msg;
  20956. EXPECT_EQ(ws::Text, client.read(msg));
  20957. EXPECT_EQ("", msg);
  20958. client.close();
  20959. }
  20960. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20961. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20962. "/ws-echo");
  20963. // First connection
  20964. ASSERT_TRUE(client.connect());
  20965. ASSERT_TRUE(client.send("first"));
  20966. std::string msg;
  20967. ASSERT_TRUE(client.read(msg));
  20968. EXPECT_EQ("first", msg);
  20969. client.close();
  20970. EXPECT_FALSE(client.is_open());
  20971. // Reconnect using the same client object
  20972. ASSERT_TRUE(client.connect());
  20973. ASSERT_TRUE(client.is_open());
  20974. ASSERT_TRUE(client.send("second"));
  20975. ASSERT_TRUE(client.read(msg));
  20976. EXPECT_EQ("second", msg);
  20977. client.close();
  20978. }
  20979. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20980. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20981. "/ws-close-status");
  20982. ASSERT_TRUE(client.connect());
  20983. // Trigger the server to close with GoingAway status
  20984. ASSERT_TRUE(client.send("trigger"));
  20985. // read() should return false after receiving the close frame
  20986. std::string msg;
  20987. EXPECT_FALSE(client.read(msg));
  20988. EXPECT_FALSE(client.is_open());
  20989. }
  20990. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20991. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20992. "/ws-echo");
  20993. ASSERT_TRUE(client.connect());
  20994. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20995. EXPECT_FALSE(client.is_open());
  20996. }
  20997. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20998. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20999. ws::WebSocketClient client(
  21000. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21001. ASSERT_TRUE(client.connect());
  21002. // Server should have selected graphql-ws
  21003. EXPECT_EQ("graphql-ws", client.subprotocol());
  21004. client.close();
  21005. }
  21006. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21007. Headers headers;
  21008. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21009. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21010. ws::WebSocketClient client(
  21011. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21012. ASSERT_TRUE(client.connect());
  21013. // The offer on the second field line counts too, so graphql-ws is selected
  21014. EXPECT_EQ("graphql-ws", client.subprotocol());
  21015. client.close();
  21016. }
  21017. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21018. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21019. ws::WebSocketClient client(
  21020. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21021. ASSERT_TRUE(client.connect());
  21022. // Server should not have selected any subprotocol
  21023. EXPECT_TRUE(client.subprotocol().empty());
  21024. client.close();
  21025. }
  21026. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21027. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21028. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21029. "/ws-subprotocol-unoffered",
  21030. headers);
  21031. ASSERT_TRUE(client.connect());
  21032. EXPECT_TRUE(client.subprotocol().empty());
  21033. client.close();
  21034. }
  21035. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21036. // Connect without requesting any subprotocol
  21037. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21038. "/ws-subprotocol");
  21039. ASSERT_TRUE(client.connect());
  21040. EXPECT_TRUE(client.subprotocol().empty());
  21041. client.close();
  21042. }
  21043. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21044. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21045. "/ws-echo");
  21046. client.set_tcp_nodelay(true);
  21047. client.set_connection_timeout(3, 0);
  21048. bool socket_options_called = false;
  21049. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21050. ASSERT_TRUE(client.connect());
  21051. ASSERT_TRUE(client.is_open());
  21052. EXPECT_TRUE(socket_options_called);
  21053. ASSERT_TRUE(client.send("hello"));
  21054. std::string msg;
  21055. auto result = client.read(msg);
  21056. EXPECT_EQ(result, ws::ReadResult::Text);
  21057. EXPECT_EQ(msg, "hello");
  21058. client.close();
  21059. }
  21060. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21062. "/ws-echo");
  21063. client.set_connection_timeout(std::chrono::seconds(3));
  21064. client.set_write_timeout(std::chrono::seconds(3));
  21065. // A sub-second remainder exercises the seconds/microseconds split.
  21066. client.set_read_timeout(std::chrono::milliseconds(1500));
  21067. ASSERT_TRUE(client.connect());
  21068. auto start = std::chrono::steady_clock::now();
  21069. std::string msg;
  21070. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21071. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21072. std::chrono::steady_clock::now() - start)
  21073. .count();
  21074. // Above 1s so that dropping the microseconds half of the split fails here.
  21075. // Ignoring the setter altogether would not reach this line at all: a client
  21076. // waits forever by default.
  21077. EXPECT_GE(elapsed, 1400);
  21078. EXPECT_LT(elapsed, 30000);
  21079. }
  21080. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21081. Server svr;
  21082. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21083. if (!req.has_header("Authorization")) {
  21084. res.status = StatusCode::Unauthorized_401;
  21085. res.set_content("Unauthorized", "text/plain");
  21086. return Server::HandlerResponse::Handled;
  21087. }
  21088. return Server::HandlerResponse::Unhandled;
  21089. });
  21090. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21091. std::string msg;
  21092. while (ws.read(msg)) {
  21093. ws.send(msg);
  21094. }
  21095. });
  21096. auto port = svr.bind_to_any_port("localhost");
  21097. std::thread t([&]() { svr.listen_after_bind(); });
  21098. svr.wait_until_ready();
  21099. // Without Authorization header - should be rejected before upgrade
  21100. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21101. EXPECT_FALSE(client1.connect());
  21102. // The rejection is framed like any other HTTP response
  21103. {
  21104. Client cli("localhost", port);
  21105. Headers headers = {{"Upgrade", "websocket"},
  21106. {"Connection", "Upgrade"},
  21107. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21108. {"Sec-WebSocket-Version", "13"}};
  21109. auto res = cli.Get("/ws", headers);
  21110. ASSERT_TRUE(res);
  21111. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21112. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21113. EXPECT_EQ("Unauthorized", res->body);
  21114. }
  21115. // With Authorization header - should succeed
  21116. Headers headers = {{"Authorization", "Bearer token123"}};
  21117. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21118. headers);
  21119. ASSERT_TRUE(client2.connect());
  21120. ASSERT_TRUE(client2.send("hello"));
  21121. std::string msg;
  21122. ASSERT_TRUE(client2.read(msg));
  21123. EXPECT_EQ("hello", msg);
  21124. client2.close();
  21125. svr.stop();
  21126. t.join();
  21127. }
  21128. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21129. Server svr;
  21130. std::atomic<int> pre_request_calls{0};
  21131. std::atomic<bool> route_matched{false};
  21132. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21133. pre_request_calls++;
  21134. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21135. if (req.get_header_value("Authorization") != "Bearer token123") {
  21136. res.status = StatusCode::Unauthorized_401;
  21137. res.set_content("Unauthorized", "text/plain");
  21138. return Server::HandlerResponse::Handled;
  21139. }
  21140. return Server::HandlerResponse::Unhandled;
  21141. });
  21142. std::atomic<bool> handler_called{false};
  21143. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21144. handler_called = true;
  21145. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21146. });
  21147. auto port = svr.bind_to_any_port("localhost");
  21148. std::thread t([&]() { svr.listen_after_bind(); });
  21149. svr.wait_until_ready();
  21150. // Without Authorization header - should be rejected before upgrade
  21151. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21152. "/ws/1");
  21153. EXPECT_FALSE(client1.connect());
  21154. EXPECT_FALSE(handler_called);
  21155. EXPECT_EQ(1, pre_request_calls);
  21156. EXPECT_TRUE(route_matched);
  21157. // The rejection is an ordinary HTTP response, not a protocol switch
  21158. {
  21159. Client cli("localhost", port);
  21160. Headers headers = {{"Upgrade", "websocket"},
  21161. {"Connection", "Upgrade"},
  21162. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21163. {"Sec-WebSocket-Version", "13"}};
  21164. auto res = cli.Get("/ws/1", headers);
  21165. ASSERT_TRUE(res);
  21166. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21167. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21168. EXPECT_EQ("Unauthorized", res->body);
  21169. }
  21170. EXPECT_FALSE(handler_called);
  21171. // With Authorization header - should succeed
  21172. Headers headers = {{"Authorization", "Bearer token123"}};
  21173. ws::WebSocketClient client2(
  21174. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21175. ASSERT_TRUE(client2.connect());
  21176. std::string msg;
  21177. ASSERT_TRUE(client2.read(msg));
  21178. EXPECT_EQ("/ws/:id 2", msg);
  21179. EXPECT_TRUE(handler_called);
  21180. client2.close();
  21181. svr.stop();
  21182. t.join();
  21183. }
  21184. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21185. Server svr;
  21186. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21187. // A read timeout is how a handler gets control back. Without it, a handler
  21188. // parked in read() can never write on the connection it is reading.
  21189. ws.set_read_timeout(std::chrono::milliseconds(100));
  21190. std::string msg;
  21191. while (ws.is_open()) {
  21192. auto r = ws.read(msg);
  21193. if (r == httplib::ws::Timeout) {
  21194. ws.send("tick");
  21195. continue;
  21196. }
  21197. if (r == httplib::ws::Fail) { break; }
  21198. ws.send(msg);
  21199. }
  21200. });
  21201. auto port = svr.bind_to_any_port("localhost");
  21202. std::thread t([&]() { svr.listen_after_bind(); });
  21203. svr.wait_until_ready();
  21204. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21205. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21206. ASSERT_TRUE(client.connect());
  21207. // The client sends nothing, so anything it receives came out of the
  21208. // handler's timeout path.
  21209. std::string msg;
  21210. ASSERT_EQ(client.read(msg), ws::Text);
  21211. EXPECT_EQ("tick", msg);
  21212. client.close();
  21213. svr.stop();
  21214. t.join();
  21215. }
  21216. // Stream::read may return fewer bytes than asked for. This is that contract at
  21217. // its worst -- one byte per call -- which is what a frame header straddling a
  21218. // read buffer's boundary looks like to the frame parser.
  21219. class WsByteAtATimeStream : public Stream {
  21220. public:
  21221. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21222. bool is_readable() const override { return true; }
  21223. bool wait_readable() const override { return true; }
  21224. bool wait_writable() const override { return true; }
  21225. ssize_t read(char *ptr, size_t size) override {
  21226. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21227. *ptr = data_[pos_++];
  21228. return 1;
  21229. }
  21230. ssize_t write(const char *, size_t size) override {
  21231. return static_cast<ssize_t>(size);
  21232. }
  21233. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21234. ip = "127.0.0.1";
  21235. port = 0;
  21236. }
  21237. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21238. ip = "127.0.0.1";
  21239. port = 0;
  21240. }
  21241. socket_t socket() const override { return INVALID_SOCKET; }
  21242. time_t duration() const override { return 0; }
  21243. private:
  21244. std::string data_;
  21245. size_t pos_ = 0;
  21246. };
  21247. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21248. // A 200-byte payload uses the 16-bit extended length, so the header, the
  21249. // length and the mask key are all multi-byte fields here. Each used to be
  21250. // read with a single read() call, which fails as soon as one is split.
  21251. std::string body(200, 'x');
  21252. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21253. std::string frame;
  21254. frame += static_cast<char>(0x81); // FIN + Text
  21255. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21256. frame += static_cast<char>(body.size() >> 8);
  21257. frame += static_cast<char>(body.size() & 0xff);
  21258. for (size_t i = 0; i < 4; i++) {
  21259. frame += static_cast<char>(mask[i]);
  21260. }
  21261. for (size_t i = 0; i < body.size(); i++) {
  21262. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21263. }
  21264. WsByteAtATimeStream strm(frame);
  21265. ws::Opcode opcode;
  21266. std::string payload;
  21267. bool fin = false;
  21268. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21269. /*expect_masked=*/true, 1024),
  21270. ws::impl::FrameRead::Ok);
  21271. EXPECT_TRUE(fin);
  21272. EXPECT_EQ(opcode, ws::Opcode::Text);
  21273. EXPECT_EQ(payload, body);
  21274. }
  21275. TEST(WebSocketTest, QueryStringInHandshake) {
  21276. Server svr;
  21277. std::mutex mtx;
  21278. std::string received_target;
  21279. std::string received_token;
  21280. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21281. {
  21282. std::lock_guard<std::mutex> lock(mtx);
  21283. received_target = req.target;
  21284. if (req.has_param("token")) {
  21285. received_token = req.get_param_value("token");
  21286. }
  21287. }
  21288. std::string msg;
  21289. while (ws.read(msg)) {
  21290. ws.send(msg);
  21291. }
  21292. });
  21293. auto port = svr.bind_to_any_port("localhost");
  21294. std::thread t([&]() { svr.listen_after_bind(); });
  21295. svr.wait_until_ready();
  21296. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21297. "/ws?token=ABC&session=123");
  21298. ASSERT_TRUE(client.connect());
  21299. // Round-trip ensures the handler has run and captured the request.
  21300. ASSERT_TRUE(client.send("hello"));
  21301. std::string msg;
  21302. ASSERT_TRUE(client.read(msg));
  21303. EXPECT_EQ("hello", msg);
  21304. client.close();
  21305. {
  21306. std::lock_guard<std::mutex> lock(mtx);
  21307. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21308. EXPECT_EQ("ABC", received_token);
  21309. }
  21310. svr.stop();
  21311. t.join();
  21312. }
  21313. // Run a handshake against a throwaway server and hand the request the server
  21314. // received back to the caller, so tests can assert on the headers the client
  21315. // actually put on the wire.
  21316. static void capture_websocket_handshake_request(
  21317. const Headers &client_headers,
  21318. std::function<void(const Request &, int port)> verify) {
  21319. Server svr;
  21320. std::mutex mtx;
  21321. Request received;
  21322. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21323. {
  21324. std::lock_guard<std::mutex> lock(mtx);
  21325. received = req;
  21326. }
  21327. std::string msg;
  21328. while (ws.read(msg)) {
  21329. ws.send(msg);
  21330. }
  21331. });
  21332. auto port = svr.bind_to_any_port("localhost");
  21333. std::thread t([&]() { svr.listen_after_bind(); });
  21334. auto se = detail::scope_exit([&] {
  21335. svr.stop();
  21336. t.join();
  21337. });
  21338. svr.wait_until_ready();
  21339. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21340. client_headers);
  21341. ASSERT_TRUE(client.connect());
  21342. ASSERT_TRUE(client.send("hello"));
  21343. std::string msg;
  21344. ASSERT_TRUE(client.read(msg));
  21345. client.close();
  21346. {
  21347. std::lock_guard<std::mutex> lock(mtx);
  21348. verify(received, port);
  21349. }
  21350. }
  21351. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21352. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21353. // Non-default port must be present in the Host header. Default ports
  21354. // (80/443) are omitted; that logic is covered by
  21355. // MakeHostAndPortStringTest.
  21356. EXPECT_EQ("localhost:" + std::to_string(port),
  21357. req.get_header_value("Host"));
  21358. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21359. req.get_header_value("User-Agent"));
  21360. EXPECT_FALSE(req.has_header("Accept"));
  21361. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21362. EXPECT_FALSE(req.has_header("Content-Length"));
  21363. });
  21364. }
  21365. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21366. capture_websocket_handshake_request(
  21367. {{"Host", "example.com"},
  21368. {"User-Agent", "custom-agent"},
  21369. {"X-Custom", "value"}},
  21370. [](const Request &req, int) {
  21371. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21372. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21373. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21374. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21375. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21376. });
  21377. }
  21378. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21379. capture_websocket_handshake_request(
  21380. {{"Upgrade", "bogus"},
  21381. {"Connection", "close"},
  21382. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21383. {"Sec-WebSocket-Version", "8"}},
  21384. [](const Request &req, int) {
  21385. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21386. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21387. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21388. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21389. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21390. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21391. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21392. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21393. req.get_header_value("Sec-WebSocket-Key"));
  21394. });
  21395. }
  21396. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21397. // A header the client refuses to send must abort the handshake before any
  21398. // part of it reaches the wire; a lone request line would otherwise sit in
  21399. // the peer's buffer as a truncated request.
  21400. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21401. ASSERT_NE(INVALID_SOCKET, srv);
  21402. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21403. sockaddr_in addr{};
  21404. addr.sin_family = AF_INET;
  21405. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21406. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21407. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21408. ASSERT_EQ(0, ::listen(srv, 1));
  21409. sockaddr_in bound{};
  21410. socklen_t bound_len = sizeof(bound);
  21411. ASSERT_EQ(
  21412. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21413. auto port = ntohs(bound.sin_port);
  21414. ssize_t received = -1;
  21415. std::thread t([&] {
  21416. // Bound every blocking call so a regression fails the test with a bad
  21417. // value instead of hanging the suite.
  21418. fd_set rfds;
  21419. FD_ZERO(&rfds);
  21420. FD_SET(srv, &rfds);
  21421. timeval tv{5, 0};
  21422. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21423. 0) {
  21424. return;
  21425. }
  21426. sockaddr_in cli_addr{};
  21427. socklen_t cli_len = sizeof(cli_addr);
  21428. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21429. if (cli == INVALID_SOCKET) { return; }
  21430. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21431. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21432. char buf[4096];
  21433. received = ::recv(cli, buf, sizeof(buf), 0);
  21434. });
  21435. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21436. // connect() has already shut the socket down by the time it returns false,
  21437. // so the peer sees EOF without waiting for the client to be destroyed.
  21438. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21439. {{"X-Bad", "a\r\nInjected: 1"}});
  21440. EXPECT_FALSE(client.connect());
  21441. t.join();
  21442. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21443. EXPECT_EQ(0, received);
  21444. }
  21445. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21446. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21447. // contains "upgrade" as a substring is a different token and must not
  21448. // start a WebSocket handshake.
  21449. auto make_request = [](const std::vector<std::string> &connection_values) {
  21450. Request req;
  21451. req.method = "GET";
  21452. req.headers.emplace("Upgrade", "websocket");
  21453. for (const auto &value : connection_values) {
  21454. req.headers.emplace("Connection", value);
  21455. }
  21456. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21457. req.headers.emplace("Sec-WebSocket-Version", "13");
  21458. return req;
  21459. };
  21460. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21461. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21462. EXPECT_TRUE(
  21463. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21464. EXPECT_TRUE(
  21465. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21466. EXPECT_TRUE(
  21467. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21468. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21469. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21470. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21471. EXPECT_FALSE(
  21472. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21473. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21474. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21475. }
  21476. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21477. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21478. // asks recipients to match each protocol-name case-insensitively, and RFC
  21479. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21480. // client naming websocket alongside another protocol, or on a second field
  21481. // line, is offering websocket; a value that merely contains "websocket" as a
  21482. // substring is a different protocol name and is not.
  21483. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21484. Request req;
  21485. req.method = "GET";
  21486. for (const auto &value : upgrade_values) {
  21487. req.headers.emplace("Upgrade", value);
  21488. }
  21489. req.headers.emplace("Connection", "Upgrade");
  21490. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21491. req.headers.emplace("Sec-WebSocket-Version", "13");
  21492. return req;
  21493. };
  21494. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21495. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21496. EXPECT_TRUE(
  21497. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21498. EXPECT_TRUE(
  21499. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21500. EXPECT_TRUE(
  21501. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21502. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21503. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21504. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21505. EXPECT_FALSE(
  21506. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21507. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21508. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21509. }
  21510. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21511. Server svr;
  21512. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21513. auto port = svr.bind_to_any_port("localhost");
  21514. std::thread t([&]() { svr.listen_after_bind(); });
  21515. auto se = detail::scope_exit([&] {
  21516. svr.stop();
  21517. t.join();
  21518. });
  21519. svr.wait_until_ready();
  21520. Headers headers = {{"Upgrade", "websocket"},
  21521. {"Connection", "notupgrade"},
  21522. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21523. {"Sec-WebSocket-Version", "13"}};
  21524. Client cli("localhost", port);
  21525. auto res = cli.Get("/ws", headers);
  21526. // The route exists only as a WebSocket route, so a request that fails the
  21527. // handshake check falls through to ordinary routing.
  21528. ASSERT_TRUE(res);
  21529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21530. }
  21531. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21532. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21533. // Connection value is the only thing left for the client to reject.
  21534. Server svr;
  21535. svr.Get("/ws", [](const Request &req, Response &res) {
  21536. res.status = StatusCode::SwitchingProtocol_101;
  21537. res.set_header("Upgrade", "websocket");
  21538. res.set_header("Connection", "notupgrade");
  21539. res.set_header("Sec-WebSocket-Accept",
  21540. detail::websocket_accept_key(
  21541. req.get_header_value("Sec-WebSocket-Key")));
  21542. });
  21543. auto port = svr.bind_to_any_port("localhost");
  21544. std::thread t([&]() { svr.listen_after_bind(); });
  21545. auto se = detail::scope_exit([&] {
  21546. svr.stop();
  21547. t.join();
  21548. });
  21549. svr.wait_until_ready();
  21550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21551. auto res = client.connect();
  21552. EXPECT_FALSE(res);
  21553. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21554. EXPECT_FALSE(client.is_open());
  21555. }
  21556. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21557. Server svr;
  21558. svr.Get("/ws", [](const Request &req, Response &res) {
  21559. res.status = StatusCode::SwitchingProtocol_101;
  21560. res.set_header("Upgrade", "websocket");
  21561. res.set_header("Connection", "Upgrade");
  21562. res.set_header("Sec-WebSocket-Accept",
  21563. detail::websocket_accept_key(
  21564. req.get_header_value("Sec-WebSocket-Key")));
  21565. res.set_header("Sec-WebSocket-Protocol", "admin");
  21566. });
  21567. auto port = svr.bind_to_any_port("localhost");
  21568. std::thread t([&]() { svr.listen_after_bind(); });
  21569. auto se = detail::scope_exit([&] {
  21570. svr.stop();
  21571. t.join();
  21572. });
  21573. svr.wait_until_ready();
  21574. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21575. // Server selects a subprotocol the client never offered
  21576. {
  21577. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21578. ws::WebSocketClient client(url, headers);
  21579. auto res = client.connect();
  21580. EXPECT_FALSE(res);
  21581. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21582. EXPECT_FALSE(client.is_open());
  21583. EXPECT_TRUE(client.subprotocol().empty());
  21584. }
  21585. // Client offered none but the server named one anyway
  21586. {
  21587. ws::WebSocketClient client(url);
  21588. auto res = client.connect();
  21589. EXPECT_FALSE(res);
  21590. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21591. EXPECT_FALSE(client.is_open());
  21592. EXPECT_TRUE(client.subprotocol().empty());
  21593. }
  21594. }
  21595. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21596. // The socket path doubles as the URL host, so it must not contain '/'.
  21597. const char *shard = getenv("GTEST_SHARD_INDEX");
  21598. const std::string sock_path =
  21599. shard ? std::string("httplib-ws-") + shard + ".sock"
  21600. : std::string("httplib-ws.sock");
  21601. std::remove(sock_path.c_str());
  21602. Server svr;
  21603. std::mutex mtx;
  21604. std::string received_host;
  21605. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21606. {
  21607. std::lock_guard<std::mutex> lock(mtx);
  21608. received_host = req.get_header_value("Host");
  21609. }
  21610. std::string msg;
  21611. while (ws.read(msg)) {
  21612. ws.send(msg);
  21613. }
  21614. });
  21615. svr.set_address_family(AF_UNIX);
  21616. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21617. auto se = detail::scope_exit([&] {
  21618. svr.stop();
  21619. t.join();
  21620. std::remove(sock_path.c_str());
  21621. });
  21622. svr.wait_until_ready();
  21623. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21624. client.set_address_family(AF_UNIX);
  21625. ASSERT_TRUE(client.connect());
  21626. ASSERT_TRUE(client.send("hello"));
  21627. std::string msg;
  21628. ASSERT_TRUE(client.read(msg));
  21629. client.close();
  21630. {
  21631. std::lock_guard<std::mutex> lock(mtx);
  21632. // There is no host:port for a Unix socket, so the same "localhost"
  21633. // placeholder the HTTP client uses is expected.
  21634. EXPECT_EQ("localhost", received_host);
  21635. }
  21636. }
  21637. // Two threads must never parse WebSocket frames from the same stream.
  21638. // close() used to read the peer's Close reply with its own frame read, so it
  21639. // raced a reader thread that was in the middle of a payload: the payload loop
  21640. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21641. // so bytes taken by close() were replaced with bytes from further along the
  21642. // stream. The message kept its length and silently changed content.
  21643. //
  21644. // The raw peer below sends a frame header plus part of the payload, waits for
  21645. // the handler to call close(), and only then sends the rest. Whichever thread
  21646. // would win the race for those bytes, the message must arrive intact, because
  21647. // close() must not touch the stream while read() owns it.
  21648. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21649. #ifndef _WIN32
  21650. signal(SIGPIPE, SIG_IGN);
  21651. #endif
  21652. const size_t payload_len = 120; // fits the 7-bit length field
  21653. const size_t prefix_len = 8;
  21654. const int attempts = 8;
  21655. std::string expected(payload_len, '\0');
  21656. for (size_t i = 0; i < payload_len; i++) {
  21657. expected[i] = static_cast<char>('a' + i % 26);
  21658. }
  21659. std::atomic<bool> peer_stalled{false};
  21660. std::atomic<bool> handler_done{false};
  21661. std::mutex received_mutex;
  21662. std::vector<std::string> received;
  21663. // Bound every wait, so a regression fails the test instead of hanging the
  21664. // suite.
  21665. auto wait_for = [](const std::atomic<bool> &flag) {
  21666. for (int i = 0; i < 500 && !flag; i++) {
  21667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21668. }
  21669. };
  21670. Server svr;
  21671. svr.set_websocket_ping_interval(0);
  21672. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21673. std::thread reader([&]() {
  21674. std::string msg;
  21675. while (ws.read(msg)) {
  21676. std::lock_guard<std::mutex> guard(received_mutex);
  21677. received.push_back(msg);
  21678. }
  21679. });
  21680. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21681. // inside read_websocket_frame() when close() runs.
  21682. wait_for(peer_stalled);
  21683. ws.close();
  21684. reader.join();
  21685. handler_done = true;
  21686. });
  21687. auto port = svr.bind_to_any_port("127.0.0.1");
  21688. std::thread t([&]() { svr.listen_after_bind(); });
  21689. auto se = detail::scope_exit([&] {
  21690. svr.stop();
  21691. t.join();
  21692. });
  21693. svr.wait_until_ready();
  21694. auto send_bytes = [](socket_t s, const std::string &data) {
  21695. #ifdef _WIN32
  21696. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21697. #else
  21698. auto n = ::send(s, data.data(), data.size(), 0);
  21699. #endif
  21700. return n == static_cast<decltype(n)>(data.size());
  21701. };
  21702. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21703. // Every length used here fits the 7-bit length field.
  21704. auto masked_header = [](uint8_t first_byte, size_t len) {
  21705. std::string h;
  21706. h += static_cast<char>(first_byte);
  21707. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21708. h.append(4, '\0'); // mask key
  21709. return h;
  21710. };
  21711. for (int attempt = 0; attempt < attempts; attempt++) {
  21712. peer_stalled = false;
  21713. handler_done = false;
  21714. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21715. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21716. auto se_sock = detail::scope_exit([&] {
  21717. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21718. });
  21719. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21720. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21721. sockaddr_in addr{};
  21722. addr.sin_family = AF_INET;
  21723. addr.sin_port = htons(static_cast<uint16_t>(port));
  21724. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21725. ASSERT_EQ(
  21726. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21727. << "attempt " << attempt;
  21728. ASSERT_TRUE(send_bytes(sock,
  21729. "GET /ws HTTP/1.1\r\n"
  21730. "Host: 127.0.0.1\r\n"
  21731. "Upgrade: websocket\r\n"
  21732. "Connection: Upgrade\r\n"
  21733. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21734. "Sec-WebSocket-Version: 13\r\n"
  21735. "\r\n"))
  21736. << "attempt " << attempt;
  21737. std::string response;
  21738. while (response.find("\r\n\r\n") == std::string::npos) {
  21739. char buf[512];
  21740. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21741. if (n <= 0) { break; }
  21742. response.append(buf, static_cast<size_t>(n));
  21743. }
  21744. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21745. << "attempt " << attempt;
  21746. // Send the header of a Binary message but only the first prefix_len bytes
  21747. // of its payload, leaving the reader thread stalled inside the payload.
  21748. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21749. expected.substr(0, prefix_len)))
  21750. << "attempt " << attempt;
  21751. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21752. peer_stalled = true;
  21753. // Let close() send its Close frame and park in its own read before the
  21754. // rest of the payload arrives, so both threads are waiting for it.
  21755. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21756. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21757. close_frame += static_cast<char>(0x03); // status 1000
  21758. close_frame += static_cast<char>(0xE8);
  21759. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21760. << "attempt " << attempt;
  21761. // Closing the peer releases the reader thread even on the buggy path,
  21762. // where it waits for bytes another thread already consumed.
  21763. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21764. detail::close_socket(sock);
  21765. sock = INVALID_SOCKET;
  21766. wait_for(handler_done);
  21767. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21768. }
  21769. std::lock_guard<std::mutex> guard(received_mutex);
  21770. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21771. << "a message in flight when close() ran was dropped";
  21772. for (size_t i = 0; i < received.size(); i++) {
  21773. EXPECT_EQ(expected, received[i]) << "message " << i;
  21774. }
  21775. }
  21776. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21777. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21778. protected:
  21779. void SetUp() override {
  21780. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21781. SERVER_PRIVATE_KEY_FILE);
  21782. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21783. std::string msg;
  21784. ws::ReadResult ret;
  21785. while ((ret = ws.read(msg))) {
  21786. if (ret == ws::Binary) {
  21787. ws.send(msg.data(), msg.size());
  21788. } else {
  21789. ws.send(msg);
  21790. }
  21791. }
  21792. });
  21793. port_ = server_->bind_to_any_port(HOST);
  21794. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21795. server_->wait_until_ready();
  21796. }
  21797. void TearDown() override {
  21798. server_->stop();
  21799. if (server_thread_.joinable()) { server_thread_.join(); }
  21800. }
  21801. std::unique_ptr<SSLServer> server_;
  21802. std::thread server_thread_;
  21803. int port_ = 0;
  21804. };
  21805. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21806. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21807. "/ws-echo");
  21808. client.enable_server_certificate_verification(false);
  21809. ASSERT_TRUE(client.connect());
  21810. ASSERT_TRUE(client.is_open());
  21811. ASSERT_TRUE(client.send("Hello WSS"));
  21812. std::string msg;
  21813. EXPECT_EQ(ws::Text, client.read(msg));
  21814. EXPECT_EQ("Hello WSS", msg);
  21815. client.close();
  21816. }
  21817. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21818. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21819. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21820. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21821. // client (without calling close() first) is the only path that runs
  21822. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21823. // bug exactly.
  21824. //
  21825. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21826. // when linked against an instrumented libssl; run under Valgrind to catch it
  21827. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21828. // suite (the freed session otherwise stalls on the close handshake) — this test
  21829. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21830. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21831. {
  21832. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21833. "/ws-echo");
  21834. client.enable_server_certificate_verification(false);
  21835. client.set_read_timeout(2, 0);
  21836. client.set_write_timeout(2, 0);
  21837. ASSERT_TRUE(client.connect());
  21838. ASSERT_TRUE(client.is_open());
  21839. ASSERT_TRUE(client.send("still open"));
  21840. // Intentionally do NOT call client.close(): leaving scope runs
  21841. // shutdown_and_close() with the WebSocket still open, which must send the
  21842. // close frame while the TLS session is still alive.
  21843. }
  21844. }
  21845. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21846. // shutdown_and_close() at the start of connect(), reproducing the same
  21847. // use-after-free within the test body rather than at scope exit. The second
  21848. // connect must succeed and echo, proving the close handshake ran over a live
  21849. // session. See the note above about memory-tool requirements.
  21850. TEST_F(WebSocketSSLIntegrationTest,
  21851. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21852. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21853. "/ws-echo");
  21854. client.enable_server_certificate_verification(false);
  21855. client.set_read_timeout(2, 0);
  21856. client.set_write_timeout(2, 0);
  21857. ASSERT_TRUE(client.connect());
  21858. ASSERT_TRUE(client.is_open());
  21859. ASSERT_TRUE(client.send("still open"));
  21860. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21861. // the still-open connection, which must not touch a freed TLS session.
  21862. ASSERT_TRUE(client.connect());
  21863. ASSERT_TRUE(client.is_open());
  21864. ASSERT_TRUE(client.send("after reconnect"));
  21865. std::string msg;
  21866. EXPECT_EQ(ws::Text, client.read(msg));
  21867. EXPECT_EQ("after reconnect", msg);
  21868. client.close();
  21869. }
  21870. #endif
  21871. #ifdef CPPHTTPLIB_SSL_ENABLED
  21872. class WebSocketSSLCATest : public ::testing::Test {
  21873. protected:
  21874. void SetUp() override {
  21875. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21876. SERVER_PRIVATE_KEY_FILE);
  21877. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21878. std::string msg;
  21879. while (ws.read(msg)) {
  21880. ws.send(msg);
  21881. }
  21882. });
  21883. port_ = server_->bind_to_any_port("127.0.0.1");
  21884. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21885. server_->wait_until_ready();
  21886. }
  21887. void TearDown() override {
  21888. server_->stop();
  21889. if (server_thread_.joinable()) { server_thread_.join(); }
  21890. }
  21891. std::string url() const {
  21892. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21893. }
  21894. std::unique_ptr<SSLServer> server_;
  21895. std::thread server_thread_;
  21896. int port_ = 0;
  21897. };
  21898. // A custom CA loaded as PEM verifies the server with full certificate
  21899. // verification enabled
  21900. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21901. ws::WebSocketClient client(url());
  21902. std::string cert;
  21903. read_file(SERVER_CERT2_FILE, cert);
  21904. client.load_ca_cert_store(cert.c_str(), cert.size());
  21905. ASSERT_TRUE(client.connect());
  21906. ASSERT_TRUE(client.send("hello"));
  21907. std::string msg;
  21908. EXPECT_EQ(ws::Text, client.read(msg));
  21909. EXPECT_EQ("hello", msg);
  21910. client.close();
  21911. }
  21912. // A custom CA that does not cover the server must fail verification (the
  21913. // custom CA is exclusive; system certs are not loaded alongside it)
  21914. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21915. ws::WebSocketClient client(url());
  21916. std::string cert;
  21917. read_file(CLIENT_CA_CERT_FILE, cert);
  21918. client.load_ca_cert_store(cert.c_str(), cert.size());
  21919. auto res = client.connect();
  21920. ASSERT_FALSE(res);
  21921. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21922. EXPECT_EQ(-1, res.status());
  21923. EXPECT_NE(0u, res.ssl_backend_error());
  21924. }
  21925. // The same CA as a file path rather than PEM in memory
  21926. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21927. ws::WebSocketClient client(url());
  21928. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21929. ASSERT_TRUE(client.connect());
  21930. ASSERT_TRUE(client.send("hello"));
  21931. std::string msg;
  21932. EXPECT_EQ(ws::Text, client.read(msg));
  21933. EXPECT_EQ("hello", msg);
  21934. client.close();
  21935. }
  21936. // ...and a CA file that does not cover the server still fails, so it is the
  21937. // path above that decides the outcome
  21938. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21939. ws::WebSocketClient client(url());
  21940. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21941. ASSERT_FALSE(client.connect());
  21942. }
  21943. // Regression test: reconnecting with a native custom CA store used to reuse
  21944. // a store handle the previous TLS context had already freed (use-after-free
  21945. // under the OpenSSL backend). The context now lives as long as the client.
  21946. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21947. ws::WebSocketClient client(url());
  21948. std::string cert;
  21949. read_file(SERVER_CERT2_FILE, cert);
  21950. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21951. ASSERT_TRUE(client.connect());
  21952. client.close();
  21953. ASSERT_TRUE(client.connect());
  21954. ASSERT_TRUE(client.send("again"));
  21955. std::string msg;
  21956. EXPECT_EQ(ws::Text, client.read(msg));
  21957. EXPECT_EQ("again", msg);
  21958. client.close();
  21959. }
  21960. // Regression test: a certificate with a trusted chain but no identity match
  21961. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21962. // verification entirely for IP hosts, so this connection succeeded there.
  21963. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21964. // chain verification while the identity check must still fail.
  21965. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21967. ASSERT_TRUE(svr.is_valid());
  21968. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21969. std::string msg;
  21970. while (ws.read(msg)) {
  21971. ws.send(msg);
  21972. }
  21973. });
  21974. auto port = svr.bind_to_any_port("127.0.0.1");
  21975. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21976. auto se = detail::scope_exit([&] {
  21977. svr.stop();
  21978. t.join();
  21979. });
  21980. svr.wait_until_ready();
  21981. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21982. "/echo");
  21983. std::string cert;
  21984. read_file(SERVER_CERT_FILE, cert);
  21985. client.load_ca_cert_store(cert.c_str(), cert.size());
  21986. ASSERT_FALSE(client.connect());
  21987. }
  21988. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21989. // SNI, so nothing binds the host name to the TLS session. These bind the
  21990. // server to "localhost" instead, the only shape that exercises the SNI and
  21991. // hostname-verification path with certificate verification left enabled.
  21992. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21993. protected:
  21994. void Start(const char *cert_file) {
  21995. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21996. SERVER_PRIVATE_KEY_FILE);
  21997. ASSERT_TRUE(server_->is_valid());
  21998. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21999. std::string msg;
  22000. while (ws.read(msg)) {
  22001. ws.send(msg);
  22002. }
  22003. });
  22004. port_ = server_->bind_to_any_port("localhost");
  22005. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22006. server_->wait_until_ready();
  22007. }
  22008. void TearDown() override {
  22009. if (server_) { server_->stop(); }
  22010. if (server_thread_.joinable()) { server_thread_.join(); }
  22011. }
  22012. std::string url() const {
  22013. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22014. }
  22015. std::unique_ptr<SSLServer> server_;
  22016. std::thread server_thread_;
  22017. int port_ = 0;
  22018. };
  22019. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22020. // out and the connection is usable
  22021. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22022. Start(SERVER_CERT2_FILE);
  22023. ws::WebSocketClient client(url());
  22024. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22025. ASSERT_TRUE(client.connect());
  22026. ASSERT_TRUE(client.send("hello"));
  22027. std::string msg;
  22028. EXPECT_EQ(ws::Text, client.read(msg));
  22029. EXPECT_EQ("hello", msg);
  22030. client.close();
  22031. }
  22032. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22033. // while the identity check must still reject "localhost"
  22034. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22035. Start(SERVER_CERT_FILE);
  22036. ws::WebSocketClient client(url());
  22037. client.set_ca_cert_path(SERVER_CERT_FILE);
  22038. auto res = client.connect();
  22039. ASSERT_FALSE(res);
  22040. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22041. EXPECT_EQ(-1, res.status());
  22042. }
  22043. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22044. // disabled: the chain is still checked, only the identity check is skipped
  22045. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22046. Start(SERVER_CERT_FILE);
  22047. ws::WebSocketClient client(url());
  22048. client.set_ca_cert_path(SERVER_CERT_FILE);
  22049. client.enable_server_hostname_verification(false);
  22050. ASSERT_TRUE(client.connect());
  22051. ASSERT_TRUE(client.send("hello"));
  22052. std::string msg;
  22053. EXPECT_EQ(ws::Text, client.read(msg));
  22054. EXPECT_EQ("hello", msg);
  22055. client.close();
  22056. }
  22057. // A CA that did not sign the server certificate fails the chain, even though
  22058. // the name would match
  22059. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22060. Start(SERVER_CERT2_FILE);
  22061. ws::WebSocketClient client(url());
  22062. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22063. ASSERT_FALSE(client.connect());
  22064. }
  22065. // With verification disabled, neither the chain nor the name is checked
  22066. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22067. Start(SERVER_CERT_FILE);
  22068. ws::WebSocketClient client(url());
  22069. client.enable_server_certificate_verification(false);
  22070. ASSERT_TRUE(client.connect());
  22071. ASSERT_TRUE(client.send("hello"));
  22072. std::string msg;
  22073. EXPECT_EQ(ws::Text, client.read(msg));
  22074. EXPECT_EQ("hello", msg);
  22075. client.close();
  22076. }
  22077. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22078. protected:
  22079. void SetUp() override {
  22080. server_ = httplib::detail::make_unique<SSLServer>(
  22081. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22082. ASSERT_TRUE(server_->is_valid());
  22083. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22084. std::string msg;
  22085. while (ws.read(msg)) {
  22086. ws.send(msg);
  22087. }
  22088. });
  22089. port_ = server_->bind_to_any_port("localhost");
  22090. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22091. server_->wait_until_ready();
  22092. }
  22093. void TearDown() override {
  22094. server_->stop();
  22095. if (server_thread_.joinable()) { server_thread_.join(); }
  22096. }
  22097. std::string url() const {
  22098. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22099. }
  22100. void ConnectWithClientCert(const std::string &client_cert_file,
  22101. const std::string &client_private_key_file,
  22102. const char *private_key_password) {
  22103. std::string cert_pem, key_pem;
  22104. read_file(client_cert_file, cert_pem);
  22105. read_file(client_private_key_file, key_pem);
  22106. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22107. key_pem.c_str(), key_pem.size(),
  22108. private_key_password};
  22109. ws::WebSocketClient client(url(), pem);
  22110. ASSERT_TRUE(client.is_valid());
  22111. client.enable_server_certificate_verification(false);
  22112. ASSERT_TRUE(client.connect());
  22113. ASSERT_TRUE(client.send("hello"));
  22114. std::string msg;
  22115. EXPECT_EQ(ws::Text, client.read(msg));
  22116. EXPECT_EQ("hello", msg);
  22117. client.close();
  22118. }
  22119. std::unique_ptr<SSLServer> server_;
  22120. std::thread server_thread_;
  22121. int port_ = 0;
  22122. };
  22123. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22124. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22125. }
  22126. // Control for the tests above: the fixture's server really does require a
  22127. // client certificate, so it is the PEM the constructor installed that decides
  22128. // the outcome.
  22129. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22130. ws::WebSocketClient client(url());
  22131. ASSERT_TRUE(client.is_valid());
  22132. client.enable_server_certificate_verification(false);
  22133. EXPECT_FALSE(client.connect());
  22134. }
  22135. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22136. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22137. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22138. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22139. }
  22140. #endif
  22141. #if !defined(_WIN32)
  22142. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22143. auto secret_dir = std::string("./symlink_test_secret");
  22144. auto served_dir = std::string("./symlink_test_served");
  22145. auto secret_file = secret_dir + "/secret.txt";
  22146. auto symlink_path = served_dir + "/escape";
  22147. // Setup: create directories and files
  22148. mkdir(secret_dir.c_str(), 0755);
  22149. mkdir(served_dir.c_str(), 0755);
  22150. {
  22151. std::ofstream ofs(secret_file);
  22152. ofs << "SECRET_DATA";
  22153. }
  22154. // Create symlink using absolute path so it resolves correctly
  22155. #ifdef PATH_MAX
  22156. char abs_secret[PATH_MAX];
  22157. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22158. #else
  22159. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22160. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22161. ASSERT_NE(nullptr, abs_secret);
  22162. #endif
  22163. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22164. auto se = detail::scope_exit([&] {
  22165. unlink(symlink_path.c_str());
  22166. unlink(secret_file.c_str());
  22167. rmdir(served_dir.c_str());
  22168. rmdir(secret_dir.c_str());
  22169. });
  22170. Server svr;
  22171. svr.set_mount_point("/", served_dir);
  22172. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22173. auto se2 = detail::scope_exit([&] {
  22174. svr.stop();
  22175. listen_thread.join();
  22176. });
  22177. svr.wait_until_ready();
  22178. Client cli("localhost", PORT);
  22179. // Symlink pointing outside base dir should be blocked
  22180. auto res = cli.Get("/escape/secret.txt");
  22181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22182. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22183. }
  22184. #endif
  22185. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22186. // "GET /smuggled" request), reads the first response, and only then sends the
  22187. // embedded request as the body. Returns how many times /smuggled ran.
  22188. //
  22189. // The body is sent AFTER receiving the first response (as in the original
  22190. // PoC) so that the stream_line_reader cannot buffer it together with the
  22191. // headers of the first request.
  22192. static int count_smuggled_requests(const std::string &outer_head,
  22193. std::string &first_response) {
  22194. Server svr;
  22195. svr.set_mount_point("/", "./www");
  22196. std::atomic<int> smuggled_count(0);
  22197. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22198. smuggled_count++;
  22199. res.set_content("oops", "text/plain");
  22200. });
  22201. svr.Post("/post", [&](const Request &req, Response &res) {
  22202. res.set_content(req.body, "text/plain");
  22203. });
  22204. auto port = svr.bind_to_any_port("localhost");
  22205. thread t = thread([&] { svr.listen_after_bind(); });
  22206. auto se = detail::scope_exit([&] {
  22207. svr.stop();
  22208. t.join();
  22209. });
  22210. svr.wait_until_ready();
  22211. auto error = Error::Success;
  22212. auto sock = detail::create_client_socket(
  22213. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22214. /*connection_timeout_sec=*/2, 0,
  22215. /*read_timeout_sec=*/2, 0,
  22216. /*write_timeout_sec=*/2, 0, std::string(), error);
  22217. EXPECT_NE(INVALID_SOCKET, sock);
  22218. if (sock == INVALID_SOCKET) { return -1; }
  22219. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22220. // The "smuggled" request will be sent as the body of the outer request
  22221. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22222. "Host: localhost\r\n"
  22223. "Connection: close\r\n"
  22224. "\r\n";
  22225. auto head = outer_head;
  22226. auto len = std::to_string(smuggled.size());
  22227. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22228. pos = head.find("{len}", pos + len.size())) {
  22229. head.replace(pos, 5, len);
  22230. }
  22231. // Step 1: Send only the outer request headers (no body yet)
  22232. auto sent = send(sock, head.data(), head.size(), 0);
  22233. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22234. // Step 2: Read the first response
  22235. char buf[4096];
  22236. for (;;) {
  22237. auto n = recv(sock, buf, sizeof(buf), 0);
  22238. if (n <= 0) break;
  22239. first_response.append(buf, static_cast<size_t>(n));
  22240. // Stop once we have a complete response (headers + body)
  22241. auto hdr_end = first_response.find("\r\n\r\n");
  22242. if (hdr_end != std::string::npos) {
  22243. // Check for Content-Length to know when the body is complete
  22244. auto cl_pos = first_response.find("Content-Length:");
  22245. if (cl_pos != std::string::npos) {
  22246. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22247. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22248. auto cl = std::stoul(
  22249. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22250. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22251. } else {
  22252. break; // No Content-Length, assume headers-only response
  22253. }
  22254. }
  22255. }
  22256. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22257. // vulnerable server the keep-alive loop reads this as a second request. The
  22258. // server may already have closed the connection, so the result is ignored.
  22259. send(sock, smuggled.data(), smuggled.size(), 0);
  22260. // Half-close so that a server which drained the body sees EOF and closes,
  22261. // instead of the read below waiting for the read timeout.
  22262. #ifdef _WIN32
  22263. ::shutdown(sock, SD_SEND);
  22264. #else
  22265. ::shutdown(sock, SHUT_WR);
  22266. #endif
  22267. // Step 4: Read until the server closes the connection
  22268. for (;;) {
  22269. auto n = recv(sock, buf, sizeof(buf), 0);
  22270. if (n <= 0) break;
  22271. }
  22272. return smuggled_count.load();
  22273. }
  22274. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22275. // A GET request with Content-Length to a static file handler must have its
  22276. // body drained before the keep-alive connection is reused. Otherwise the
  22277. // unread body bytes are interpreted as the next HTTP request.
  22278. std::string first_response;
  22279. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22280. "Host: localhost\r\n"
  22281. "Content-Length: {len}\r\n"
  22282. "\r\n",
  22283. first_response));
  22284. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22285. }
  22286. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22287. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22288. // be answered with 400 and the connection closed. Treating it as "no body"
  22289. // leaves the body to be parsed as the next request.
  22290. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22291. const char *targets[] = {
  22292. "GET /file", // handler that never reads the body
  22293. "GET /not-found", // no handler matches (404)
  22294. "POST /post", // handler that reads the body
  22295. };
  22296. for (auto target : targets) {
  22297. for (auto value : values) {
  22298. std::string first_response;
  22299. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22300. " HTTP/1.1\r\n"
  22301. "Host: localhost\r\n"
  22302. "Content-Length: " +
  22303. value + "\r\n\r\n",
  22304. first_response))
  22305. << target << " with Content-Length: " << value;
  22306. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22307. << target << " with Content-Length: " << value;
  22308. }
  22309. }
  22310. }
  22311. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22312. // A 400 for an unparseable request line leaves the rest of the message
  22313. // unread, so the connection must be closed rather than reused.
  22314. std::string first_response;
  22315. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22316. "Host: localhost\r\n"
  22317. "Content-Length: {len}\r\n"
  22318. "\r\n",
  22319. first_response));
  22320. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22321. }
  22322. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22323. // Same as above for a header block that fails to parse.
  22324. std::string first_response;
  22325. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22326. "Host: localhost\r\n"
  22327. "Bad Header\r\n"
  22328. "Content-Length: {len}\r\n"
  22329. "\r\n",
  22330. first_response));
  22331. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22332. }
  22333. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22334. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22335. // server must not read another request on that connection, even when the
  22336. // request had no body to drain.
  22337. std::string first_response;
  22338. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22339. "Host: localhost\r\n"
  22340. "\r\n",
  22341. first_response));
  22342. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22343. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22344. }
  22345. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22346. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22347. // must be rejected with 400 Bad Request.
  22348. Server svr;
  22349. svr.Post("/test", [&](const Request &, Response &res) {
  22350. res.set_content("ok", "text/plain");
  22351. });
  22352. thread t = thread([&] { svr.listen(HOST, PORT); });
  22353. auto se = detail::scope_exit([&] {
  22354. svr.stop();
  22355. t.join();
  22356. ASSERT_FALSE(svr.is_running());
  22357. });
  22358. svr.wait_until_ready();
  22359. // Exact "chunked"
  22360. {
  22361. auto req = "POST /test HTTP/1.1\r\n"
  22362. "Host: localhost\r\n"
  22363. "Content-Length: 5\r\n"
  22364. "Transfer-Encoding: chunked\r\n"
  22365. "Connection: close\r\n"
  22366. "\r\n"
  22367. "hello";
  22368. std::string response;
  22369. ASSERT_TRUE(send_request(1, req, &response));
  22370. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22371. response.substr(0, response.find("\r\n")));
  22372. }
  22373. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22374. {
  22375. auto req = "POST /test HTTP/1.1\r\n"
  22376. "Host: localhost\r\n"
  22377. "Content-Length: 5\r\n"
  22378. "Transfer-Encoding: gzip, chunked\r\n"
  22379. "Connection: close\r\n"
  22380. "\r\n"
  22381. "hello";
  22382. std::string response;
  22383. ASSERT_TRUE(send_request(1, req, &response));
  22384. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22385. response.substr(0, response.find("\r\n")));
  22386. }
  22387. }
  22388. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22389. Server svr;
  22390. svr.Post("/test", [&](const Request &, Response &res) {
  22391. res.set_content("ok", "text/plain");
  22392. });
  22393. thread t = thread([&] { svr.listen(HOST, PORT); });
  22394. auto se = detail::scope_exit([&] {
  22395. svr.stop();
  22396. t.join();
  22397. ASSERT_FALSE(svr.is_running());
  22398. });
  22399. svr.wait_until_ready();
  22400. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22401. // length cannot be determined, so the server must answer 400 and close
  22402. // rather than treat the request as bodyless and leave the body in the
  22403. // socket for the next request to pick up.
  22404. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22405. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22406. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22407. std::string response;
  22408. ASSERT_TRUE(send_request(1, req, &response));
  22409. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22410. response.substr(0, response.find("\r\n")))
  22411. << transfer_encoding;
  22412. }
  22413. // RFC 9110 5.3: the codings may also be split across several
  22414. // Transfer-Encoding lines, which combine in the order they were received.
  22415. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22416. // just like the single-line "chunked, gzip" above.
  22417. {
  22418. auto req = "POST /test HTTP/1.1\r\n"
  22419. "Host: localhost\r\n"
  22420. "Transfer-Encoding: chunked\r\n"
  22421. "Transfer-Encoding: gzip\r\n"
  22422. "\r\n"
  22423. "0\r\n\r\n";
  22424. std::string response;
  22425. ASSERT_TRUE(send_request(1, req, &response));
  22426. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22427. response.substr(0, response.find("\r\n")));
  22428. }
  22429. // A sequence ending in chunked stays valid.
  22430. auto req = "POST /test HTTP/1.1\r\n"
  22431. "Host: localhost\r\n"
  22432. "Transfer-Encoding: gzip, chunked\r\n"
  22433. "Connection: close\r\n"
  22434. "\r\n"
  22435. "0\r\n\r\n";
  22436. std::string response;
  22437. ASSERT_TRUE(send_request(1, req, &response));
  22438. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22439. // ...including when it is spread over several lines.
  22440. auto split_req = "POST /test HTTP/1.1\r\n"
  22441. "Host: localhost\r\n"
  22442. "Transfer-Encoding: gzip\r\n"
  22443. "Transfer-Encoding: chunked\r\n"
  22444. "Connection: close\r\n"
  22445. "\r\n"
  22446. "0\r\n\r\n";
  22447. std::string split_response;
  22448. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22449. EXPECT_EQ("HTTP/1.1 200 OK",
  22450. split_response.substr(0, split_response.find("\r\n")));
  22451. }
  22452. // Regression for issue #2450: a DELETE without Content-Length on a
  22453. // keep-alive connection must not let the post-response drain consume the
  22454. // next request's bytes.
  22455. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22456. Server svr;
  22457. std::atomic<int> delete_count(0);
  22458. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22459. delete_count++;
  22460. res.status = StatusCode::NoContent_204;
  22461. });
  22462. auto port = svr.bind_to_any_port(HOST);
  22463. thread t = thread([&] { svr.listen_after_bind(); });
  22464. auto se = detail::scope_exit([&] {
  22465. svr.stop();
  22466. t.join();
  22467. });
  22468. svr.wait_until_ready();
  22469. auto error = Error::Success;
  22470. auto sock = detail::create_client_socket(
  22471. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22472. /*connection_timeout_sec=*/2, 0,
  22473. /*read_timeout_sec=*/2, 0,
  22474. /*write_timeout_sec=*/2, 0, std::string(), error);
  22475. ASSERT_NE(INVALID_SOCKET, sock);
  22476. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22477. auto send_request_and_read_response = [&](const std::string &req,
  22478. std::string &out) -> bool {
  22479. auto sent = send(sock, req.data(), req.size(), 0);
  22480. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22481. char buf[4096];
  22482. for (;;) {
  22483. auto n = recv(sock, buf, sizeof(buf), 0);
  22484. if (n <= 0) { return !out.empty(); }
  22485. out.append(buf, static_cast<size_t>(n));
  22486. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22487. }
  22488. };
  22489. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22490. "Host: localhost\r\n"
  22491. "\r\n";
  22492. std::string resp1;
  22493. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22494. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22495. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22496. "Host: localhost\r\n"
  22497. "Connection: close\r\n"
  22498. "\r\n";
  22499. std::string resp2;
  22500. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22501. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22502. EXPECT_EQ(2, delete_count.load());
  22503. }
  22504. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22505. Server svr;
  22506. svr.Post("/ingest", [&](const Request &, Response &res,
  22507. const ContentReader &content_reader) {
  22508. auto consumed = content_reader([](const char *, size_t) { return false; });
  22509. EXPECT_FALSE(consumed);
  22510. res.status = StatusCode::Conflict_409;
  22511. res.set_header("Connection", "close");
  22512. });
  22513. auto port = svr.bind_to_any_port(HOST);
  22514. thread t = thread([&] { svr.listen_after_bind(); });
  22515. auto se = detail::scope_exit([&] {
  22516. svr.stop();
  22517. t.join();
  22518. });
  22519. svr.wait_until_ready();
  22520. auto error = Error::Success;
  22521. auto sock = detail::create_client_socket(
  22522. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22523. /*connection_timeout_sec=*/2, 0,
  22524. /*read_timeout_sec=*/1, 0,
  22525. /*write_timeout_sec=*/2, 0, std::string(), error);
  22526. ASSERT_NE(INVALID_SOCKET, sock);
  22527. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22528. std::string request = "POST /ingest HTTP/1.1\r\n"
  22529. "Host: localhost\r\n"
  22530. "Transfer-Encoding: chunked\r\n"
  22531. "\r\n"
  22532. "4\r\n"
  22533. "data\r\n";
  22534. auto sent = send(sock, request.data(), request.size(), 0);
  22535. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22536. std::string response;
  22537. ssize_t received = 0;
  22538. do {
  22539. char buf[4096];
  22540. received = recv(sock, buf, sizeof(buf), 0);
  22541. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22542. } while (received > 0);
  22543. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22544. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22545. EXPECT_EQ(0, received);
  22546. }
  22547. namespace no_proxy_test {
  22548. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22549. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22550. // calling listen().
  22551. class ScopedServer {
  22552. public:
  22553. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22554. ~ScopedServer() {
  22555. svr_.stop();
  22556. if (th_.joinable()) { th_.join(); }
  22557. }
  22558. Server &svr() { return svr_; }
  22559. int port() const { return port_; }
  22560. void listen() {
  22561. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22562. svr_.wait_until_ready();
  22563. }
  22564. private:
  22565. Server svr_;
  22566. std::thread th_;
  22567. int port_ = 0;
  22568. };
  22569. class ProxyAndTargetServers {
  22570. public:
  22571. ProxyAndTargetServers() {
  22572. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22573. proxy_hits_++;
  22574. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22575. res.set_content("via-proxy", "text/plain");
  22576. });
  22577. target_.Get(".*", [this](const Request &req, Response &res) {
  22578. target_hits_++;
  22579. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22580. res.set_content("direct", "text/plain");
  22581. });
  22582. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22583. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22584. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22585. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22586. proxy_mock_.wait_until_ready();
  22587. target_.wait_until_ready();
  22588. }
  22589. ~ProxyAndTargetServers() {
  22590. proxy_mock_.stop();
  22591. target_.stop();
  22592. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22593. if (target_thread_.joinable()) { target_thread_.join(); }
  22594. }
  22595. Server &proxy_mock() { return proxy_mock_; }
  22596. Server &target() { return target_; }
  22597. int proxy_port() const { return proxy_port_; }
  22598. int target_port() const { return target_port_; }
  22599. int proxy_hits() const { return proxy_hits_.load(); }
  22600. int target_hits() const { return target_hits_.load(); }
  22601. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22602. void reset_counters() {
  22603. proxy_hits_ = 0;
  22604. target_hits_ = 0;
  22605. last_had_proxy_authz_ = false;
  22606. }
  22607. private:
  22608. Server proxy_mock_;
  22609. Server target_;
  22610. std::thread proxy_thread_;
  22611. std::thread target_thread_;
  22612. int proxy_port_ = 0;
  22613. int target_port_ = 0;
  22614. std::atomic<int> proxy_hits_{0};
  22615. std::atomic<int> target_hits_{0};
  22616. std::atomic<bool> last_had_proxy_authz_{false};
  22617. };
  22618. inline std::unique_ptr<Client> make_client(const std::string &host,
  22619. ProxyAndTargetServers &s) {
  22620. auto cli = detail::make_unique<Client>(host, s.target_port());
  22621. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22622. cli->set_proxy("127.0.0.1", s.proxy_port());
  22623. return cli;
  22624. }
  22625. } // namespace no_proxy_test
  22626. using no_proxy_test::make_client;
  22627. using no_proxy_test::ProxyAndTargetServers;
  22628. TEST(NoProxyTest, ExactHostnameBypasses) {
  22629. ProxyAndTargetServers s;
  22630. auto cli = make_client("example.com", s);
  22631. cli->set_no_proxy({"example.com"});
  22632. auto res = cli->Get("/");
  22633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22634. EXPECT_EQ(0, s.proxy_hits());
  22635. EXPECT_EQ(1, s.target_hits());
  22636. }
  22637. TEST(NoProxyTest, SubdomainBypasses) {
  22638. ProxyAndTargetServers s;
  22639. auto cli = make_client("foo.example.com", s);
  22640. cli->set_no_proxy({"example.com"});
  22641. auto res = cli->Get("/");
  22642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22643. EXPECT_EQ(0, s.proxy_hits());
  22644. EXPECT_EQ(1, s.target_hits());
  22645. }
  22646. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22647. // Regression guard: "evilexample.com" must not be considered a subdomain
  22648. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22649. // check would let traffic bypass the proxy and leak credentials direct
  22650. // to the attacker host.
  22651. ProxyAndTargetServers s;
  22652. auto cli = make_client("evilexample.com", s);
  22653. cli->set_no_proxy({"example.com"});
  22654. auto res = cli->Get("/");
  22655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22656. EXPECT_GE(s.proxy_hits(), 1);
  22657. EXPECT_EQ(0, s.target_hits());
  22658. }
  22659. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22660. ProxyAndTargetServers s;
  22661. auto cli = make_client("example.com.evil.com", s);
  22662. cli->set_no_proxy({"example.com"});
  22663. auto res = cli->Get("/");
  22664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22665. EXPECT_GE(s.proxy_hits(), 1);
  22666. EXPECT_EQ(0, s.target_hits());
  22667. }
  22668. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22669. ProxyAndTargetServers s;
  22670. auto cli = make_client("example.com", s);
  22671. cli->set_no_proxy({".example.com"});
  22672. auto res = cli->Get("/");
  22673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22674. EXPECT_EQ(0, s.proxy_hits());
  22675. EXPECT_EQ(1, s.target_hits());
  22676. }
  22677. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22678. ProxyAndTargetServers s;
  22679. auto cli = make_client("Example.COM", s);
  22680. cli->set_no_proxy({"EXAMPLE.com"});
  22681. auto res = cli->Get("/");
  22682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22683. EXPECT_EQ(0, s.proxy_hits());
  22684. EXPECT_EQ(1, s.target_hits());
  22685. }
  22686. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22687. ProxyAndTargetServers s;
  22688. auto cli = make_client("example.com.", s);
  22689. cli->set_no_proxy({"example.com"});
  22690. auto res = cli->Get("/");
  22691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22692. EXPECT_EQ(0, s.proxy_hits());
  22693. EXPECT_EQ(1, s.target_hits());
  22694. }
  22695. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22696. // Trailing dots must be normalized on BOTH sides — host and entry.
  22697. // An implementation that only strips the host-side trailing dot would
  22698. // fail to match host "example.com" against entry "example.com." because
  22699. // a literal substring search would compare 11 chars against 12.
  22700. ProxyAndTargetServers s;
  22701. auto cli = make_client("example.com", s);
  22702. cli->set_no_proxy({"example.com."});
  22703. auto res = cli->Get("/");
  22704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22705. EXPECT_EQ(0, s.proxy_hits());
  22706. EXPECT_EQ(1, s.target_hits());
  22707. }
  22708. TEST(NoProxyTest, WildcardBypassesEverything) {
  22709. ProxyAndTargetServers s;
  22710. auto cli = make_client("anything.invalid.test", s);
  22711. cli->set_no_proxy({"*"});
  22712. auto res = cli->Get("/");
  22713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22714. EXPECT_EQ(0, s.proxy_hits());
  22715. EXPECT_EQ(1, s.target_hits());
  22716. }
  22717. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22718. ProxyAndTargetServers s;
  22719. Client cli("127.0.0.1", s.target_port());
  22720. cli.set_proxy("127.0.0.1", s.proxy_port());
  22721. cli.set_no_proxy({"127.0.0.1"});
  22722. auto res = cli.Get("/");
  22723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22724. EXPECT_EQ(0, s.proxy_hits());
  22725. EXPECT_EQ(1, s.target_hits());
  22726. }
  22727. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22728. ProxyAndTargetServers s;
  22729. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22730. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22731. cli.set_proxy("127.0.0.1", s.proxy_port());
  22732. cli.set_no_proxy({"::1"});
  22733. auto res = cli.Get("/");
  22734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22735. EXPECT_EQ(0, s.proxy_hits());
  22736. EXPECT_EQ(1, s.target_hits());
  22737. }
  22738. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22739. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22740. // must still be recognized as IPv6 for CIDR matching. Implementations
  22741. // that detect IPv6 only when the host begins with '[' would parse the
  22742. // host as a hostname and miss the match.
  22743. ProxyAndTargetServers s;
  22744. Client cli("fe80::1", s.target_port());
  22745. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22746. cli.set_proxy("127.0.0.1", s.proxy_port());
  22747. cli.set_no_proxy({"fe80::/10"});
  22748. auto res = cli.Get("/");
  22749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22750. EXPECT_EQ(0, s.proxy_hits());
  22751. EXPECT_EQ(1, s.target_hits());
  22752. }
  22753. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22754. ProxyAndTargetServers s;
  22755. Client cli("::1", s.target_port());
  22756. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22757. cli.set_proxy("127.0.0.1", s.proxy_port());
  22758. cli.set_no_proxy({"[::1]"});
  22759. auto res = cli.Get("/");
  22760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22761. EXPECT_EQ(0, s.proxy_hits());
  22762. EXPECT_EQ(1, s.target_hits());
  22763. }
  22764. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22765. ProxyAndTargetServers s;
  22766. Client cli("fe80::1", s.target_port());
  22767. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22768. cli.set_proxy("127.0.0.1", s.proxy_port());
  22769. cli.set_no_proxy({"[fe80::]/10"});
  22770. auto res = cli.Get("/");
  22771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22772. EXPECT_EQ(0, s.proxy_hits());
  22773. EXPECT_EQ(1, s.target_hits());
  22774. }
  22775. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22776. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22777. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22778. // tricks via address-family conversion.
  22779. ProxyAndTargetServers s;
  22780. Client cli("::ffff:127.0.0.1", s.target_port());
  22781. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22782. cli.set_proxy("127.0.0.1", s.proxy_port());
  22783. cli.set_no_proxy({"127.0.0.1"});
  22784. auto res = cli.Get("/");
  22785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22786. EXPECT_GE(s.proxy_hits(), 1);
  22787. EXPECT_EQ(0, s.target_hits());
  22788. }
  22789. TEST(NoProxyTest, IPv4CidrMatch) {
  22790. ProxyAndTargetServers s;
  22791. Client cli("127.0.0.1", s.target_port());
  22792. cli.set_proxy("127.0.0.1", s.proxy_port());
  22793. cli.set_no_proxy({"127.0.0.0/8"});
  22794. auto res = cli.Get("/");
  22795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22796. EXPECT_EQ(0, s.proxy_hits());
  22797. EXPECT_EQ(1, s.target_hits());
  22798. }
  22799. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22800. ProxyAndTargetServers s;
  22801. Client cli("127.0.0.1", s.target_port());
  22802. cli.set_proxy("127.0.0.1", s.proxy_port());
  22803. cli.set_no_proxy({"10.0.0.0/8"});
  22804. auto res = cli.Get("/");
  22805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22806. EXPECT_GE(s.proxy_hits(), 1);
  22807. EXPECT_EQ(0, s.target_hits());
  22808. }
  22809. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22810. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22811. // IPv4 target matches.
  22812. ProxyAndTargetServers s;
  22813. Client cli("127.0.0.1", s.target_port());
  22814. cli.set_proxy("127.0.0.1", s.proxy_port());
  22815. cli.set_no_proxy({"0.0.0.0/0"});
  22816. auto res = cli.Get("/");
  22817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22818. EXPECT_EQ(0, s.proxy_hits());
  22819. EXPECT_EQ(1, s.target_hits());
  22820. }
  22821. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22822. ProxyAndTargetServers s;
  22823. Client cli("127.0.0.1", s.target_port());
  22824. cli.set_proxy("127.0.0.1", s.proxy_port());
  22825. cli.set_no_proxy({"127.0.0.1"});
  22826. auto res = cli.Get("/");
  22827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22828. EXPECT_EQ(0, s.proxy_hits());
  22829. EXPECT_EQ(1, s.target_hits());
  22830. }
  22831. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22832. ProxyAndTargetServers s;
  22833. Client cli("127.0.0.1", s.target_port());
  22834. cli.set_proxy("127.0.0.1", s.proxy_port());
  22835. cli.set_no_proxy({"127.0.0.0/33"});
  22836. auto res = cli.Get("/");
  22837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22838. EXPECT_GE(s.proxy_hits(), 1);
  22839. EXPECT_EQ(0, s.target_hits());
  22840. }
  22841. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22842. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22843. ProxyAndTargetServers s;
  22844. Client cli("127.0.0.1", s.target_port());
  22845. cli.set_proxy("127.0.0.1", s.proxy_port());
  22846. cli.set_no_proxy({"127.0.0.1/"});
  22847. auto res = cli.Get("/");
  22848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22849. EXPECT_GE(s.proxy_hits(), 1);
  22850. EXPECT_EQ(0, s.target_hits());
  22851. }
  22852. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22853. ProxyAndTargetServers s;
  22854. auto cli = make_client("internal.corp", s);
  22855. cli->set_proxy_basic_auth("u", "p");
  22856. cli->set_no_proxy({"internal.corp"});
  22857. auto res = cli->Get("/");
  22858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22859. EXPECT_EQ(1, s.target_hits());
  22860. EXPECT_EQ(0, s.proxy_hits());
  22861. EXPECT_FALSE(s.last_had_proxy_authz())
  22862. << "Proxy-Authorization must not be sent direct to the target";
  22863. }
  22864. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22865. ProxyAndTargetServers s;
  22866. auto cli = make_client("public.example", s);
  22867. cli->set_proxy_basic_auth("u", "p");
  22868. cli->set_no_proxy({"internal.corp"}); // does not match
  22869. auto res = cli->Get("/");
  22870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22871. EXPECT_GE(s.proxy_hits(), 1);
  22872. EXPECT_TRUE(s.last_had_proxy_authz());
  22873. }
  22874. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  22875. std::atomic<int> hits{0};
  22876. std::atomic<int> hits_with_authz{0};
  22877. no_proxy_test::ScopedServer proxy_mock;
  22878. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22879. hits++;
  22880. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  22881. if (req.target.find("/redir") != std::string::npos) {
  22882. res.set_redirect("http://other.example/landed");
  22883. } else {
  22884. res.set_content("via-proxy", "text/plain");
  22885. }
  22886. });
  22887. proxy_mock.listen();
  22888. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  22889. hits = 0;
  22890. hits_with_authz = 0;
  22891. Client cli("public.example", 80);
  22892. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22893. cli.set_proxy_basic_auth(c.first, c.second);
  22894. cli.set_follow_location(true);
  22895. // The redirect to another host goes through the proxy as well
  22896. auto res = cli.Get("/redir");
  22897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22898. EXPECT_EQ(2, hits.load());
  22899. EXPECT_EQ(2, hits_with_authz.load());
  22900. }
  22901. }
  22902. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22903. ProxyAndTargetServers s;
  22904. auto cli = make_client("anything.test", s);
  22905. auto res = cli->Get("/");
  22906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22907. EXPECT_GE(s.proxy_hits(), 1);
  22908. EXPECT_EQ(0, s.target_hits());
  22909. }
  22910. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22911. ProxyAndTargetServers s;
  22912. auto cli = make_client("example.com", s);
  22913. cli->set_no_proxy({"example.com:8080"});
  22914. auto res = cli->Get("/");
  22915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22916. EXPECT_GE(s.proxy_hits(), 1);
  22917. EXPECT_EQ(0, s.target_hits());
  22918. }
  22919. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22920. ProxyAndTargetServers s;
  22921. auto cli = make_client("anything.test", s);
  22922. cli->set_no_proxy({"", " ", "\t"});
  22923. auto res = cli->Get("/");
  22924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22925. EXPECT_GE(s.proxy_hits(), 1);
  22926. EXPECT_EQ(0, s.target_hits());
  22927. }
  22928. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22929. // An entry with leading/trailing whitespace must still match — env-style
  22930. // values are commonly pasted with stray spaces and an implementation
  22931. // that feeds the raw token directly to inet_pton would fail to match
  22932. // valid CIDRs because of the spaces.
  22933. ProxyAndTargetServers s;
  22934. Client cli("127.0.0.1", s.target_port());
  22935. cli.set_proxy("127.0.0.1", s.proxy_port());
  22936. cli.set_no_proxy({" 127.0.0.0/8 "});
  22937. auto res = cli.Get("/");
  22938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22939. EXPECT_EQ(0, s.proxy_hits());
  22940. EXPECT_EQ(1, s.target_hits());
  22941. }
  22942. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22943. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22944. // go direct and must NOT carry Proxy-Authorization.
  22945. std::atomic<int> proxy_hits{0};
  22946. std::atomic<int> target_hits{0};
  22947. std::atomic<bool> target_saw_authz{false};
  22948. no_proxy_test::ScopedServer proxy_mock, target;
  22949. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22950. proxy_hits++;
  22951. res.status = 302;
  22952. res.set_header("Location", "http://127.0.0.1:" +
  22953. std::to_string(target.port()) + "/landed");
  22954. });
  22955. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22956. target_hits++;
  22957. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22958. res.set_content("direct", "text/plain");
  22959. });
  22960. proxy_mock.listen();
  22961. target.listen();
  22962. Client cli("public.example", target.port());
  22963. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22964. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22965. cli.set_proxy_basic_auth("u", "p");
  22966. cli.set_no_proxy({"127.0.0.1"});
  22967. cli.set_follow_location(true);
  22968. auto res = cli.Get("/redir");
  22969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22970. EXPECT_GE(proxy_hits.load(), 1);
  22971. EXPECT_GE(target_hits.load(), 1);
  22972. EXPECT_FALSE(target_saw_authz.load());
  22973. }
  22974. #ifdef CPPHTTPLIB_SSL_ENABLED
  22975. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22976. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22977. // proxy creds would be sent to the (possibly hostile) origin.
  22978. std::atomic<int> target_hits{0};
  22979. std::atomic<bool> target_saw_proxy_authz{false};
  22980. no_proxy_test::ScopedServer target;
  22981. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22982. target_hits++;
  22983. if (req.has_header("Proxy-Authorization")) {
  22984. target_saw_proxy_authz = true;
  22985. }
  22986. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22987. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22988. "nonce=\"abc\", algorithm=MD5");
  22989. });
  22990. target.listen();
  22991. // The proxy address is set to the target's port: the bypass MUST kick in;
  22992. // if it doesn't, the test still routes "via proxy" to the same server and
  22993. // the Proxy-Authorization assertion below catches the leak.
  22994. Client cli("evil.example", target.port());
  22995. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22996. cli.set_proxy("127.0.0.1", target.port());
  22997. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22998. cli.set_no_proxy({"evil.example"});
  22999. auto res = cli.Get("/x");
  23000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23001. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23002. EXPECT_EQ(1, target_hits.load());
  23003. EXPECT_FALSE(target_saw_proxy_authz.load());
  23004. }
  23005. #endif
  23006. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23007. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23008. std::atomic<int> proxy_hits{0};
  23009. std::atomic<int> bypass_hits{0};
  23010. std::atomic<bool> proxy_saw_c_url{false};
  23011. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23012. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23013. proxy_hits++;
  23014. if (req.path.find("/start") != std::string::npos) {
  23015. res.status = 302;
  23016. res.set_header("Location", "http://127.0.0.1:" +
  23017. std::to_string(bypass_server.port()) +
  23018. "/middle");
  23019. return;
  23020. }
  23021. if (req.path.find("/end") != std::string::npos) {
  23022. proxy_saw_c_url = true;
  23023. res.set_content("c-via-proxy", "text/plain");
  23024. return;
  23025. }
  23026. res.set_content("unexpected", "text/plain");
  23027. });
  23028. // public.example's "advertised" port is arbitrary (the request never lands
  23029. // there — it goes through the proxy), but use a dynamic value to stay
  23030. // friendly with sharded parallel runs.
  23031. int public_port = bypass_server.port();
  23032. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23033. bypass_hits++;
  23034. res.status = 302;
  23035. res.set_header("Location", "http://public.example:" +
  23036. std::to_string(public_port) + "/end");
  23037. });
  23038. proxy_mock.listen();
  23039. bypass_server.listen();
  23040. Client cli("public.example", public_port);
  23041. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23042. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23043. cli.set_no_proxy({"127.0.0.1"});
  23044. cli.set_follow_location(true);
  23045. auto res = cli.Get("/start");
  23046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23047. EXPECT_EQ(StatusCode::OK_200, res->status);
  23048. EXPECT_EQ("c-via-proxy", res->body);
  23049. EXPECT_GE(proxy_hits.load(), 2);
  23050. EXPECT_GE(bypass_hits.load(), 1);
  23051. EXPECT_TRUE(proxy_saw_c_url.load());
  23052. }
  23053. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23054. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23055. // request reconnects to the correct endpoint.
  23056. std::atomic<int> proxy_hits{0};
  23057. std::atomic<int> target_hits{0};
  23058. no_proxy_test::ScopedServer proxy_mock, target;
  23059. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23060. proxy_hits++;
  23061. res.set_content("via-proxy", "text/plain");
  23062. });
  23063. target.svr().Get(".*", [&](const Request &, Response &res) {
  23064. target_hits++;
  23065. res.set_content("direct", "text/plain");
  23066. });
  23067. proxy_mock.listen();
  23068. target.listen();
  23069. Client cli("public.example", target.port());
  23070. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23071. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23072. cli.set_keep_alive(true);
  23073. auto res1 = cli.Get("/a");
  23074. ASSERT_TRUE(res1);
  23075. EXPECT_EQ("via-proxy", res1->body);
  23076. EXPECT_EQ(1, proxy_hits.load());
  23077. EXPECT_EQ(0, target_hits.load());
  23078. cli.set_no_proxy({"public.example"});
  23079. auto res2 = cli.Get("/b");
  23080. ASSERT_TRUE(res2);
  23081. EXPECT_EQ("direct", res2->body);
  23082. EXPECT_EQ(1, proxy_hits.load());
  23083. EXPECT_EQ(1, target_hits.load());
  23084. }
  23085. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23086. namespace proxy_tunnel_test {
  23087. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23088. class ScopedSSLServer {
  23089. public:
  23090. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23091. port_ = svr_.bind_to_any_port("127.0.0.1");
  23092. }
  23093. ~ScopedSSLServer() {
  23094. svr_.stop();
  23095. if (th_.joinable()) { th_.join(); }
  23096. }
  23097. SSLServer &svr() { return svr_; }
  23098. int port() const { return port_; }
  23099. void listen() {
  23100. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23101. svr_.wait_until_ready();
  23102. }
  23103. private:
  23104. SSLServer svr_;
  23105. std::thread th_;
  23106. int port_ = 0;
  23107. };
  23108. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23109. class ScopedConnectProxy {
  23110. public:
  23111. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23112. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23113. if (listen_fd_ < 0) { return; }
  23114. int yes = 1;
  23115. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23116. sockaddr_in a{};
  23117. a.sin_family = AF_INET;
  23118. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23119. a.sin_port = 0;
  23120. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23121. return;
  23122. }
  23123. socklen_t alen = sizeof(a);
  23124. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23125. 0) {
  23126. return;
  23127. }
  23128. port_ = ntohs(a.sin_port);
  23129. if (::listen(listen_fd_, 1) != 0) { return; }
  23130. th_ = std::thread([this] { run(); });
  23131. }
  23132. ~ScopedConnectProxy() {
  23133. stop_ = true;
  23134. if (listen_fd_ >= 0) {
  23135. ::shutdown(listen_fd_, SHUT_RDWR);
  23136. ::close(listen_fd_);
  23137. }
  23138. if (th_.joinable()) { th_.join(); }
  23139. }
  23140. int port() const { return port_; }
  23141. int connect_hits() const { return connect_hits_.load(); }
  23142. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23143. std::string connect_request() const {
  23144. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23145. return connect_request_;
  23146. }
  23147. private:
  23148. void run() {
  23149. while (!stop_.load()) {
  23150. fd_set rfds;
  23151. FD_ZERO(&rfds);
  23152. FD_SET(listen_fd_, &rfds);
  23153. timeval tv{0, 100 * 1000};
  23154. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23155. if (sel <= 0) { continue; }
  23156. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23157. if (client_fd < 0) { continue; }
  23158. std::string req;
  23159. char buf[2048];
  23160. while (req.find("\r\n\r\n") == std::string::npos) {
  23161. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23162. if (n <= 0) { break; }
  23163. req.append(buf, static_cast<size_t>(n));
  23164. }
  23165. if (req.compare(0, 7, "CONNECT") != 0) {
  23166. ::close(client_fd);
  23167. continue;
  23168. }
  23169. connect_hits_++;
  23170. {
  23171. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23172. connect_request_ = req;
  23173. }
  23174. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23175. ::send(client_fd, ok, std::strlen(ok), 0);
  23176. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23177. sockaddr_in o{};
  23178. o.sin_family = AF_INET;
  23179. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23180. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23181. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23182. 0) {
  23183. ::close(client_fd);
  23184. ::close(origin_fd);
  23185. continue;
  23186. }
  23187. auto forward = [](int from, int to) {
  23188. char b[8192];
  23189. for (;;) {
  23190. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23191. if (n <= 0) { break; }
  23192. ssize_t off = 0;
  23193. while (off < n) {
  23194. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23195. if (s <= 0) {
  23196. off = n;
  23197. break;
  23198. }
  23199. off += s;
  23200. }
  23201. }
  23202. ::shutdown(to, SHUT_WR);
  23203. };
  23204. std::thread t1([&] { forward(client_fd, origin_fd); });
  23205. std::thread t2([&] { forward(origin_fd, client_fd); });
  23206. t1.join();
  23207. t2.join();
  23208. ::close(client_fd);
  23209. ::close(origin_fd);
  23210. }
  23211. }
  23212. int forward_port_ = -1;
  23213. int listen_fd_ = -1;
  23214. int port_ = 0;
  23215. std::thread th_;
  23216. std::atomic<bool> stop_{false};
  23217. std::atomic<int> connect_hits_{0};
  23218. mutable std::mutex connect_request_mutex_;
  23219. std::string connect_request_;
  23220. };
  23221. // Sends one request through the CONNECT proxy to the TLS origin with a
  23222. // credential configured for each hop, and checks that each credential reaches
  23223. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23224. // origin's (every header in origin_headers) on the tunnelled request.
  23225. void CredentialsStayWithTheirHop(
  23226. const std::function<void(SSLClient &)> &set_credentials,
  23227. const std::string &scheme,
  23228. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23229. std::atomic<int> origin_hits{0};
  23230. std::atomic<bool> origin_saw_proxy_authz{false};
  23231. std::atomic<bool> origin_saw_headers{false};
  23232. ScopedSSLServer origin;
  23233. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23234. origin_hits++;
  23235. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23236. origin_saw_headers =
  23237. std::all_of(origin_headers.begin(), origin_headers.end(),
  23238. [&](const std::string &h) { return req.has_header(h); });
  23239. res.set_content("ok", "text/plain");
  23240. });
  23241. origin.listen();
  23242. ScopedConnectProxy proxy(origin.port());
  23243. ASSERT_NE(0, proxy.port());
  23244. // Pinned to 127.0.0.1 for the same reason as the test below.
  23245. SSLClient cli("127.0.0.1", origin.port());
  23246. cli.enable_server_certificate_verification(false);
  23247. cli.set_proxy("127.0.0.1", proxy.port());
  23248. set_credentials(cli);
  23249. auto res = cli.Get("/x");
  23250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23251. EXPECT_EQ(StatusCode::OK_200, res->status);
  23252. EXPECT_EQ(1, origin_hits.load());
  23253. EXPECT_EQ(1, proxy.connect_hits());
  23254. EXPECT_TRUE(origin_saw_headers.load());
  23255. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23256. << "Proxy-Authorization must not be sent inside the tunnel";
  23257. auto connect_req = proxy.connect_request();
  23258. EXPECT_NE(std::string::npos,
  23259. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23260. for (const auto &h : origin_headers) {
  23261. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23262. << h << " must not be sent to the proxy on CONNECT";
  23263. }
  23264. }
  23265. } // namespace proxy_tunnel_test
  23266. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23267. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23268. [](SSLClient &cli) {
  23269. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23270. cli.set_basic_auth("origin-user", "origin-pass");
  23271. },
  23272. "Basic");
  23273. }
  23274. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23275. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23276. [](SSLClient &cli) {
  23277. cli.set_proxy_bearer_token_auth("proxy-token");
  23278. cli.set_bearer_token_auth("origin-token");
  23279. },
  23280. "Bearer");
  23281. }
  23282. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23283. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23284. [](SSLClient &cli) {
  23285. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23286. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23287. {"Cookie", "sid=origin-session"},
  23288. {"X-Api-Key", "origin-key"}});
  23289. },
  23290. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23291. }
  23292. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23293. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23294. // retry; otherwise proxy creds would be sent to the origin.
  23295. std::atomic<int> origin_hits{0};
  23296. std::atomic<bool> origin_saw_proxy_authz{false};
  23297. proxy_tunnel_test::ScopedSSLServer origin;
  23298. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23299. origin_hits++;
  23300. if (req.has_header("Proxy-Authorization")) {
  23301. origin_saw_proxy_authz = true;
  23302. }
  23303. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23304. res.set_header("Proxy-Authenticate",
  23305. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23306. "algorithm=MD5");
  23307. });
  23308. origin.listen();
  23309. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23310. ASSERT_NE(0, proxy.port());
  23311. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23312. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23313. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23314. // and answer with its own status, making this test flaky.
  23315. SSLClient cli("127.0.0.1", origin.port());
  23316. cli.enable_server_certificate_verification(false);
  23317. cli.set_proxy("127.0.0.1", proxy.port());
  23318. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23319. auto res = cli.Get("/x");
  23320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23321. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23322. EXPECT_EQ(1, origin_hits.load());
  23323. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23324. EXPECT_EQ(1, proxy.connect_hits());
  23325. }
  23326. #endif