test.cc 886 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declaration: in split builds split.py strips `inline` and moves the
  474. // definition into httplib.cc, so detail::base64_encode is not visible from the
  475. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  476. // in both header-only and split builds.
  477. namespace httplib {
  478. namespace detail {
  479. std::string base64_encode(const std::string &in);
  480. } // namespace detail
  481. } // namespace httplib
  482. TEST(Base64EncodeTest, KnownAnswers) {
  483. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  484. // where the accumulator's top bit is already set before the next shift.
  485. EXPECT_EQ("", detail::base64_encode(""));
  486. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  487. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  488. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  489. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  490. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  491. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  492. // High bytes keep the top bit set across several rounds.
  493. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  494. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  495. }
  496. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  497. string unescapedCharacters = "-_.!~*'()";
  498. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  499. }
  500. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  501. string reservedCharacters = ";,/?:@&=+$";
  502. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  503. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  504. }
  505. TEST(ClientQueryOrder, PreserveOrder) {
  506. // This test reproduces Issue #2259: client may reorder query parameters
  507. // when sending a GET request. The expected behavior is that the client
  508. // preserves the original query string order when the caller supplied it
  509. // as part of the path.
  510. Server svr;
  511. svr.Get("/", [&](const Request &req, Response &res) {
  512. // Echo back the raw target so the test can assert ordering
  513. res.set_content(req.target, "text/plain");
  514. });
  515. std::thread t{[&] { svr.listen(HOST, PORT); }};
  516. auto se = detail::scope_exit([&] {
  517. svr.stop();
  518. t.join();
  519. ASSERT_FALSE(svr.is_running());
  520. });
  521. svr.wait_until_ready();
  522. Client cli(HOST, PORT);
  523. ASSERT_TRUE(cli.is_valid());
  524. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  525. auto res = cli.Get(original);
  526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  527. // Expect the echoed target to exactly match the original path (order
  528. // preserved)
  529. EXPECT_EQ(res->body, original);
  530. }
  531. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  532. string chineseCharacters = U8("中国語");
  533. string russianCharacters = U8("дом");
  534. string brazilianCharacters = U8("óculos");
  535. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  536. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  537. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  538. "%D0%B4%D0%BE%D0%BC");
  539. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  540. }
  541. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  542. string unescapedCharacters = "-_.!~*'()";
  543. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  544. }
  545. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  546. string reservedCharacters = ";,/?:@&=+$";
  547. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  548. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  549. }
  550. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  551. string chineseCharacters = U8("中国語");
  552. string russianCharacters = U8("дом");
  553. string brazilianCharacters = U8("óculos");
  554. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  555. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  556. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  557. "%D0%B4%D0%BE%D0%BC");
  558. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  559. }
  560. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  561. // Issue #2082 use case: encoding path component with ampersand
  562. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  563. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  564. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  565. }
  566. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  567. string unescapedCharacters = "-_.!~*'()";
  568. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  569. }
  570. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  571. string reservedCharacters = ";,/?:@&=+$#";
  572. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  573. }
  574. TEST(EncodeUriTest, TestUTF8Characters) {
  575. string chineseCharacters = U8("中国語");
  576. string russianCharacters = U8("дом");
  577. string brazilianCharacters = U8("óculos");
  578. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  579. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  580. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  581. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  582. }
  583. TEST(EncodeUriTest, TestCompleteUri) {
  584. string uri =
  585. "https://example.com/path/to/resource?query=value&param=test#fragment";
  586. EXPECT_EQ(
  587. httplib::encode_uri(uri),
  588. "https://example.com/path/to/resource?query=value&param=test#fragment");
  589. }
  590. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  591. string uri =
  592. "https://example.com/path with spaces/file name.html?q=hello world";
  593. EXPECT_EQ(httplib::encode_uri(uri),
  594. "https://example.com/path%20with%20spaces/"
  595. "file%20name.html?q=hello%20world");
  596. }
  597. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  598. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  599. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  600. }
  601. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  602. string unescapedCharacters = "-_.!~*'()";
  603. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  604. }
  605. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  606. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  607. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  608. string encodedBrazilian = "%C3%B3culos";
  609. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  610. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  611. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  612. }
  613. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  614. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  615. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  616. "Piri Tommy Villiers - on & on");
  617. }
  618. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  619. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  620. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  621. }
  622. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  623. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  624. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  625. }
  626. TEST(DecodeUriTest, TestUTF8Characters) {
  627. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  628. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  629. string encodedBrazilian = "%C3%B3culos";
  630. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  631. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  632. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  633. }
  634. TEST(DecodeUriTest, TestCompleteUri) {
  635. string encodedUri = "https://example.com/path%20with%20spaces/"
  636. "file%20name.html?q=hello%20world";
  637. EXPECT_EQ(
  638. httplib::decode_uri(encodedUri),
  639. "https://example.com/path with spaces/file name.html?q=hello world");
  640. }
  641. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  642. string original =
  643. "https://example.com/path with spaces/file name.html?q=hello world";
  644. string encoded = httplib::encode_uri(original);
  645. string decoded = httplib::decode_uri(encoded);
  646. EXPECT_EQ(decoded, original);
  647. }
  648. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  649. // decode_uri is the inverse of encode_uri: an escaped reserved character
  650. // stays encoded so it is not promoted into a real delimiter, while
  651. // non-reserved escapes still decode (like JS decodeURI).
  652. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  653. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  654. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  655. "%3F%3A%40%26%3D%2B%24%2C%3B");
  656. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  657. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  658. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  659. "http://example.com/a%2Fb");
  660. // decode_uri_component still decodes the reserved character.
  661. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  662. }
  663. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  664. string original = "Piri Tommy Villiers - on & on";
  665. string encoded = httplib::encode_uri_component(original);
  666. string decoded = httplib::decode_uri_component(encoded);
  667. EXPECT_EQ(decoded, original);
  668. }
  669. TEST(TrimTests, TrimStringTests) {
  670. EXPECT_EQ("abc", detail::trim_copy("abc"));
  671. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  672. EXPECT_TRUE(detail::trim_copy("").empty());
  673. }
  674. TEST(AsciiTest, LocaleIndependentClassification) {
  675. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  676. // which consult the global C locale: std::isalnum(0xC5) can return true
  677. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  678. // helpers must classify every byte by the ASCII grammar alone.
  679. for (int i = 0; i < 256; i++) {
  680. auto c = static_cast<char>(i);
  681. auto is_digit = i >= '0' && i <= '9';
  682. auto is_upper = i >= 'A' && i <= 'Z';
  683. auto is_lower = i >= 'a' && i <= 'z';
  684. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  685. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  686. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  687. << "byte " << i;
  688. }
  689. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  690. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  691. // Non-ASCII bytes must be percent-encoded, never passed through as
  692. // alphanumeric.
  693. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  694. }
  695. TEST(FromCharsTest, Double) {
  696. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  697. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  698. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  699. auto parse = [](const std::string &s, double &v) {
  700. return detail::from_chars(s.data(), s.data() + s.size(), v);
  701. };
  702. double v = -1.0;
  703. // Representative quality values.
  704. EXPECT_EQ(parse("0", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 0.0);
  706. EXPECT_EQ(parse("1", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 1.0);
  708. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.8);
  710. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 0.001);
  712. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  713. EXPECT_DOUBLE_EQ(v, 1.0);
  714. // A missing integer or fractional part is tolerated.
  715. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 0.5);
  717. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  718. EXPECT_DOUBLE_EQ(v, 5.0);
  719. // Values outside [0, 1] still parse; the caller range-checks them.
  720. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  721. EXPECT_DOUBLE_EQ(v, 123.456);
  722. // Stops at the first byte that is not part of the number and reports where.
  723. std::string trailing = "0.9, text/html";
  724. auto r = parse(trailing, v);
  725. EXPECT_EQ(r.ec, std::errc{});
  726. EXPECT_DOUBLE_EQ(v, 0.9);
  727. EXPECT_EQ(*r.ptr, ',');
  728. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  729. // outright, and an 'e'/'E' simply ends the number.
  730. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  731. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  732. std::string exp_input = "1.5e3";
  733. r = parse(exp_input, v);
  734. EXPECT_EQ(r.ec, std::errc{});
  735. EXPECT_DOUBLE_EQ(v, 1.5);
  736. EXPECT_EQ(*r.ptr, 'e');
  737. // Invalid inputs.
  738. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  741. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  742. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  743. // Pathological but well-formed inputs must stay bounded (no overflow, no
  744. // out-of-bounds table access) and stay within [0, 1] for the caller.
  745. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  746. std::errc{});
  747. EXPECT_DOUBLE_EQ(v, 0.0);
  748. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  749. std::errc{});
  750. EXPECT_GE(v, 0.0);
  751. EXPECT_LE(v, 1.0);
  752. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  753. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  754. }
  755. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  756. // Simple case without quality values
  757. std::vector<std::string> result1;
  758. EXPECT_TRUE(detail::parse_accept_header(
  759. "text/html,application/json,text/plain", result1));
  760. EXPECT_EQ(result1.size(), 3U);
  761. EXPECT_EQ(result1[0], "text/html");
  762. EXPECT_EQ(result1[1], "application/json");
  763. EXPECT_EQ(result1[2], "text/plain");
  764. // With quality values
  765. std::vector<std::string> result2;
  766. EXPECT_TRUE(detail::parse_accept_header(
  767. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  768. EXPECT_EQ(result2.size(), 3U);
  769. EXPECT_EQ(result2[0], "application/json"); // highest q value
  770. EXPECT_EQ(result2[1], "text/html");
  771. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  772. }
  773. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  774. // Mixed with and without quality values
  775. std::vector<std::string> result;
  776. EXPECT_TRUE(detail::parse_accept_header(
  777. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  778. EXPECT_EQ(result.size(), 3U);
  779. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  780. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  781. EXPECT_EQ(result[2], "application/json"); // q=0.5
  782. }
  783. TEST(ParseAcceptHeaderTest, EdgeCases) {
  784. // Empty header
  785. std::vector<std::string> empty_result;
  786. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  787. EXPECT_TRUE(empty_result.empty());
  788. // Single type
  789. std::vector<std::string> single_result;
  790. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  791. EXPECT_EQ(single_result.size(), 1U);
  792. EXPECT_EQ(single_result[0], "application/json");
  793. // Wildcard types
  794. std::vector<std::string> wildcard_result;
  795. EXPECT_TRUE(detail::parse_accept_header(
  796. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  797. EXPECT_EQ(wildcard_result.size(), 3U);
  798. EXPECT_EQ(wildcard_result[0], "application/json");
  799. EXPECT_EQ(wildcard_result[1], "text/*");
  800. EXPECT_EQ(wildcard_result[2], "*/*");
  801. }
  802. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  803. // Common browser Accept header
  804. std::vector<std::string> browser_result;
  805. EXPECT_TRUE(
  806. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  807. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  808. browser_result));
  809. EXPECT_EQ(browser_result.size(), 6U);
  810. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  813. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  814. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  815. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  816. // API client header
  817. std::vector<std::string> api_result;
  818. EXPECT_TRUE(detail::parse_accept_header(
  819. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  820. api_result));
  821. EXPECT_EQ(api_result.size(), 3U);
  822. EXPECT_EQ(api_result[0], "application/json");
  823. EXPECT_EQ(api_result[1], "application/xml");
  824. EXPECT_EQ(api_result[2], "text/plain");
  825. }
  826. TEST(ParseAcceptHeaderTest, SpecialCases) {
  827. // Quality value with 3 decimal places
  828. std::vector<std::string> decimal_result;
  829. EXPECT_TRUE(detail::parse_accept_header(
  830. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  831. EXPECT_EQ(decimal_result.size(), 2U);
  832. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  833. EXPECT_EQ(decimal_result[1], "text/html");
  834. // Zero quality (should still be included but with lowest priority)
  835. std::vector<std::string> zero_q_result;
  836. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  837. zero_q_result));
  838. EXPECT_EQ(zero_q_result.size(), 2U);
  839. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  840. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  841. // No spaces around commas
  842. std::vector<std::string> no_space_result;
  843. EXPECT_TRUE(detail::parse_accept_header(
  844. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  845. no_space_result));
  846. EXPECT_EQ(no_space_result.size(), 3U);
  847. EXPECT_EQ(no_space_result[0], "text/html");
  848. EXPECT_EQ(no_space_result[1], "application/json");
  849. EXPECT_EQ(no_space_result[2], "text/plain");
  850. }
  851. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  852. // Quality values always use '.' as the decimal separator, so parsing must
  853. // not depend on the process locale. An embedding application may have
  854. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  855. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  856. std::string saved = cur ? cur : "C";
  857. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  858. "fr_FR.UTF-8"};
  859. bool switched = false;
  860. for (const auto loc : comma_locales) {
  861. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  862. std::localeconv()->decimal_point[0] == ',') {
  863. switched = true;
  864. break;
  865. }
  866. }
  867. if (!switched) {
  868. std::setlocale(LC_NUMERIC, saved.c_str());
  869. GTEST_SKIP() << "no comma-decimal locale available on this host";
  870. }
  871. // The higher-weighted type appears later in the list, so a correct parse
  872. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  873. // sensitive parse reads both weights as 0 and leaves the original order.
  874. std::vector<std::string> result;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "application/json;q=0.1,text/html;q=0.9", result));
  877. ASSERT_EQ(result.size(), 2U);
  878. EXPECT_EQ(result[0], "text/html");
  879. EXPECT_EQ(result[1], "application/json");
  880. std::setlocale(LC_NUMERIC, saved.c_str());
  881. }
  882. TEST(ParseAcceptHeaderTest, InvalidCases) {
  883. std::vector<std::string> result;
  884. // Invalid quality value (> 1.0)
  885. EXPECT_FALSE(
  886. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  887. // Invalid quality value (< 0.0)
  888. EXPECT_FALSE(
  889. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  890. // Invalid quality value (not a number)
  891. EXPECT_FALSE(detail::parse_accept_header(
  892. "text/html;q=invalid,application/json", result));
  893. // A valid numeric prefix does not make the entire quality value valid.
  894. EXPECT_FALSE(detail::parse_accept_header(
  895. "text/html;q=0.5junk,application/json", result));
  896. // Empty quality value
  897. EXPECT_FALSE(
  898. detail::parse_accept_header("text/html;q=,application/json", result));
  899. // Invalid media type format (no slash and not wildcard)
  900. EXPECT_FALSE(
  901. detail::parse_accept_header("invalidtype,application/json", result));
  902. // Valid cases should still work
  903. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  904. EXPECT_EQ(result.size(), 1U);
  905. EXPECT_EQ(result[0], "*/*");
  906. EXPECT_TRUE(detail::parse_accept_header("*", result));
  907. EXPECT_EQ(result.size(), 1U);
  908. EXPECT_EQ(result[0], "*");
  909. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  910. EXPECT_EQ(result.size(), 1U);
  911. EXPECT_EQ(result[0], "text/*");
  912. }
  913. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  914. // elements, so a leading, trailing or doubled comma is a legal Accept value
  915. // and must not be answered with 400 Bad Request.
  916. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  917. struct {
  918. const char *value;
  919. std::vector<std::string> expected;
  920. } cases[] = {
  921. {",application/json", {"application/json"}},
  922. {"text/html,", {"text/html"}},
  923. {"text/html,,*/*", {"text/html", "*/*"}},
  924. // An empty element may be spelled with whitespace in it
  925. {"text/html, , application/json", {"text/html", "application/json"}},
  926. // Nothing but empty elements is an empty list, which means the same
  927. // thing as no Accept header at all
  928. {",,,", {}},
  929. // Quality values still apply across ignored empty elements
  930. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  931. };
  932. for (const auto &c : cases) {
  933. std::vector<std::string> result;
  934. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  935. << "value: " << c.value;
  936. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  937. }
  938. // An invalid entry is still rejected when empty elements surround it
  939. std::vector<std::string> result;
  940. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  941. }
  942. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  943. Server svr;
  944. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  945. EXPECT_EQ(req.accept_content_types.size(), 3U);
  946. EXPECT_EQ(req.accept_content_types[0], "application/json");
  947. EXPECT_EQ(req.accept_content_types[1], "text/html");
  948. EXPECT_EQ(req.accept_content_types[2], "*/*");
  949. res.set_content("ok", "text/plain");
  950. });
  951. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  952. EXPECT_TRUE(false);
  953. res.set_content("bad request", "text/plain");
  954. });
  955. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  956. auto se = detail::scope_exit([&] {
  957. svr.stop();
  958. listen_thread.join();
  959. ASSERT_FALSE(svr.is_running());
  960. });
  961. svr.wait_until_ready();
  962. Client cli("localhost", PORT);
  963. {
  964. auto res = cli.Get(
  965. "/accept_ok",
  966. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  968. EXPECT_EQ(StatusCode::OK_200, res->status);
  969. }
  970. {
  971. auto res = cli.Get("/accept_bad_request",
  972. Headers{{"Accept", "text/html;q=abc,application/json"}});
  973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  974. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  975. }
  976. }
  977. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  978. Server svr;
  979. svr.Get("/", [](const Request & /*req*/, Response &res) {
  980. res.set_content("ok", "text/plain");
  981. });
  982. std::atomic<int> start_count{0};
  983. std::atomic<bool> running_when_called{false};
  984. svr.set_start_handler([&]() {
  985. running_when_called = svr.is_running();
  986. start_count++;
  987. });
  988. auto port = svr.bind_to_any_port(HOST);
  989. std::thread t([&]() { svr.listen_after_bind(); });
  990. auto se = detail::scope_exit([&] {
  991. svr.stop();
  992. t.join();
  993. ASSERT_FALSE(svr.is_running());
  994. });
  995. svr.wait_until_ready();
  996. // A successful request proves the accept loop is running, which the start
  997. // handler precedes; so by now the handler must have run exactly once.
  998. Client cli(HOST, port);
  999. cli.set_connection_timeout(std::chrono::seconds(5));
  1000. auto res = cli.Get("/");
  1001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1002. EXPECT_EQ(StatusCode::OK_200, res->status);
  1003. EXPECT_EQ(1, start_count.load());
  1004. EXPECT_TRUE(running_when_called.load());
  1005. }
  1006. TEST(DivideTest, DivideStringTests) {
  1007. auto divide = [](const std::string &str, char d) {
  1008. std::string lhs;
  1009. std::string rhs;
  1010. detail::divide(str, d,
  1011. [&](const char *lhs_data, std::size_t lhs_size,
  1012. const char *rhs_data, std::size_t rhs_size) {
  1013. lhs.assign(lhs_data, lhs_size);
  1014. rhs.assign(rhs_data, rhs_size);
  1015. });
  1016. return std::make_pair(std::move(lhs), std::move(rhs));
  1017. };
  1018. {
  1019. const auto res = divide("", '=');
  1020. EXPECT_EQ(res.first, "");
  1021. EXPECT_EQ(res.second, "");
  1022. }
  1023. {
  1024. const auto res = divide("=", '=');
  1025. EXPECT_EQ(res.first, "");
  1026. EXPECT_EQ(res.second, "");
  1027. }
  1028. {
  1029. const auto res = divide(" ", '=');
  1030. EXPECT_EQ(res.first, " ");
  1031. EXPECT_EQ(res.second, "");
  1032. }
  1033. {
  1034. const auto res = divide("a", '=');
  1035. EXPECT_EQ(res.first, "a");
  1036. EXPECT_EQ(res.second, "");
  1037. }
  1038. {
  1039. const auto res = divide("a=", '=');
  1040. EXPECT_EQ(res.first, "a");
  1041. EXPECT_EQ(res.second, "");
  1042. }
  1043. {
  1044. const auto res = divide("=b", '=');
  1045. EXPECT_EQ(res.first, "");
  1046. EXPECT_EQ(res.second, "b");
  1047. }
  1048. {
  1049. const auto res = divide("a=b", '=');
  1050. EXPECT_EQ(res.first, "a");
  1051. EXPECT_EQ(res.second, "b");
  1052. }
  1053. {
  1054. const auto res = divide("a=b=", '=');
  1055. EXPECT_EQ(res.first, "a");
  1056. EXPECT_EQ(res.second, "b=");
  1057. }
  1058. {
  1059. const auto res = divide("a=b=c", '=');
  1060. EXPECT_EQ(res.first, "a");
  1061. EXPECT_EQ(res.second, "b=c");
  1062. }
  1063. }
  1064. TEST(SplitTest, ParseQueryString) {
  1065. string s = "key1=val1&key2=val2&key3=val3";
  1066. Params dic;
  1067. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1068. [&](const char *b, const char *e) {
  1069. string key, val;
  1070. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1071. if (key.empty()) {
  1072. key.assign(b2, e2);
  1073. } else {
  1074. val.assign(b2, e2);
  1075. }
  1076. });
  1077. dic.emplace(key, val);
  1078. });
  1079. EXPECT_EQ("val1", dic.find("key1")->second);
  1080. EXPECT_EQ("val2", dic.find("key2")->second);
  1081. EXPECT_EQ("val3", dic.find("key3")->second);
  1082. }
  1083. TEST(SplitTest, ParseInvalidQueryTests) {
  1084. {
  1085. string s = " ";
  1086. Params dict;
  1087. detail::parse_query_text(s, dict);
  1088. EXPECT_TRUE(dict.empty());
  1089. }
  1090. {
  1091. string s = " = =";
  1092. Params dict;
  1093. detail::parse_query_text(s, dict);
  1094. EXPECT_TRUE(dict.empty());
  1095. }
  1096. }
  1097. TEST(ParseQueryTest, ParseQueryString) {
  1098. {
  1099. std::string s = "key1=val1&key2=val2&key3=val3";
  1100. Params dic;
  1101. detail::parse_query_text(s, dic);
  1102. EXPECT_EQ("val1", dic.find("key1")->second);
  1103. EXPECT_EQ("val2", dic.find("key2")->second);
  1104. EXPECT_EQ("val3", dic.find("key3")->second);
  1105. }
  1106. {
  1107. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1108. Params dic;
  1109. detail::parse_query_text(s, dic);
  1110. EXPECT_EQ("", dic.find("key1")->second);
  1111. EXPECT_EQ("val1", dic.find("key2")->second);
  1112. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1113. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1114. }
  1115. }
  1116. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1117. Params dic;
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1119. dic.emplace("key1", "val1");
  1120. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1121. dic.emplace("key2", "val2");
  1122. dic.emplace("key3", "val3");
  1123. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1124. }
  1125. // Joins every entry of a Headers or Params into "key=value " so a whole
  1126. // traversal can be compared in one assertion. Both are instantiations of the
  1127. // same insertion-ordered container, so one helper serves both.
  1128. template <typename Map> static std::string entries_to_string(const Map &m) {
  1129. std::string s;
  1130. for (const auto &entry : m) {
  1131. s += entry.first + "=" + entry.second + " ";
  1132. }
  1133. return s;
  1134. }
  1135. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1136. // Params used to be a std::multimap, which sorted by name and handed the
  1137. // caller's query back alphabetised. A client signing its query string could
  1138. // not reproduce the order it asked for.
  1139. Params dic;
  1140. dic.emplace("zulu", "1");
  1141. dic.emplace("alpha", "2");
  1142. dic.emplace("mike", "3");
  1143. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1144. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1145. }
  1146. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1147. Params dic;
  1148. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1149. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1150. }
  1151. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1152. Request req;
  1153. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1154. req.params);
  1155. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1156. EXPECT_EQ("first", req.get_param_value("tag"));
  1157. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1158. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1159. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1160. EXPECT_EQ("", req.get_param_value("tag", 3));
  1161. }
  1162. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1163. // Params shares its container with Headers, which matches field names
  1164. // case-insensitively. Parameter names must not pick that up.
  1165. Params dic;
  1166. dic.emplace("Key", "upper");
  1167. dic.emplace("key", "lower");
  1168. EXPECT_EQ(2U, dic.size());
  1169. EXPECT_EQ(1U, dic.count("Key"));
  1170. EXPECT_EQ(1U, dic.count("key"));
  1171. EXPECT_EQ("upper", dic.find("Key")->second);
  1172. EXPECT_EQ("lower", dic.find("key")->second);
  1173. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1174. }
  1175. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1176. Server svr;
  1177. std::string order;
  1178. svr.Get("/order", [&](const Request &req, Response &res) {
  1179. order = entries_to_string(req.params);
  1180. res.set_content("ok", "text/plain");
  1181. });
  1182. auto port = svr.bind_to_any_port(HOST);
  1183. thread t = thread([&] { svr.listen_after_bind(); });
  1184. auto se = detail::scope_exit([&] {
  1185. svr.stop();
  1186. t.join();
  1187. ASSERT_FALSE(svr.is_running());
  1188. });
  1189. svr.wait_until_ready();
  1190. Client cli(HOST, port);
  1191. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1192. ASSERT_TRUE(res);
  1193. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1194. }
  1195. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1196. Server svr;
  1197. std::string field_order, file_order;
  1198. svr.Post("/order", [&](const Request &req, Response &res) {
  1199. for (const auto &field : req.form.fields) {
  1200. field_order += field.first + "=" + field.second.content + " ";
  1201. }
  1202. for (const auto &file : req.form.files) {
  1203. file_order += file.first + "=" + file.second.filename + " ";
  1204. }
  1205. res.set_content("ok", "text/plain");
  1206. });
  1207. auto port = svr.bind_to_any_port(HOST);
  1208. thread t = thread([&] { svr.listen_after_bind(); });
  1209. auto se = detail::scope_exit([&] {
  1210. svr.stop();
  1211. t.join();
  1212. ASSERT_FALSE(svr.is_running());
  1213. });
  1214. svr.wait_until_ready();
  1215. UploadFormDataItems items = {
  1216. {"zulu", "1", "", ""},
  1217. {"alpha", "2", "", ""},
  1218. {"mike", "3", "", ""},
  1219. {"zebra", "z", "z.txt", "text/plain"},
  1220. {"apple", "a", "a.txt", "text/plain"},
  1221. };
  1222. Client cli(HOST, port);
  1223. auto res = cli.Post("/order", items);
  1224. ASSERT_TRUE(res);
  1225. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1226. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1227. }
  1228. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1229. Server svr;
  1230. std::vector<std::string> values;
  1231. std::string first, second, out_of_range, order;
  1232. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1233. values = req.form.get_fields("tag");
  1234. first = req.form.get_field("tag", 0);
  1235. second = req.form.get_field("tag", 1);
  1236. out_of_range = req.form.get_field("tag", 2);
  1237. for (const auto &field : req.form.fields) {
  1238. order += field.first + "=" + field.second.content + " ";
  1239. }
  1240. res.set_content("ok", "text/plain");
  1241. });
  1242. auto port = svr.bind_to_any_port(HOST);
  1243. thread t = thread([&] { svr.listen_after_bind(); });
  1244. auto se = detail::scope_exit([&] {
  1245. svr.stop();
  1246. t.join();
  1247. ASSERT_FALSE(svr.is_running());
  1248. });
  1249. svr.wait_until_ready();
  1250. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1251. // not adjacent in the container.
  1252. UploadFormDataItems items = {
  1253. {"tag", "first", "", ""},
  1254. {"other", "x", "", ""},
  1255. {"tag", "second", "", ""},
  1256. };
  1257. Client cli(HOST, port);
  1258. auto res = cli.Post("/repeated", items);
  1259. ASSERT_TRUE(res);
  1260. ASSERT_EQ(2U, values.size());
  1261. EXPECT_EQ("first", values[0]);
  1262. EXPECT_EQ("second", values[1]);
  1263. EXPECT_EQ("first", first);
  1264. EXPECT_EQ("second", second);
  1265. // std::multimap already kept entries sharing a name in insertion order, so
  1266. // everything above passes without this change too. The whole traversal is
  1267. // what tells the two apart: sorting by name would hoist "other" to the front
  1268. // and the two "tag" parts would end up adjacent.
  1269. EXPECT_EQ("tag=first other=x tag=second ", order);
  1270. // Advancing past the last entry of a name used to run off the container;
  1271. // the container's saturating increment makes it return the default instead.
  1272. EXPECT_EQ("", out_of_range);
  1273. }
  1274. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1275. // Server::read_content() keeps a FormFields::iterator alive across the
  1276. // content callbacks that fill the part it points at. The container is
  1277. // vector-backed, so a later emplace can reallocate and invalidate an older
  1278. // iterator; 64 parts grow the vector through seven reallocations, which
  1279. // checks that every part's content still lands in its own entry.
  1280. const size_t part_count = 64;
  1281. // One formula for both the parts sent and the values expected back, so the
  1282. // two cannot drift apart.
  1283. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1284. auto content_of = [](size_t i) {
  1285. return std::string(64, static_cast<char>('a' + (i % 26)));
  1286. };
  1287. Server svr;
  1288. std::vector<std::pair<std::string, std::string>> received;
  1289. svr.Post("/many", [&](const Request &req, Response &res) {
  1290. for (const auto &field : req.form.fields) {
  1291. received.emplace_back(field.first, field.second.content);
  1292. }
  1293. res.set_content("ok", "text/plain");
  1294. });
  1295. auto port = svr.bind_to_any_port(HOST);
  1296. thread t = thread([&] { svr.listen_after_bind(); });
  1297. auto se = detail::scope_exit([&] {
  1298. svr.stop();
  1299. t.join();
  1300. ASSERT_FALSE(svr.is_running());
  1301. });
  1302. svr.wait_until_ready();
  1303. UploadFormDataItems items;
  1304. for (size_t i = 0; i < part_count; i++) {
  1305. items.push_back({name_of(i), content_of(i), "", ""});
  1306. }
  1307. Client cli(HOST, port);
  1308. auto res = cli.Post("/many", items);
  1309. ASSERT_TRUE(res);
  1310. ASSERT_EQ(part_count, received.size());
  1311. for (size_t i = 0; i < part_count; i++) {
  1312. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1313. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1314. }
  1315. }
  1316. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1317. string content_type = "multipart/form-data; boundary=something";
  1318. string boundary;
  1319. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1320. EXPECT_TRUE(ret);
  1321. EXPECT_EQ(boundary, "something");
  1322. }
  1323. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1324. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1325. string boundary;
  1326. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1327. EXPECT_TRUE(ret);
  1328. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1329. }
  1330. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1331. string content_type =
  1332. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1333. string boundary;
  1334. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1335. EXPECT_TRUE(ret);
  1336. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1337. }
  1338. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1339. string content_type =
  1340. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1341. string boundary;
  1342. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1343. EXPECT_TRUE(ret);
  1344. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1345. }
  1346. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1347. const string boundary(70, 'a');
  1348. string content_type = "multipart/form-data; boundary=" + boundary;
  1349. string parsed;
  1350. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1351. EXPECT_TRUE(ret);
  1352. EXPECT_EQ(parsed, boundary);
  1353. }
  1354. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1355. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1356. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1357. string parsed;
  1358. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1359. EXPECT_FALSE(ret);
  1360. }
  1361. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1362. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1363. // is 72 characters on the wire and still valid.
  1364. const string boundary(70, 'a');
  1365. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1366. string parsed;
  1367. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1368. EXPECT_EQ(parsed, boundary);
  1369. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1370. parsed.clear();
  1371. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1372. }
  1373. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1374. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1375. // The parameter parser must not treat that '=' as the key/value separator.
  1376. string content_type =
  1377. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1378. "charset=UTF-8";
  1379. string parsed;
  1380. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1381. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1382. }
  1383. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1384. // A ';' inside the quoted-string is part of the value, not a parameter
  1385. // separator, so it must not truncate the boundary.
  1386. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1387. string parsed;
  1388. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1389. EXPECT_EQ(parsed, "a;b");
  1390. }
  1391. TEST(ParseDispositionParamsTest, QuotedValues) {
  1392. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1393. // ';' and '=' are ordinary characters inside one.
  1394. struct {
  1395. const char *value;
  1396. std::vector<std::pair<const char *, const char *>> expected;
  1397. } cases[] = {
  1398. {"name=\"file1\"; filename=\"a.txt\"",
  1399. {{"name", "file1"}, {"filename", "a.txt"}}},
  1400. // Whitespace around '=' and ';' is still trimmed
  1401. {"name=\"file2\" ;filename = \"a.html\"",
  1402. {{"name", "file2"}, {"filename", "a.html"}}},
  1403. // '=' inside the value used to leave only the text after the last one
  1404. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1405. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1406. {"name=\"x=y\"", {{"name", "x=y"}}},
  1407. // ';' inside the value used to truncate the pair and leave a bogus one
  1408. {"name=\"file3\"; filename=\"a;b.txt\"",
  1409. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1410. // An unquoted value keeps working, and so does filename*
  1411. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1412. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1413. // A parameter with no key is dropped rather than turned into one whose
  1414. // key is the value
  1415. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1416. };
  1417. for (const auto &c : cases) {
  1418. Params params;
  1419. detail::parse_disposition_params(c.value, params);
  1420. for (const auto &kv : c.expected) {
  1421. auto it = params.find(kv.first);
  1422. ASSERT_NE(it, params.end())
  1423. << "value: " << c.value << ", key: " << kv.first;
  1424. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1425. }
  1426. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1427. }
  1428. }
  1429. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1430. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1431. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1432. Server svr;
  1433. std::string field_value, file_name, file_filename;
  1434. bool has_field = false, has_file = false;
  1435. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1436. has_field = req.form.has_field("x=y");
  1437. field_value = req.form.get_field("x=y");
  1438. has_file = req.form.has_file("file1");
  1439. const auto &file = req.form.get_file("file1");
  1440. file_name = file.name;
  1441. file_filename = file.filename;
  1442. res.set_content("ok", "text/plain");
  1443. });
  1444. auto port = svr.bind_to_any_port(HOST);
  1445. thread t = thread([&] { svr.listen_after_bind(); });
  1446. auto se = detail::scope_exit([&] {
  1447. svr.stop();
  1448. t.join();
  1449. ASSERT_FALSE(svr.is_running());
  1450. });
  1451. svr.wait_until_ready();
  1452. UploadFormDataItems items = {
  1453. {"x=y", "field-value", "", ""},
  1454. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1455. };
  1456. Client cli(HOST, port);
  1457. auto res = cli.Post("/quoted", items);
  1458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1459. ASSERT_EQ(StatusCode::OK_200, res->status);
  1460. EXPECT_TRUE(has_field);
  1461. EXPECT_EQ("field-value", field_value);
  1462. EXPECT_TRUE(has_file);
  1463. EXPECT_EQ("file1", file_name);
  1464. EXPECT_EQ("a;b=report.pdf", file_filename);
  1465. }
  1466. TEST(GetHeaderValueTest, DefaultValue) {
  1467. Headers headers = {{"Dummy", "Dummy"}};
  1468. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1469. EXPECT_STREQ("text/plain", val);
  1470. }
  1471. TEST(GetHeaderValueTest, DefaultValueInt) {
  1472. Headers headers = {{"Dummy", "Dummy"}};
  1473. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1474. EXPECT_EQ(100ull, val);
  1475. }
  1476. TEST(GetHeaderValueTest, RegularValue) {
  1477. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1478. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1479. EXPECT_STREQ("text/html", val);
  1480. }
  1481. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1482. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1483. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1484. EXPECT_STREQ("text/html", val);
  1485. }
  1486. TEST(GetHeaderValueTest, SetContent) {
  1487. Response res;
  1488. res.set_content("html", "text/html");
  1489. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1490. res.set_content("text", "text/plain");
  1491. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1492. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1493. }
  1494. TEST(GetHeaderValueTest, RegularValueInt) {
  1495. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1496. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1497. EXPECT_EQ(100ull, val);
  1498. }
  1499. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1500. Headers headers = {{"Content-Length", "x"}};
  1501. auto is_invalid_value = false;
  1502. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1503. is_invalid_value);
  1504. EXPECT_EQ(0ull, val);
  1505. EXPECT_TRUE(is_invalid_value);
  1506. }
  1507. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1508. // An all-digit value that overflows size_t must be reported as invalid, not
  1509. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1510. // a large length to a small one on 32-bit builds, leaving the framing length
  1511. // wrong while is_invalid_value stayed false.
  1512. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1513. auto is_invalid_value = false;
  1514. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1515. is_invalid_value);
  1516. EXPECT_TRUE(is_invalid_value);
  1517. // A well-formed length is unaffected.
  1518. Headers ok = {{"Content-Length", "1234"}};
  1519. is_invalid_value = false;
  1520. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1521. is_invalid_value);
  1522. EXPECT_EQ(1234ull, val);
  1523. EXPECT_FALSE(is_invalid_value);
  1524. }
  1525. TEST(GetHeaderValueTest, Range) {
  1526. {
  1527. Headers headers = {make_range_header({{1, -1}})};
  1528. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1529. EXPECT_STREQ("bytes=1-", val);
  1530. }
  1531. {
  1532. Headers headers = {make_range_header({{-1, 1}})};
  1533. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1534. EXPECT_STREQ("bytes=-1", val);
  1535. }
  1536. {
  1537. Headers headers = {make_range_header({{1, 10}})};
  1538. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1539. EXPECT_STREQ("bytes=1-10", val);
  1540. }
  1541. {
  1542. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1543. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1544. EXPECT_STREQ("bytes=1-10, 100-", val);
  1545. }
  1546. {
  1547. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1548. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1549. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1550. }
  1551. {
  1552. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1553. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1554. EXPECT_STREQ("bytes=0-0, -1", val);
  1555. }
  1556. }
  1557. TEST(BearerTokenAuthTest, SchemeValidation) {
  1558. // A value shorter than "Bearer " must not throw from the fixed-length
  1559. // substr, and a non-Bearer scheme must not be reported as a token.
  1560. struct {
  1561. const char *value;
  1562. const char *expected;
  1563. } cases[] = {
  1564. {"x", ""},
  1565. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1566. {"Bearer abc123", "abc123"},
  1567. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1568. };
  1569. for (const auto &c : cases) {
  1570. Request req;
  1571. req.set_header("Authorization", c.value);
  1572. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1573. }
  1574. }
  1575. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1576. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1577. // to depend on the standard library (libstdc++ handed back duplicates in
  1578. // reverse insertion order, libc++ in insertion order).
  1579. Request req;
  1580. req.set_header("Accept-Encoding", "gzip");
  1581. req.set_header("Accept-Encoding", "deflate");
  1582. req.set_header("Accept-Encoding", "br");
  1583. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1584. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1585. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1586. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1587. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1588. }
  1589. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1590. Request req;
  1591. req.set_header("X-Test", "only");
  1592. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1593. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1594. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1595. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1596. }
  1597. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1598. Headers headers;
  1599. headers.emplace("Host", "example.com");
  1600. headers.emplace("Accept-Encoding", "gzip");
  1601. headers.emplace("User-Agent", "test");
  1602. headers.emplace("Accept-Encoding", "deflate");
  1603. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1604. "Accept-Encoding=deflate ",
  1605. entries_to_string(headers));
  1606. }
  1607. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1608. Headers headers = {{"Content-Type", "text/html"},
  1609. {"CONTENT-TYPE", "text/xml"}};
  1610. EXPECT_EQ(2U, headers.count("content-type"));
  1611. auto it = headers.find("content-type");
  1612. ASSERT_TRUE(it != headers.end());
  1613. EXPECT_EQ("text/html", it->second);
  1614. }
  1615. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1616. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1617. // drop only those fields and leave everything positioned between them.
  1618. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1619. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1620. auto rng = headers.equal_range("a");
  1621. headers.erase(rng.first, rng.second);
  1622. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1623. }
  1624. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1625. Headers headers = {
  1626. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1627. EXPECT_EQ(3U, headers.erase("A"));
  1628. EXPECT_EQ(0U, headers.count("A"));
  1629. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1630. }
  1631. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1632. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1633. headers.emplace_front("Host", "example.com");
  1634. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1635. entries_to_string(headers));
  1636. }
  1637. TEST(ParseHeaderValueTest, Range) {
  1638. {
  1639. Ranges ranges;
  1640. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1641. EXPECT_TRUE(ret);
  1642. EXPECT_EQ(1u, ranges.size());
  1643. EXPECT_EQ(1u, ranges[0].first);
  1644. EXPECT_EQ(-1, ranges[0].second);
  1645. }
  1646. {
  1647. Ranges ranges;
  1648. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1649. EXPECT_TRUE(ret);
  1650. EXPECT_EQ(1u, ranges.size());
  1651. EXPECT_EQ(-1, ranges[0].first);
  1652. EXPECT_EQ(1u, ranges[0].second);
  1653. }
  1654. {
  1655. Ranges ranges;
  1656. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1657. EXPECT_TRUE(ret);
  1658. EXPECT_EQ(1u, ranges.size());
  1659. EXPECT_EQ(1u, ranges[0].first);
  1660. EXPECT_EQ(10u, ranges[0].second);
  1661. }
  1662. {
  1663. Ranges ranges;
  1664. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1665. EXPECT_FALSE(ret);
  1666. }
  1667. {
  1668. Ranges ranges;
  1669. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(2u, ranges.size());
  1672. EXPECT_EQ(1u, ranges[0].first);
  1673. EXPECT_EQ(10u, ranges[0].second);
  1674. EXPECT_EQ(100u, ranges[1].first);
  1675. EXPECT_EQ(-1, ranges[1].second);
  1676. }
  1677. {
  1678. Ranges ranges;
  1679. auto ret =
  1680. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1681. EXPECT_TRUE(ret);
  1682. EXPECT_EQ(3u, ranges.size());
  1683. EXPECT_EQ(1u, ranges[0].first);
  1684. EXPECT_EQ(10u, ranges[0].second);
  1685. EXPECT_EQ(100u, ranges[1].first);
  1686. EXPECT_EQ(200u, ranges[1].second);
  1687. EXPECT_EQ(300u, ranges[2].first);
  1688. EXPECT_EQ(400u, ranges[2].second);
  1689. }
  1690. {
  1691. Ranges ranges;
  1692. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1703. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1704. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1705. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1706. EXPECT_FALSE(
  1707. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1708. EXPECT_TRUE(ranges.empty());
  1709. }
  1710. {
  1711. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1712. // remainder of the representation, so it stays accepted.
  1713. Ranges ranges;
  1714. auto ret =
  1715. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1716. EXPECT_TRUE(ret);
  1717. ASSERT_EQ(1u, ranges.size());
  1718. EXPECT_EQ(0, ranges[0].first);
  1719. EXPECT_EQ(-1, ranges[0].second);
  1720. }
  1721. // RFC 9110 14.1: range unit names are case-insensitive.
  1722. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1723. Ranges ranges;
  1724. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1725. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1726. }
  1727. }
  1728. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1729. Request req;
  1730. req.set_header("Accept-Encoding", "gzip");
  1731. Response res;
  1732. res.set_header("Content-Type", "text/plain");
  1733. auto ret = detail::encoding_type(req, res);
  1734. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1735. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1736. #else
  1737. EXPECT_TRUE(ret == detail::EncodingType::None);
  1738. #endif
  1739. }
  1740. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1741. Request req;
  1742. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1743. Response res;
  1744. res.set_header("Content-Type", "text/plain");
  1745. auto ret = detail::encoding_type(req, res);
  1746. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1747. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1748. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1749. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1750. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1751. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1752. #else
  1753. EXPECT_TRUE(ret == detail::EncodingType::None);
  1754. #endif
  1755. }
  1756. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1757. Request req;
  1758. req.set_header("Accept-Encoding",
  1759. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1760. Response res;
  1761. res.set_header("Content-Type", "text/plain");
  1762. auto ret = detail::encoding_type(req, res);
  1763. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1764. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1765. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1766. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1767. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1768. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1769. #else
  1770. EXPECT_TRUE(ret == detail::EncodingType::None);
  1771. #endif
  1772. }
  1773. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1774. // All supported encodings rejected with q=0 should return None
  1775. Request req;
  1776. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1777. Response res;
  1778. res.set_header("Content-Type", "text/plain");
  1779. auto ret = detail::encoding_type(req, res);
  1780. EXPECT_TRUE(ret == detail::EncodingType::None);
  1781. }
  1782. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1783. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. auto ret = detail::encoding_type(req, res);
  1789. EXPECT_TRUE(ret == detail::EncodingType::None);
  1790. }
  1791. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1797. }
  1798. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1799. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1800. Request req;
  1801. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1802. Response res;
  1803. res.set_header("Content-Type", "text/plain");
  1804. auto ret = detail::encoding_type(req, res);
  1805. EXPECT_TRUE(ret == detail::EncodingType::None);
  1806. }
  1807. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1808. // RFC 7231: Accept-Encoding values are case-insensitive
  1809. Request req;
  1810. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1811. Response res;
  1812. res.set_header("Content-Type", "text/plain");
  1813. auto ret = detail::encoding_type(req, res);
  1814. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1815. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1816. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1817. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1818. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1819. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1820. #else
  1821. EXPECT_TRUE(ret == detail::EncodingType::None);
  1822. #endif
  1823. }
  1824. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1825. // q value should determine priority, not hardcoded order
  1826. Request req;
  1827. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1828. Response res;
  1829. res.set_header("Content-Type", "text/plain");
  1830. auto ret = detail::encoding_type(req, res);
  1831. // gzip has highest q=1.0, so it should be selected even though
  1832. // br and zstd are also supported
  1833. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1834. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1835. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1836. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1837. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1838. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1839. #else
  1840. EXPECT_TRUE(ret == detail::EncodingType::None);
  1841. #endif
  1842. }
  1843. TEST(BufferStreamTest, read) {
  1844. detail::BufferStream strm1;
  1845. Stream &strm = strm1;
  1846. EXPECT_EQ(5, strm.write("hello"));
  1847. char buf[512];
  1848. EXPECT_EQ(2, strm.read(buf, 2));
  1849. EXPECT_EQ('h', buf[0]);
  1850. EXPECT_EQ('e', buf[1]);
  1851. EXPECT_EQ(2, strm.read(buf, 2));
  1852. EXPECT_EQ('l', buf[0]);
  1853. EXPECT_EQ('l', buf[1]);
  1854. EXPECT_EQ(1, strm.read(buf, 1));
  1855. EXPECT_EQ('o', buf[0]);
  1856. EXPECT_EQ(0, strm.read(buf, 1));
  1857. }
  1858. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1859. auto host = "www.httpwatch.com";
  1860. auto ip = hosted_at(host);
  1861. EXPECT_EQ("23.96.13.243", ip);
  1862. std::vector<std::string> addrs;
  1863. hosted_at(host, addrs);
  1864. EXPECT_EQ(1u, addrs.size());
  1865. }
  1866. #if 0 // It depends on each test environment...
  1867. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1868. auto host = "www.youtube.com";
  1869. std::vector<std::string> addrs;
  1870. hosted_at(host, addrs);
  1871. EXPECT_EQ(20u, addrs.size());
  1872. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1873. EXPECT_TRUE(it != addrs.end());
  1874. }
  1875. #endif
  1876. class ChunkedEncodingTest : public ::testing::Test {
  1877. protected:
  1878. ChunkedEncodingTest()
  1879. : cli_(HOST, PORT)
  1880. #ifdef CPPHTTPLIB_SSL_ENABLED
  1881. ,
  1882. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1883. #endif
  1884. {
  1885. cli_.set_connection_timeout(2);
  1886. #ifdef CPPHTTPLIB_SSL_ENABLED
  1887. cli_.enable_server_certificate_verification(false);
  1888. #endif
  1889. }
  1890. virtual void SetUp() {
  1891. read_file("./image.jpg", image_data_);
  1892. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1893. res.set_content("Hello World!", "text/plain");
  1894. });
  1895. svr_.Get(
  1896. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1897. res.set_chunked_content_provider(
  1898. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1899. size_t remaining = image_data_.size() - offset;
  1900. if (remaining == 0) {
  1901. sink.done();
  1902. } else {
  1903. constexpr size_t CHUNK_SIZE = 1024;
  1904. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1905. sink.write(&image_data_[offset], send_size);
  1906. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1907. }
  1908. return true;
  1909. });
  1910. });
  1911. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1912. svr_.wait_until_ready();
  1913. }
  1914. virtual void TearDown() {
  1915. svr_.stop();
  1916. if (!request_threads_.empty()) {
  1917. std::this_thread::sleep_for(std::chrono::seconds(1));
  1918. for (auto &t : request_threads_) {
  1919. t.join();
  1920. }
  1921. }
  1922. t_.join();
  1923. }
  1924. #ifdef CPPHTTPLIB_SSL_ENABLED
  1925. SSLClient cli_;
  1926. SSLServer svr_;
  1927. #else
  1928. Client cli_;
  1929. Server svr_;
  1930. #endif
  1931. thread t_;
  1932. std::vector<thread> request_threads_;
  1933. std::string image_data_;
  1934. };
  1935. TEST_F(ChunkedEncodingTest, NormalGet) {
  1936. auto res = cli_.Get("/chunked");
  1937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1938. std::string out;
  1939. read_file("./image.jpg", out);
  1940. EXPECT_EQ(StatusCode::OK_200, res->status);
  1941. EXPECT_EQ(out, res->body);
  1942. }
  1943. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1944. std::string body;
  1945. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1946. body.append(data, data_length);
  1947. return true;
  1948. });
  1949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1950. std::string out;
  1951. read_file("./image.jpg", out);
  1952. EXPECT_EQ(StatusCode::OK_200, res->status);
  1953. EXPECT_EQ(out, body);
  1954. }
  1955. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1956. std::string body;
  1957. auto res = cli_.Get(
  1958. "/chunked",
  1959. [&](const Response &response) {
  1960. EXPECT_EQ(StatusCode::OK_200, response.status);
  1961. return true;
  1962. },
  1963. [&](const char *data, size_t data_length) {
  1964. body.append(data, data_length);
  1965. return true;
  1966. });
  1967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1968. std::string out;
  1969. read_file("./image.jpg", out);
  1970. EXPECT_EQ(StatusCode::OK_200, res->status);
  1971. EXPECT_EQ(out, body);
  1972. }
  1973. TEST(RangeTest, FromHTTPBin_Online) {
  1974. auto host = "httpbingo.org";
  1975. auto path = std::string{"/range/32"};
  1976. #ifdef CPPHTTPLIB_SSL_ENABLED
  1977. auto port = 443;
  1978. SSLClient cli(host, port);
  1979. #else
  1980. auto port = 80;
  1981. Client cli(host, port);
  1982. #endif
  1983. cli.set_connection_timeout(5);
  1984. {
  1985. auto res = cli.Get(path);
  1986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1987. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1988. EXPECT_EQ(StatusCode::OK_200, res->status);
  1989. }
  1990. {
  1991. Headers headers = {make_range_header({{1, -1}})};
  1992. auto res = cli.Get(path, headers);
  1993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1994. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1995. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1996. }
  1997. {
  1998. Headers headers = {make_range_header({{1, 10}})};
  1999. auto res = cli.Get(path, headers);
  2000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2001. EXPECT_EQ("bcdefghijk", res->body);
  2002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2003. }
  2004. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2005. // entire resource, while the original httpbin returned 200. Both are
  2006. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2007. {
  2008. Headers headers = {make_range_header({{0, 31}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. {
  2016. Headers headers = {make_range_header({{0, -1}})};
  2017. auto res = cli.Get(path, headers);
  2018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2019. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2020. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2021. res->status == StatusCode::PartialContent_206);
  2022. }
  2023. // go-httpbin returns 206 with clamped range for over-range requests,
  2024. // while the original httpbin returned 416. Both behaviors are observed
  2025. // in real servers, so we only verify the request succeeds.
  2026. {
  2027. Headers headers = {make_range_header({{0, 32}})};
  2028. auto res = cli.Get(path, headers);
  2029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2030. }
  2031. }
  2032. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2033. auto host = "unresolvableaddress.local";
  2034. auto path = std::string{"/"};
  2035. #ifdef CPPHTTPLIB_SSL_ENABLED
  2036. auto port = 443;
  2037. SSLClient cli(host, port);
  2038. #else
  2039. auto port = 80;
  2040. Client cli(host, port);
  2041. #endif
  2042. cli.set_connection_timeout(1);
  2043. {
  2044. auto res = cli.Get(path);
  2045. ASSERT_FALSE(res);
  2046. }
  2047. std::this_thread::sleep_for(std::chrono::seconds(8));
  2048. }
  2049. #if defined(__linux__) && defined(__GLIBC__) && \
  2050. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2051. // Forward declaration: in split builds split.py strips `inline` and moves the
  2052. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2053. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2054. // against the symbol in both header-only and split builds.
  2055. namespace httplib {
  2056. namespace detail {
  2057. int getaddrinfo_with_timeout(const char *node, const char *service,
  2058. const struct addrinfo *hints,
  2059. struct addrinfo **res, time_t timeout_sec);
  2060. } // namespace detail
  2061. } // namespace httplib
  2062. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2063. //
  2064. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2065. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2066. // gai_suspend() call hits the connection timeout the function calls
  2067. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2068. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2069. // still alive and still references the now-destroyed stack frame.
  2070. //
  2071. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2072. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2073. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2074. // and runs them in a container.
  2075. namespace {
  2076. bool should_run_issue_2431_tests() {
  2077. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2078. return v && *v && std::string(v) != "0";
  2079. }
  2080. std::string unique_unresolvable_host(int n) {
  2081. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2082. // glibc still asks the configured nameserver — which is exactly the path
  2083. // we want to exercise. A unique label per call avoids the resolver cache.
  2084. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2085. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2086. std::to_string(n) + ".invalid";
  2087. }
  2088. } // namespace
  2089. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2090. if (!should_run_issue_2431_tests()) {
  2091. GTEST_SKIP()
  2092. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2093. }
  2094. for (int i = 0; i < 8; ++i) {
  2095. struct addrinfo hints;
  2096. memset(&hints, 0, sizeof(hints));
  2097. hints.ai_family = AF_UNSPEC;
  2098. hints.ai_socktype = SOCK_STREAM;
  2099. auto host = unique_unresolvable_host(i);
  2100. struct addrinfo *result = nullptr;
  2101. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2102. &result, /*timeout_sec=*/1);
  2103. if (rc == 0 && result) { freeaddrinfo(result); }
  2104. }
  2105. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2106. // stack region they still believe holds their gaicb.
  2107. std::this_thread::sleep_for(std::chrono::seconds(3));
  2108. }
  2109. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2110. if (!should_run_issue_2431_tests()) {
  2111. GTEST_SKIP()
  2112. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2113. }
  2114. std::atomic<bool> stop{false};
  2115. std::vector<std::thread> threads;
  2116. for (int t = 0; t < 8; ++t) {
  2117. threads.emplace_back([t, &stop] {
  2118. int i = 0;
  2119. while (!stop.load(std::memory_order_relaxed)) {
  2120. struct addrinfo hints;
  2121. memset(&hints, 0, sizeof(hints));
  2122. hints.ai_family = AF_UNSPEC;
  2123. hints.ai_socktype = SOCK_STREAM;
  2124. auto host = unique_unresolvable_host(t * 100000 + i++);
  2125. struct addrinfo *result = nullptr;
  2126. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2127. &result, /*timeout_sec=*/1);
  2128. if (rc == 0 && result) { freeaddrinfo(result); }
  2129. }
  2130. });
  2131. }
  2132. std::this_thread::sleep_for(std::chrono::seconds(8));
  2133. stop.store(true, std::memory_order_relaxed);
  2134. for (auto &th : threads) {
  2135. th.join();
  2136. }
  2137. std::this_thread::sleep_for(std::chrono::seconds(3));
  2138. }
  2139. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2140. if (!should_run_issue_2431_tests()) {
  2141. GTEST_SKIP()
  2142. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2143. }
  2144. std::atomic<bool> stop{false};
  2145. std::vector<std::thread> threads;
  2146. for (int t = 0; t < 8; ++t) {
  2147. threads.emplace_back([t, &stop] {
  2148. int i = 0;
  2149. while (!stop.load(std::memory_order_relaxed)) {
  2150. auto host = unique_unresolvable_host(t * 100000 + i++);
  2151. Client cli(host, 80);
  2152. cli.set_connection_timeout(1, 0);
  2153. cli.set_read_timeout(1, 0);
  2154. cli.set_write_timeout(1, 0);
  2155. (void)cli.Get("/");
  2156. }
  2157. });
  2158. }
  2159. std::this_thread::sleep_for(std::chrono::seconds(8));
  2160. stop.store(true, std::memory_order_relaxed);
  2161. for (auto &th : threads) {
  2162. th.join();
  2163. }
  2164. std::this_thread::sleep_for(std::chrono::seconds(3));
  2165. }
  2166. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2167. TEST(ConnectionErrorTest, InvalidHost) {
  2168. auto host = "-abcde.com";
  2169. #ifdef CPPHTTPLIB_SSL_ENABLED
  2170. auto port = 443;
  2171. SSLClient cli(host, port);
  2172. #else
  2173. auto port = 80;
  2174. Client cli(host, port);
  2175. #endif
  2176. cli.set_connection_timeout(std::chrono::seconds(2));
  2177. auto res = cli.Get("/");
  2178. ASSERT_TRUE(!res);
  2179. EXPECT_EQ(Error::Connection, res.error());
  2180. }
  2181. TEST(ConnectionErrorTest, InvalidHost2) {
  2182. auto host = "httpcan.org/";
  2183. #ifdef CPPHTTPLIB_SSL_ENABLED
  2184. SSLClient cli(host);
  2185. #else
  2186. Client cli(host);
  2187. #endif
  2188. cli.set_connection_timeout(std::chrono::seconds(2));
  2189. auto res = cli.Get("/");
  2190. ASSERT_TRUE(!res);
  2191. EXPECT_EQ(Error::Connection, res.error());
  2192. }
  2193. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2194. auto host = "httpcan.org/";
  2195. #ifdef CPPHTTPLIB_SSL_ENABLED
  2196. SSLClient cli(host);
  2197. #else
  2198. Client cli(host);
  2199. #endif
  2200. cli.set_connection_timeout(std::chrono::seconds(2));
  2201. auto res = cli.Get("/");
  2202. ASSERT_TRUE(!res);
  2203. stringstream s;
  2204. s << "error code: " << res.error();
  2205. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2206. }
  2207. TEST(ConnectionErrorTest, InvalidPort) {
  2208. auto host = "localhost";
  2209. auto port = 44380;
  2210. #ifdef CPPHTTPLIB_SSL_ENABLED
  2211. SSLClient cli(host, port);
  2212. #else
  2213. Client cli(host, port);
  2214. #endif
  2215. cli.set_connection_timeout(std::chrono::seconds(2));
  2216. auto res = cli.Get("/");
  2217. ASSERT_TRUE(!res);
  2218. EXPECT_TRUE(Error::Connection == res.error() ||
  2219. Error::ConnectionTimeout == res.error());
  2220. }
  2221. TEST(ConnectionErrorTest, Timeout_Online) {
  2222. auto host = "google.com";
  2223. #ifdef CPPHTTPLIB_SSL_ENABLED
  2224. auto port = 44380;
  2225. SSLClient cli(host, port);
  2226. #else
  2227. auto port = 8080;
  2228. Client cli(host, port);
  2229. #endif
  2230. cli.set_connection_timeout(std::chrono::seconds(2));
  2231. // only probe one address type so that the error reason
  2232. // correlates to the timed-out IPv4, not the unsupported
  2233. // IPv6 connection attempt
  2234. cli.set_address_family(AF_INET);
  2235. auto res = cli.Get("/");
  2236. ASSERT_TRUE(!res);
  2237. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2238. }
  2239. TEST(CancelTest, NoCancel_Online) {
  2240. auto host = "httpbingo.org";
  2241. auto path = std::string{"/range/32"};
  2242. #ifdef CPPHTTPLIB_SSL_ENABLED
  2243. auto port = 443;
  2244. SSLClient cli(host, port);
  2245. #else
  2246. auto port = 80;
  2247. Client cli(host, port);
  2248. #endif
  2249. cli.set_connection_timeout(std::chrono::seconds(5));
  2250. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2252. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2253. EXPECT_EQ(StatusCode::OK_200, res->status);
  2254. }
  2255. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2256. // Use /bytes with a large payload so that the DownloadProgress callback
  2257. // (which only fires for Content-Length responses) is invoked before the
  2258. // entire body is received, giving cancellation a chance to fire.
  2259. auto host = "httpbingo.org";
  2260. auto path = std::string{"/bytes/524288"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2269. cli.set_connection_timeout(std::chrono::seconds(5));
  2270. ASSERT_TRUE(!res);
  2271. EXPECT_EQ(Error::Canceled, res.error());
  2272. }
  2273. TEST(CancelTest, WithCancelLargePayload_Online) {
  2274. auto host = "httpbingo.org";
  2275. auto path = std::string{"/bytes/524288"};
  2276. #ifdef CPPHTTPLIB_SSL_ENABLED
  2277. auto port = 443;
  2278. SSLClient cli(host, port);
  2279. #else
  2280. auto port = 80;
  2281. Client cli(host, port);
  2282. #endif
  2283. cli.set_connection_timeout(std::chrono::seconds(5));
  2284. uint32_t count = 0;
  2285. auto res =
  2286. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2287. ASSERT_TRUE(!res);
  2288. EXPECT_EQ(Error::Canceled, res.error());
  2289. }
  2290. TEST(CancelTest, NoCancelPost) {
  2291. Server svr;
  2292. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2293. res.set_content("Hello World!", "text/plain");
  2294. });
  2295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2296. auto se = detail::scope_exit([&] {
  2297. svr.stop();
  2298. thread.join();
  2299. ASSERT_FALSE(svr.is_running());
  2300. });
  2301. svr.wait_until_ready();
  2302. Client cli(HOST, PORT);
  2303. cli.set_connection_timeout(std::chrono::seconds(5));
  2304. auto res =
  2305. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2306. "application/json", [](uint64_t, uint64_t) { return true; });
  2307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2308. EXPECT_EQ("Hello World!", res->body);
  2309. EXPECT_EQ(StatusCode::OK_200, res->status);
  2310. }
  2311. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2312. Server svr;
  2313. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2314. res.set_content("Hello World!", "text/plain");
  2315. });
  2316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2317. auto se = detail::scope_exit([&] {
  2318. svr.stop();
  2319. thread.join();
  2320. ASSERT_FALSE(svr.is_running());
  2321. });
  2322. svr.wait_until_ready();
  2323. Client cli(HOST, PORT);
  2324. cli.set_connection_timeout(std::chrono::seconds(5));
  2325. auto res =
  2326. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2327. "application/json", [](uint64_t, uint64_t) { return false; });
  2328. ASSERT_TRUE(!res);
  2329. EXPECT_EQ(Error::Canceled, res.error());
  2330. }
  2331. TEST(CancelTest, WithCancelLargePayloadPost) {
  2332. Server svr;
  2333. svr.set_payload_max_length(200 * 1024 * 1024);
  2334. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2335. res.set_content(LARGE_DATA, "text/plain");
  2336. });
  2337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. thread.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. Client cli(HOST, PORT);
  2345. cli.set_payload_max_length(200 * 1024 * 1024);
  2346. cli.set_connection_timeout(std::chrono::seconds(5));
  2347. auto res =
  2348. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2349. "application/json", [](uint64_t, uint64_t) { return false; });
  2350. ASSERT_TRUE(!res);
  2351. EXPECT_EQ(Error::Canceled, res.error());
  2352. }
  2353. TEST(CancelTest, NoCancelPut) {
  2354. Server svr;
  2355. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2356. res.set_content("Hello World!", "text/plain");
  2357. });
  2358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2359. auto se = detail::scope_exit([&] {
  2360. svr.stop();
  2361. thread.join();
  2362. ASSERT_FALSE(svr.is_running());
  2363. });
  2364. svr.wait_until_ready();
  2365. Client cli(HOST, PORT);
  2366. cli.set_connection_timeout(std::chrono::seconds(5));
  2367. auto res =
  2368. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2369. "application/json", [](uint64_t, uint64_t) { return true; });
  2370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2371. EXPECT_EQ("Hello World!", res->body);
  2372. EXPECT_EQ(StatusCode::OK_200, res->status);
  2373. }
  2374. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2375. Server svr;
  2376. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2377. res.set_content("Hello World!", "text/plain");
  2378. });
  2379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2380. auto se = detail::scope_exit([&] {
  2381. svr.stop();
  2382. thread.join();
  2383. ASSERT_FALSE(svr.is_running());
  2384. });
  2385. svr.wait_until_ready();
  2386. Client cli(HOST, PORT);
  2387. cli.set_connection_timeout(std::chrono::seconds(5));
  2388. auto res =
  2389. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2390. "application/json", [](uint64_t, uint64_t) { return false; });
  2391. ASSERT_TRUE(!res);
  2392. EXPECT_EQ(Error::Canceled, res.error());
  2393. }
  2394. TEST(CancelTest, WithCancelLargePayloadPut) {
  2395. Server svr;
  2396. svr.set_payload_max_length(200 * 1024 * 1024);
  2397. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2398. res.set_content(LARGE_DATA, "text/plain");
  2399. });
  2400. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2401. auto se = detail::scope_exit([&] {
  2402. svr.stop();
  2403. thread.join();
  2404. ASSERT_FALSE(svr.is_running());
  2405. });
  2406. svr.wait_until_ready();
  2407. Client cli(HOST, PORT);
  2408. cli.set_payload_max_length(200 * 1024 * 1024);
  2409. cli.set_connection_timeout(std::chrono::seconds(5));
  2410. auto res =
  2411. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2412. "application/json", [](uint64_t, uint64_t) { return false; });
  2413. ASSERT_TRUE(!res);
  2414. EXPECT_EQ(Error::Canceled, res.error());
  2415. }
  2416. TEST(CancelTest, NoCancelPatch) {
  2417. Server svr;
  2418. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2419. res.set_content("Hello World!", "text/plain");
  2420. });
  2421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2422. auto se = detail::scope_exit([&] {
  2423. svr.stop();
  2424. thread.join();
  2425. ASSERT_FALSE(svr.is_running());
  2426. });
  2427. svr.wait_until_ready();
  2428. Client cli(HOST, PORT);
  2429. cli.set_connection_timeout(std::chrono::seconds(5));
  2430. auto res =
  2431. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2432. "application/json", [](uint64_t, uint64_t) { return true; });
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ("Hello World!", res->body);
  2435. EXPECT_EQ(StatusCode::OK_200, res->status);
  2436. }
  2437. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2438. Server svr;
  2439. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2440. res.set_content("Hello World!", "text/plain");
  2441. });
  2442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2443. auto se = detail::scope_exit([&] {
  2444. svr.stop();
  2445. thread.join();
  2446. ASSERT_FALSE(svr.is_running());
  2447. });
  2448. svr.wait_until_ready();
  2449. Client cli(HOST, PORT);
  2450. cli.set_connection_timeout(std::chrono::seconds(5));
  2451. auto res =
  2452. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2453. "application/json", [](uint64_t, uint64_t) { return false; });
  2454. ASSERT_TRUE(!res);
  2455. EXPECT_EQ(Error::Canceled, res.error());
  2456. }
  2457. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2458. Server svr;
  2459. svr.set_payload_max_length(200 * 1024 * 1024);
  2460. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2461. res.set_content(LARGE_DATA, "text/plain");
  2462. });
  2463. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2464. auto se = detail::scope_exit([&] {
  2465. svr.stop();
  2466. thread.join();
  2467. ASSERT_FALSE(svr.is_running());
  2468. });
  2469. svr.wait_until_ready();
  2470. Client cli(HOST, PORT);
  2471. cli.set_payload_max_length(200 * 1024 * 1024);
  2472. cli.set_connection_timeout(std::chrono::seconds(5));
  2473. auto res =
  2474. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2475. "application/json", [](uint64_t, uint64_t) { return false; });
  2476. ASSERT_TRUE(!res);
  2477. EXPECT_EQ(Error::Canceled, res.error());
  2478. }
  2479. TEST(CancelTest, NoCancelDelete) {
  2480. Server svr;
  2481. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2482. res.set_content("Hello World!", "text/plain");
  2483. });
  2484. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2485. auto se = detail::scope_exit([&] {
  2486. svr.stop();
  2487. thread.join();
  2488. ASSERT_FALSE(svr.is_running());
  2489. });
  2490. svr.wait_until_ready();
  2491. Client cli(HOST, PORT);
  2492. cli.set_connection_timeout(std::chrono::seconds(5));
  2493. auto res =
  2494. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2495. "application/json", [](uint64_t, uint64_t) { return true; });
  2496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2497. EXPECT_EQ("Hello World!", res->body);
  2498. EXPECT_EQ(StatusCode::OK_200, res->status);
  2499. }
  2500. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2501. Server svr;
  2502. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2503. res.set_content("Hello World!", "text/plain");
  2504. });
  2505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2506. auto se = detail::scope_exit([&] {
  2507. svr.stop();
  2508. thread.join();
  2509. ASSERT_FALSE(svr.is_running());
  2510. });
  2511. svr.wait_until_ready();
  2512. Client cli(HOST, PORT);
  2513. cli.set_connection_timeout(std::chrono::seconds(5));
  2514. auto res =
  2515. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2516. "application/json", [](uint64_t, uint64_t) { return false; });
  2517. ASSERT_TRUE(!res);
  2518. EXPECT_EQ(Error::Canceled, res.error());
  2519. }
  2520. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2521. Server svr;
  2522. svr.set_payload_max_length(200 * 1024 * 1024);
  2523. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2524. res.set_content(LARGE_DATA, "text/plain");
  2525. });
  2526. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2527. auto se = detail::scope_exit([&] {
  2528. svr.stop();
  2529. thread.join();
  2530. ASSERT_FALSE(svr.is_running());
  2531. });
  2532. svr.wait_until_ready();
  2533. Client cli(HOST, PORT);
  2534. cli.set_payload_max_length(200 * 1024 * 1024);
  2535. cli.set_connection_timeout(std::chrono::seconds(5));
  2536. auto res =
  2537. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2538. "application/json", [](uint64_t, uint64_t) { return false; });
  2539. ASSERT_TRUE(!res);
  2540. EXPECT_EQ(Error::Canceled, res.error());
  2541. }
  2542. static std::string remove_whitespace(const std::string &input) {
  2543. std::string output;
  2544. output.reserve(input.size());
  2545. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2546. [](unsigned char c) { return !std::isspace(c); });
  2547. return output;
  2548. }
  2549. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2550. auto host = "httpbingo.org";
  2551. auto path = std::string{"/basic-auth/hello/world"};
  2552. #ifdef CPPHTTPLIB_SSL_ENABLED
  2553. auto port = 443;
  2554. SSLClient cli(host, port);
  2555. #else
  2556. auto port = 80;
  2557. Client cli(host, port);
  2558. #endif
  2559. {
  2560. auto res = cli.Get(path);
  2561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2562. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2563. }
  2564. {
  2565. auto res = cli.Get(
  2566. path, Headers{make_basic_authentication_header("hello", "world")});
  2567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2568. auto body = remove_whitespace(res->body);
  2569. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2570. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2571. EXPECT_EQ(StatusCode::OK_200, res->status);
  2572. }
  2573. {
  2574. cli.set_basic_auth("hello", "world");
  2575. auto res = cli.Get(path);
  2576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2577. auto body = remove_whitespace(res->body);
  2578. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2579. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2580. EXPECT_EQ(StatusCode::OK_200, res->status);
  2581. }
  2582. {
  2583. cli.set_basic_auth("hello", "bad");
  2584. auto res = cli.Get(path);
  2585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2586. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2587. }
  2588. {
  2589. cli.set_basic_auth("bad", "world");
  2590. auto res = cli.Get(path);
  2591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2592. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2593. }
  2594. }
  2595. #ifdef CPPHTTPLIB_SSL_ENABLED
  2596. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2597. auto host = "httpbingo.org";
  2598. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2599. auto paths = std::vector<std::string>{
  2600. "/digest-auth/auth/hello/world/MD5",
  2601. "/digest-auth/auth/hello/world/SHA-256",
  2602. };
  2603. auto port = 443;
  2604. SSLClient cli(host, port);
  2605. {
  2606. auto res = cli.Get(unauth_path);
  2607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2608. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2609. }
  2610. {
  2611. cli.set_digest_auth("hello", "world");
  2612. for (const auto &path : paths) {
  2613. auto res = cli.Get(path.c_str());
  2614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2615. auto body = remove_whitespace(res->body);
  2616. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2617. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2618. EXPECT_EQ(StatusCode::OK_200, res->status);
  2619. }
  2620. cli.set_digest_auth("hello", "bad");
  2621. for (const auto &path : paths) {
  2622. auto res = cli.Get(path.c_str());
  2623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2624. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2625. }
  2626. }
  2627. }
  2628. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2629. // comma-separated list of challenges, and each challenge may itself carry a
  2630. // comma-separated auth-param list, so a server can legally offer Basic
  2631. // before Digest, either as two field lines or packed into one. Runs one 401
  2632. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2633. // value() joins them in receipt order) and checks that the retry carries a
  2634. // well-formed Digest Authorization header naming expected_realm.
  2635. static void
  2636. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2637. const std::string &expected_realm) {
  2638. std::atomic<int> hits{0};
  2639. Server svr;
  2640. svr.Get("/x", [&](const Request &req, Response &res) {
  2641. if (++hits == 1) {
  2642. res.status = StatusCode::Unauthorized_401;
  2643. for (const auto &challenge : challenges) {
  2644. res.set_header("WWW-Authenticate", challenge);
  2645. }
  2646. } else {
  2647. auto authorization = req.get_header_value("Authorization");
  2648. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2649. EXPECT_NE(std::string::npos,
  2650. authorization.find("realm=\"" + expected_realm + "\""));
  2651. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2652. res.set_content("ok", "text/plain");
  2653. }
  2654. });
  2655. auto port = svr.bind_to_any_port(HOST);
  2656. std::thread t([&]() { svr.listen_after_bind(); });
  2657. auto se = detail::scope_exit([&] {
  2658. svr.stop();
  2659. t.join();
  2660. });
  2661. svr.wait_until_ready();
  2662. Client cli(HOST, port);
  2663. cli.set_digest_auth("hello", "world");
  2664. auto res = cli.Get("/x");
  2665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2666. EXPECT_EQ(2, hits.load());
  2667. }
  2668. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2669. static const char *kDigestChallenge =
  2670. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2671. "algorithm=MD5";
  2672. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2673. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2674. "testrealm");
  2675. }
  2676. // Same challenge list with the schemes in the opposite order, to make sure
  2677. // the fix above didn't just special-case "Basic first".
  2678. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2679. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2680. "testrealm");
  2681. }
  2682. // A comma inside a quoted auth-param value must not be mistaken for the
  2683. // separator between two challenges (or two auth-params).
  2684. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2685. run_digest_challenge_list_test(
  2686. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2687. "algorithm=MD5"},
  2688. "test,realm");
  2689. }
  2690. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2691. // make_digest_authentication_header() dereferences both unconditionally, so
  2692. // a server sending a challenge missing either one must not be treated as
  2693. // usable -- doing so used to crash the client with std::out_of_range.
  2694. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2695. Server svr;
  2696. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2697. res.status = StatusCode::Unauthorized_401;
  2698. res.set_header("WWW-Authenticate", challenge);
  2699. });
  2700. auto port = svr.bind_to_any_port(HOST);
  2701. std::thread t([&]() { svr.listen_after_bind(); });
  2702. auto se = detail::scope_exit([&] {
  2703. svr.stop();
  2704. t.join();
  2705. });
  2706. svr.wait_until_ready();
  2707. Client cli(HOST, port);
  2708. cli.set_digest_auth("hello", "world");
  2709. auto res = cli.Get("/x");
  2710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2711. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2712. }
  2713. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2714. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2715. }
  2716. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2717. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2718. }
  2719. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2720. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2721. }
  2722. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2723. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2724. // when storing the values, so the header builder has to re-escape them (and
  2725. // keep algorithm a bare token); otherwise the value breaks out of its
  2726. // quoted-string and injects extra auth-params into the client's Authorization.
  2727. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2728. std::atomic<int> hits{0};
  2729. std::string authorization;
  2730. Server svr;
  2731. svr.Get("/x", [&](const Request &req, Response &res) {
  2732. if (++hits == 1) {
  2733. res.status = StatusCode::Unauthorized_401;
  2734. // On the wire the quotes embedded in the values are backslash-escaped.
  2735. res.set_header("WWW-Authenticate",
  2736. "Digest realm=\"testrealm\", "
  2737. "nonce=\"n\\\"; injected=\\\"x\", "
  2738. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2739. } else {
  2740. authorization = req.get_header_value("Authorization");
  2741. res.set_content("ok", "text/plain");
  2742. }
  2743. });
  2744. auto port = svr.bind_to_any_port(HOST);
  2745. std::thread t([&]() { svr.listen_after_bind(); });
  2746. auto se = detail::scope_exit([&] {
  2747. svr.stop();
  2748. t.join();
  2749. });
  2750. svr.wait_until_ready();
  2751. Client cli(HOST, port);
  2752. cli.set_digest_auth("hello", "world");
  2753. auto res = cli.Get("/x");
  2754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2755. EXPECT_EQ(2, hits.load());
  2756. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2757. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2758. // inside its quoted-string rather than starting an "injected" auth-param.
  2759. EXPECT_NE(std::string::npos,
  2760. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2761. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2762. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2763. }
  2764. #endif
  2765. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2766. auto host = "google.com";
  2767. auto another_host = "example.com";
  2768. auto wrong_ip = "0.0.0.0";
  2769. #ifdef CPPHTTPLIB_SSL_ENABLED
  2770. SSLClient cli(host);
  2771. #else
  2772. Client cli(host);
  2773. #endif
  2774. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2775. auto res = cli.Get("/");
  2776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2777. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2778. }
  2779. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2780. auto host = "google.com";
  2781. auto wrong_ip = "0.0.0.0";
  2782. #ifdef CPPHTTPLIB_SSL_ENABLED
  2783. SSLClient cli(host);
  2784. #else
  2785. Client cli(host);
  2786. #endif
  2787. cli.set_hostname_addr_map({{host, wrong_ip}});
  2788. auto res = cli.Get("/");
  2789. ASSERT_TRUE(!res);
  2790. EXPECT_EQ(Error::Connection, res.error());
  2791. }
  2792. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2793. // A mapped value that is not an IP literal must be resolved. "localhost"
  2794. // resolves from the hosts file, so this test needs no external DNS.
  2795. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2796. auto host = "target.invalid";
  2797. Server svr;
  2798. std::string received_host;
  2799. svr.Get("/hi", [&](const Request &req, Response &res) {
  2800. received_host = req.get_header_value("Host");
  2801. res.set_content("Hello World!", "text/plain");
  2802. });
  2803. auto port = svr.bind_to_any_port(HOST);
  2804. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(host, port);
  2812. cli.set_hostname_addr_map({{host, HOST}});
  2813. auto res = cli.Get("/hi");
  2814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2815. EXPECT_EQ(StatusCode::OK_200, res->status);
  2816. // The mapping only redirects the connection; the identity stays host_.
  2817. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2818. }
  2819. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2820. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2821. auto host = "target.invalid";
  2822. Server svr;
  2823. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2824. res.set_content("Hello World!", "text/plain");
  2825. });
  2826. auto port = svr.bind_to_any_port("127.0.0.1");
  2827. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2828. auto se = detail::scope_exit([&] {
  2829. svr.stop();
  2830. thread.join();
  2831. ASSERT_FALSE(svr.is_running());
  2832. });
  2833. svr.wait_until_ready();
  2834. Client cli(host, port);
  2835. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2836. auto res = cli.Get("/hi");
  2837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2838. EXPECT_EQ(StatusCode::OK_200, res->status);
  2839. }
  2840. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2841. // An empty mapped value must leave host_ as the connection target. Without
  2842. // that guard the empty value would become the host argument, getaddrinfo
  2843. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2844. // loopback - silently connecting somewhere the caller never asked for.
  2845. // The server listens on loopback, so such a fallback would succeed and is
  2846. // therefore observable as a failure of this test.
  2847. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2848. Server svr;
  2849. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2850. res.set_content("Hello World!", "text/plain");
  2851. });
  2852. auto port = svr.bind_to_any_port(HOST);
  2853. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2854. auto se = detail::scope_exit([&] {
  2855. svr.stop();
  2856. thread.join();
  2857. ASSERT_FALSE(svr.is_running());
  2858. });
  2859. svr.wait_until_ready();
  2860. Client cli(blackhole, port);
  2861. cli.set_hostname_addr_map({{blackhole, ""}});
  2862. cli.set_connection_timeout(1);
  2863. auto res = cli.Get("/hi");
  2864. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2865. }
  2866. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2867. auto host = "httpbingo.org";
  2868. auto path = std::string{"/absolute-redirect/3"};
  2869. #ifdef CPPHTTPLIB_SSL_ENABLED
  2870. SSLClient cli(host);
  2871. #else
  2872. Client cli(host);
  2873. #endif
  2874. cli.set_follow_location(true);
  2875. auto res = cli.Get(path);
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. TEST(RedirectTest, Redirect_Online) {
  2880. auto host = "httpbingo.org";
  2881. auto path = std::string{"/redirect/3"};
  2882. #ifdef CPPHTTPLIB_SSL_ENABLED
  2883. SSLClient cli(host);
  2884. #else
  2885. Client cli(host);
  2886. #endif
  2887. cli.set_follow_location(true);
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. EXPECT_EQ(StatusCode::OK_200, res->status);
  2891. }
  2892. TEST(RelativeRedirectTest, Redirect_Online) {
  2893. auto host = "httpbingo.org";
  2894. auto path = std::string{"/relative-redirect/3"};
  2895. #ifdef CPPHTTPLIB_SSL_ENABLED
  2896. SSLClient cli(host);
  2897. #else
  2898. Client cli(host);
  2899. #endif
  2900. cli.set_follow_location(true);
  2901. auto res = cli.Get(path);
  2902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2903. EXPECT_EQ(StatusCode::OK_200, res->status);
  2904. }
  2905. TEST(TooManyRedirectTest, Redirect_Online) {
  2906. auto host = "httpbingo.org";
  2907. auto path = std::string{"/redirect/21"};
  2908. #ifdef CPPHTTPLIB_SSL_ENABLED
  2909. SSLClient cli(host);
  2910. #else
  2911. Client cli(host);
  2912. #endif
  2913. cli.set_follow_location(true);
  2914. auto res = cli.Get(path);
  2915. ASSERT_TRUE(!res);
  2916. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2917. }
  2918. #ifdef CPPHTTPLIB_SSL_ENABLED
  2919. TEST(YahooRedirectTest, Redirect_Online) {
  2920. Client cli("yahoo.com");
  2921. auto res = cli.Get("/");
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2924. cli.set_follow_location(true);
  2925. res = cli.Get("/");
  2926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2927. EXPECT_EQ(StatusCode::OK_200, res->status);
  2928. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2929. }
  2930. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2931. #define REDIR_HOST "httpbingo.org"
  2932. #define REDIR_PATH "/redirect-to"
  2933. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2934. SSLClient cli(REDIR_HOST);
  2935. cli.set_follow_location(true);
  2936. auto res =
  2937. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ(StatusCode::OK_200, res->status);
  2940. }
  2941. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2942. SSLClient cli(REDIR_HOST);
  2943. cli.set_follow_location(true);
  2944. Params params;
  2945. params.emplace("url", "http://example.com");
  2946. params.emplace("status_code", "302");
  2947. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. }
  2951. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2952. SSLClient cli(REDIR_HOST);
  2953. cli.set_follow_location(true);
  2954. Params params;
  2955. params.emplace("url", "http://example.com");
  2956. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2958. EXPECT_EQ(StatusCode::OK_200, res->status);
  2959. }
  2960. TEST(UrlWithSpace, Redirect_Online) {
  2961. SSLClient cli("edge.forgecdn.net");
  2962. cli.set_follow_location(true);
  2963. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2965. EXPECT_EQ(StatusCode::OK_200, res->status);
  2966. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2967. }
  2968. #endif
  2969. #if !defined(_WIN32) && !defined(_WIN64)
  2970. TEST(ReceiveSignals, Signal) {
  2971. auto setupSignalHandlers = []() {
  2972. struct sigaction act;
  2973. sigemptyset(&act.sa_mask);
  2974. act.sa_flags = SA_SIGINFO;
  2975. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2976. switch (sig) {
  2977. case SIGINT:
  2978. default: break;
  2979. }
  2980. };
  2981. ::sigaction(SIGINT, &act, nullptr);
  2982. };
  2983. Server svr;
  2984. int port = 0;
  2985. auto thread = std::thread([&]() {
  2986. setupSignalHandlers();
  2987. port = svr.bind_to_any_port(HOST);
  2988. svr.listen_after_bind();
  2989. });
  2990. auto se = detail::scope_exit([&] {
  2991. svr.stop();
  2992. thread.join();
  2993. ASSERT_FALSE(svr.is_running());
  2994. });
  2995. svr.wait_until_ready();
  2996. ASSERT_TRUE(svr.is_running());
  2997. pthread_kill(thread.native_handle(), SIGINT);
  2998. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2999. ASSERT_TRUE(svr.is_running());
  3000. }
  3001. #endif
  3002. TEST(RedirectToDifferentPort, Redirect) {
  3003. Server svr1;
  3004. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3005. res.set_content("Hello World!", "text/plain");
  3006. });
  3007. int svr1_port = 0;
  3008. auto thread1 = std::thread([&]() {
  3009. svr1_port = svr1.bind_to_any_port(HOST);
  3010. svr1.listen_after_bind();
  3011. });
  3012. Server svr2;
  3013. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3014. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3015. });
  3016. int svr2_port = 0;
  3017. auto thread2 = std::thread([&]() {
  3018. svr2_port = svr2.bind_to_any_port(HOST);
  3019. svr2.listen_after_bind();
  3020. });
  3021. auto se = detail::scope_exit([&] {
  3022. svr2.stop();
  3023. thread2.join();
  3024. svr1.stop();
  3025. thread1.join();
  3026. ASSERT_FALSE(svr2.is_running());
  3027. ASSERT_FALSE(svr1.is_running());
  3028. });
  3029. svr1.wait_until_ready();
  3030. svr2.wait_until_ready();
  3031. Client cli("localhost", svr2_port);
  3032. cli.set_follow_location(true);
  3033. auto res = cli.Get("/2");
  3034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3035. EXPECT_EQ(StatusCode::OK_200, res->status);
  3036. EXPECT_EQ("Hello World!", res->body);
  3037. }
  3038. static void
  3039. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3040. Server svr1;
  3041. std::string captured_authorization;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_authorization = req.get_header_value("Authorization");
  3044. res.set_content("OK", "text/plain");
  3045. });
  3046. int svr1_port = 0;
  3047. auto thread1 = std::thread([&]() {
  3048. svr1_port = svr1.bind_to_any_port(HOST);
  3049. svr1.listen_after_bind();
  3050. });
  3051. Server svr2;
  3052. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3053. res.set_redirect(
  3054. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3055. });
  3056. int svr2_port = 0;
  3057. auto thread2 = std::thread([&]() {
  3058. svr2_port = svr2.bind_to_any_port(HOST);
  3059. svr2.listen_after_bind();
  3060. });
  3061. auto se = detail::scope_exit([&] {
  3062. svr2.stop();
  3063. thread2.join();
  3064. svr1.stop();
  3065. thread1.join();
  3066. ASSERT_FALSE(svr2.is_running());
  3067. ASSERT_FALSE(svr1.is_running());
  3068. });
  3069. svr1.wait_until_ready();
  3070. svr2.wait_until_ready();
  3071. Client cli("localhost", svr2_port);
  3072. cli.set_follow_location(true);
  3073. set_auth(cli);
  3074. auto res = cli.Get("/redir");
  3075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3076. EXPECT_EQ(StatusCode::OK_200, res->status);
  3077. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3078. EXPECT_TRUE(captured_authorization.empty());
  3079. }
  3080. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3081. TestDoNotForwardCredentialsOnRedirect(
  3082. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3083. }
  3084. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3085. TestDoNotForwardCredentialsOnRedirect(
  3086. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3087. }
  3088. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3089. Server svr1;
  3090. std::string captured_cookie;
  3091. bool target_hit = false;
  3092. svr1.Get("/target", [&](const Request &req, Response &res) {
  3093. captured_cookie = req.get_header_value("Cookie");
  3094. target_hit = true;
  3095. res.set_content("OK", "text/plain");
  3096. });
  3097. int svr1_port = 0;
  3098. auto thread1 = std::thread([&]() {
  3099. svr1_port = svr1.bind_to_any_port(HOST);
  3100. svr1.listen_after_bind();
  3101. });
  3102. Server svr2;
  3103. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3104. res.set_redirect(
  3105. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3106. });
  3107. int svr2_port = 0;
  3108. auto thread2 = std::thread([&]() {
  3109. svr2_port = svr2.bind_to_any_port(HOST);
  3110. svr2.listen_after_bind();
  3111. });
  3112. auto se = detail::scope_exit([&] {
  3113. svr2.stop();
  3114. thread2.join();
  3115. svr1.stop();
  3116. thread1.join();
  3117. ASSERT_FALSE(svr2.is_running());
  3118. ASSERT_FALSE(svr1.is_running());
  3119. });
  3120. svr1.wait_until_ready();
  3121. svr2.wait_until_ready();
  3122. Client cli("localhost", svr2_port);
  3123. cli.set_follow_location(true);
  3124. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3125. auto res = cli.Get("/redir", headers);
  3126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3127. EXPECT_EQ(StatusCode::OK_200, res->status);
  3128. EXPECT_TRUE(target_hit);
  3129. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3130. EXPECT_TRUE(captured_cookie.empty());
  3131. }
  3132. TEST(RedirectToSamePort, ForwardCookie) {
  3133. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3134. // header so that ordinary session flows keep working.
  3135. Server svr;
  3136. std::string captured_cookie;
  3137. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3138. res.set_redirect("/target", 302);
  3139. });
  3140. svr.Get("/target", [&](const Request &req, Response &res) {
  3141. captured_cookie = req.get_header_value("Cookie");
  3142. res.set_content("OK", "text/plain");
  3143. });
  3144. auto port = svr.bind_to_any_port(HOST);
  3145. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3146. auto se = detail::scope_exit([&] {
  3147. svr.stop();
  3148. thread.join();
  3149. ASSERT_FALSE(svr.is_running());
  3150. });
  3151. svr.wait_until_ready();
  3152. Client cli(HOST, port);
  3153. cli.set_follow_location(true);
  3154. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3155. auto res = cli.Get("/redir", headers);
  3156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3157. EXPECT_EQ(StatusCode::OK_200, res->status);
  3158. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3159. }
  3160. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3161. Server svr;
  3162. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3163. // Port number that overflows int — should not crash
  3164. res.set_redirect("http://localhost:99999999999999999999/target");
  3165. });
  3166. auto port = svr.bind_to_any_port(HOST);
  3167. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3168. auto se = detail::scope_exit([&] {
  3169. svr.stop();
  3170. thread.join();
  3171. ASSERT_FALSE(svr.is_running());
  3172. });
  3173. svr.wait_until_ready();
  3174. Client cli(HOST, port);
  3175. cli.set_follow_location(true);
  3176. auto res = cli.Get("/redir");
  3177. // Should fail gracefully, not crash (no valid response due to bad port)
  3178. EXPECT_FALSE(res);
  3179. }
  3180. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3181. Server svr;
  3182. auto port = svr.bind_to_any_port(HOST);
  3183. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3184. // The server's own port followed by junk must not be followed
  3185. res.set_redirect("http://" + std::string(HOST) + ":" +
  3186. std::to_string(port) + "junk/target");
  3187. });
  3188. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3189. res.set_content("target", "text/plain");
  3190. });
  3191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3192. auto se = detail::scope_exit([&] {
  3193. svr.stop();
  3194. thread.join();
  3195. ASSERT_FALSE(svr.is_running());
  3196. });
  3197. svr.wait_until_ready();
  3198. Client cli(HOST, port);
  3199. cli.set_follow_location(true);
  3200. auto res = cli.Get("/redir");
  3201. EXPECT_FALSE(res);
  3202. }
  3203. TEST(RedirectFromPageWithContent, Redirect) {
  3204. Server svr;
  3205. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3206. res.set_content("___", "text/plain");
  3207. res.set_redirect("/2");
  3208. });
  3209. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3210. res.set_content("Hello World!", "text/plain");
  3211. });
  3212. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3213. auto se = detail::scope_exit([&] {
  3214. svr.stop();
  3215. th.join();
  3216. ASSERT_FALSE(svr.is_running());
  3217. });
  3218. svr.wait_until_ready();
  3219. {
  3220. Client cli("localhost", PORT);
  3221. cli.set_follow_location(true);
  3222. std::string body;
  3223. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3224. body.append(data, data_length);
  3225. return true;
  3226. });
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("Hello World!", body);
  3230. }
  3231. {
  3232. Client cli("localhost", PORT);
  3233. std::string body;
  3234. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3235. body.append(data, data_length);
  3236. return true;
  3237. });
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::Found_302, res->status);
  3240. EXPECT_EQ("___", body);
  3241. }
  3242. }
  3243. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3244. Server svr;
  3245. auto port_str = std::to_string(PORT);
  3246. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3247. auto expected_host = "[::1]:" + port_str;
  3248. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3249. res.set_content("___", "text/plain");
  3250. // res.set_redirect("/2");
  3251. res.set_redirect(redirect_url);
  3252. });
  3253. svr.Get("/2", [&](const Request &req, Response &res) {
  3254. auto host_header = req.headers.find("Host");
  3255. ASSERT_TRUE(host_header != req.headers.end());
  3256. EXPECT_EQ(expected_host, host_header->second);
  3257. res.set_content("Hello World!", "text/plain");
  3258. });
  3259. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3260. auto se = detail::scope_exit([&] {
  3261. svr.stop();
  3262. th.join();
  3263. ASSERT_FALSE(svr.is_running());
  3264. });
  3265. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3266. // actually starts anything, so the condition !svr.is_running() will
  3267. // always remain true, and the loop never stops.
  3268. // This basically counts how many milliseconds have passed since the
  3269. // call to svr.listen(), and if after 5 seconds nothing started yet
  3270. // aborts the test.
  3271. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3272. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3273. ASSERT_LT(milliseconds, 5000U);
  3274. }
  3275. {
  3276. Client cli("::1", PORT);
  3277. cli.set_follow_location(true);
  3278. std::string body;
  3279. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3280. body.append(data, data_length);
  3281. return true;
  3282. });
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. EXPECT_EQ(StatusCode::OK_200, res->status);
  3285. EXPECT_EQ("Hello World!", body);
  3286. }
  3287. {
  3288. Client cli("::1", PORT);
  3289. std::string body;
  3290. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3291. body.append(data, data_length);
  3292. return true;
  3293. });
  3294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3295. EXPECT_EQ(StatusCode::Found_302, res->status);
  3296. EXPECT_EQ("___", body);
  3297. }
  3298. }
  3299. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3300. Server svr;
  3301. svr.Get("/foo", [](const Request &req, Response &res) {
  3302. auto a = req.params.find("a");
  3303. if (a != req.params.end()) {
  3304. res.set_content((*a).second, "text/plain");
  3305. res.status = StatusCode::OK_200;
  3306. } else {
  3307. res.status = StatusCode::BadRequest_400;
  3308. }
  3309. });
  3310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3311. auto se = detail::scope_exit([&] {
  3312. svr.stop();
  3313. thread.join();
  3314. ASSERT_FALSE(svr.is_running());
  3315. });
  3316. svr.wait_until_ready();
  3317. {
  3318. Client cli(HOST, PORT);
  3319. cli.set_path_encode(false);
  3320. auto res = cli.Get("/foo?a=explicitly+encoded");
  3321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3322. EXPECT_EQ(StatusCode::OK_200, res->status);
  3323. // This expects it back with a space, as the `+` won't have been
  3324. // url-encoded, and server-side the params get decoded turning `+`
  3325. // into spaces.
  3326. EXPECT_EQ("explicitly encoded", res->body);
  3327. }
  3328. }
  3329. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3330. // When path encoding is disabled the client must transmit the supplied
  3331. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3332. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3333. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3334. // than a space (0x20). Assert on the raw wire target to catch this.
  3335. Server svr;
  3336. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3337. svr.Get("/foo", [&](const Request &req, Response &res) {
  3338. EXPECT_EQ(expected_target, req.target);
  3339. res.status = StatusCode::OK_200;
  3340. });
  3341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3342. auto se = detail::scope_exit([&] {
  3343. svr.stop();
  3344. thread.join();
  3345. ASSERT_FALSE(svr.is_running());
  3346. });
  3347. svr.wait_until_ready();
  3348. {
  3349. Client cli(HOST, PORT);
  3350. cli.set_path_encode(false);
  3351. auto res = cli.Get(expected_target.c_str());
  3352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3353. EXPECT_EQ(StatusCode::OK_200, res->status);
  3354. }
  3355. }
  3356. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3357. // `open_stream()` used to skip the path encoding that the buffered send
  3358. // path applies, so the same `path` produced different bytes in the request
  3359. // line depending on which API was used. Assert the two agree.
  3360. Server svr;
  3361. std::string target;
  3362. svr.Get(".*", [&](const Request &req, Response &res) {
  3363. target = req.target;
  3364. res.status = StatusCode::OK_200;
  3365. });
  3366. auto port = svr.bind_to_any_port(HOST);
  3367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3368. auto se = detail::scope_exit([&] {
  3369. svr.stop();
  3370. thread.join();
  3371. ASSERT_FALSE(svr.is_running());
  3372. });
  3373. svr.wait_until_ready();
  3374. struct {
  3375. const char *path;
  3376. const char *expected;
  3377. } cases[] = {
  3378. {"/a b?x=1", "/a%20b?x=1"},
  3379. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3380. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3381. };
  3382. for (const auto &c : cases) {
  3383. Client cli(HOST, port);
  3384. target.clear();
  3385. auto res = cli.Get(c.path);
  3386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3387. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3388. auto buffered_target = target;
  3389. target.clear();
  3390. auto handle = cli.open_stream("GET", c.path);
  3391. EXPECT_TRUE(handle.is_valid())
  3392. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3393. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3394. }
  3395. }
  3396. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3397. // The `set_path_encode(false)` contract — transmit the supplied target
  3398. // verbatim — must hold for the streaming API too.
  3399. Server svr;
  3400. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3401. std::string target;
  3402. svr.Get("/foo", [&](const Request &req, Response &res) {
  3403. target = req.target;
  3404. res.status = StatusCode::OK_200;
  3405. });
  3406. auto port = svr.bind_to_any_port(HOST);
  3407. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3408. auto se = detail::scope_exit([&] {
  3409. svr.stop();
  3410. thread.join();
  3411. ASSERT_FALSE(svr.is_running());
  3412. });
  3413. svr.wait_until_ready();
  3414. {
  3415. Client cli(HOST, port);
  3416. cli.set_path_encode(false);
  3417. auto handle = cli.open_stream("GET", expected_target);
  3418. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3419. EXPECT_EQ(expected_target, target);
  3420. }
  3421. }
  3422. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3423. // With path encoding enabled a CR/LF in the target is percent-encoded
  3424. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3425. // write_request_line still backstops `set_path_encode(false)`, which is
  3426. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3427. Server svr;
  3428. // Captured before routing: the decoded path contains a newline, which a
  3429. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3430. std::string target;
  3431. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3432. target = req.target;
  3433. res.status = StatusCode::OK_200;
  3434. return Server::HandlerResponse::Handled;
  3435. });
  3436. auto port = svr.bind_to_any_port(HOST);
  3437. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3438. auto se = detail::scope_exit([&] {
  3439. svr.stop();
  3440. thread.join();
  3441. ASSERT_FALSE(svr.is_running());
  3442. });
  3443. svr.wait_until_ready();
  3444. {
  3445. Client cli(HOST, port);
  3446. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3447. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3448. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3449. }
  3450. }
  3451. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3452. // Every control character is percent-encoded, not just CR/LF, so the target
  3453. // passes the request-target check in write_request_line.
  3454. Server svr;
  3455. std::string target;
  3456. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3457. target = req.target;
  3458. res.status = StatusCode::OK_200;
  3459. return Server::HandlerResponse::Handled;
  3460. });
  3461. auto port = svr.bind_to_any_port(HOST);
  3462. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3463. auto se = detail::scope_exit([&] {
  3464. svr.stop();
  3465. thread.join();
  3466. ASSERT_FALSE(svr.is_running());
  3467. });
  3468. svr.wait_until_ready();
  3469. {
  3470. Client cli(HOST, port);
  3471. auto res = cli.Get("/a\tb\x1b\x7f");
  3472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3473. EXPECT_EQ("/a%09b%1B%7F", target);
  3474. }
  3475. }
  3476. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3477. // Nothing may reach the wire: a raw CR/LF target would split the request
  3478. // line and inject headers.
  3479. Server svr;
  3480. // Pre-routing so that "not called" means nothing reached the server at all,
  3481. // rather than merely failing to match a handler pattern.
  3482. auto handler_called = false;
  3483. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3484. handler_called = true;
  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. cli.set_path_encode(false);
  3499. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3500. EXPECT_FALSE(handle.is_valid());
  3501. EXPECT_EQ(Error::Write, handle.error);
  3502. EXPECT_FALSE(handler_called);
  3503. }
  3504. }
  3505. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3506. // Which of the two branches runs is decided by whether the query component
  3507. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3508. // an empty query and must still fall back to building one from
  3509. // `req.params`, while a non-empty query must win over `req.params`.
  3510. Server svr;
  3511. std::string target;
  3512. svr.Get("/foo", [&](const Request &req, Response &res) {
  3513. target = req.target;
  3514. res.status = StatusCode::OK_200;
  3515. });
  3516. auto port = svr.bind_to_any_port(HOST);
  3517. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3518. auto se = detail::scope_exit([&] {
  3519. svr.stop();
  3520. thread.join();
  3521. ASSERT_FALSE(svr.is_running());
  3522. });
  3523. svr.wait_until_ready();
  3524. {
  3525. // Trailing `?` -> empty query component -> `req.params` is used.
  3526. Client cli(HOST, port);
  3527. Request req;
  3528. req.method = "GET";
  3529. req.path = "/foo?";
  3530. req.params.emplace("a", "1");
  3531. target.clear();
  3532. auto res = cli.send(req);
  3533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3534. EXPECT_EQ("/foo?a=1", target);
  3535. }
  3536. {
  3537. // Non-empty query in `req.path` -> `req.params` is not appended.
  3538. Client cli(HOST, port);
  3539. Request req;
  3540. req.method = "GET";
  3541. req.path = "/foo?b=2";
  3542. req.params.emplace("a", "1");
  3543. target.clear();
  3544. auto res = cli.send(req);
  3545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3546. EXPECT_EQ("/foo?b=2", target);
  3547. }
  3548. }
  3549. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3550. Server svr;
  3551. svr.Get("/", [](const Request &req, Response &) {
  3552. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3553. });
  3554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3555. auto se = detail::scope_exit([&] {
  3556. svr.stop();
  3557. thread.join();
  3558. ASSERT_FALSE(svr.is_running());
  3559. });
  3560. svr.wait_until_ready();
  3561. {
  3562. Client cli(HOST, PORT);
  3563. cli.set_path_encode(false);
  3564. auto res = cli.Get("/?something=%0A");
  3565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3566. EXPECT_EQ(StatusCode::OK_200, res->status);
  3567. }
  3568. }
  3569. TEST(BindServerTest, BindDualStack) {
  3570. Server svr;
  3571. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3572. res.set_content("Hello World!", "text/plain");
  3573. });
  3574. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3575. auto se = detail::scope_exit([&] {
  3576. svr.stop();
  3577. thread.join();
  3578. ASSERT_FALSE(svr.is_running());
  3579. });
  3580. svr.wait_until_ready();
  3581. {
  3582. Client cli("127.0.0.1", PORT);
  3583. auto res = cli.Get("/1");
  3584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3585. EXPECT_EQ(StatusCode::OK_200, res->status);
  3586. EXPECT_EQ("Hello World!", res->body);
  3587. }
  3588. {
  3589. Client cli("::1", PORT);
  3590. auto res = cli.Get("/1");
  3591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3592. EXPECT_EQ(StatusCode::OK_200, res->status);
  3593. EXPECT_EQ("Hello World!", res->body);
  3594. }
  3595. }
  3596. TEST(BindServerTest, BindAndListenSeparately) {
  3597. Server svr;
  3598. int port = svr.bind_to_any_port("0.0.0.0");
  3599. ASSERT_TRUE(svr.is_valid());
  3600. ASSERT_TRUE(port > 0);
  3601. svr.stop();
  3602. }
  3603. // Reports whether anything is still listening on a loopback port. A plain
  3604. // connect() is used instead of a Client request because a socket left bound by
  3605. // mistake accepts the connection into its backlog and never answers, which
  3606. // would hang the test instead of failing it.
  3607. static bool is_loopback_port_accepting(int port) {
  3608. sockaddr_in addr{};
  3609. addr.sin_family = AF_INET;
  3610. addr.sin_port = htons(static_cast<uint16_t>(port));
  3611. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3612. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3613. EXPECT_NE(sock, INVALID_SOCKET);
  3614. if (sock == INVALID_SOCKET) { return false; }
  3615. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3616. static_cast<socklen_t>(sizeof(addr)));
  3617. detail::close_socket(sock);
  3618. return ret == 0;
  3619. }
  3620. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3621. Server svr;
  3622. auto port = svr.bind_to_any_port("127.0.0.1");
  3623. ASSERT_TRUE(port > 0);
  3624. svr.stop();
  3625. // bind_to_any_port() already called listen(2), so until stop() closed the
  3626. // descriptor the port kept accepting connections into the backlog. ASSERT
  3627. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3628. // below blocks forever in the accept loop.
  3629. ASSERT_FALSE(is_loopback_port_accepting(port));
  3630. // Nothing is left to accept on, so listen_after_bind() must report failure
  3631. // instead of returning success without ever serving.
  3632. EXPECT_FALSE(svr.listen_after_bind());
  3633. // The failed listen marks the server decommissioned, so a waiter returns
  3634. // instead of spinning forever.
  3635. svr.wait_until_ready();
  3636. }
  3637. #ifdef CPPHTTPLIB_SSL_ENABLED
  3638. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3640. CLIENT_CA_CERT_DIR);
  3641. int port = svr.bind_to_any_port("0.0.0.0");
  3642. ASSERT_TRUE(svr.is_valid());
  3643. ASSERT_TRUE(port > 0);
  3644. svr.stop();
  3645. }
  3646. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3647. // or a rejected CustomRoute() registration would not stop the server binding.
  3648. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3650. CLIENT_CA_CERT_DIR);
  3651. ASSERT_TRUE(svr.is_valid());
  3652. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3653. EXPECT_FALSE(svr.is_valid());
  3654. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3655. }
  3656. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3657. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3658. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3659. int port = svr.bind_to_any_port("0.0.0.0");
  3660. ASSERT_TRUE(svr.is_valid());
  3661. ASSERT_TRUE(port > 0);
  3662. svr.stop();
  3663. }
  3664. TEST(BindServerTest, UpdateCertsPem) {
  3665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3666. int port = svr.bind_to_any_port("0.0.0.0");
  3667. ASSERT_TRUE(svr.is_valid());
  3668. ASSERT_TRUE(port > 0);
  3669. // Read PEM files
  3670. std::string cert_pem, key_pem, ca_pem;
  3671. read_file(SERVER_CERT_FILE, cert_pem);
  3672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3673. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3674. // Update server certificates using PEM API
  3675. ASSERT_TRUE(
  3676. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3677. ASSERT_TRUE(svr.is_valid());
  3678. svr.stop();
  3679. }
  3680. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3681. // Start server with client CA (enables client auth)
  3682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3683. ASSERT_TRUE(svr.is_valid());
  3684. bool handler_called = false;
  3685. svr.Get("/test", [&](const Request &req, Response &res) {
  3686. handler_called = true;
  3687. // Verify client certificate is present
  3688. auto cert = req.peer_cert();
  3689. EXPECT_TRUE(static_cast<bool>(cert));
  3690. res.set_content("ok", "text/plain");
  3691. });
  3692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3693. auto se = detail::scope_exit([&] {
  3694. svr.stop();
  3695. t.join();
  3696. ASSERT_FALSE(svr.is_running());
  3697. });
  3698. svr.wait_until_ready();
  3699. // Read PEM files
  3700. std::string cert_pem, key_pem, ca_pem;
  3701. read_file(SERVER_CERT_FILE, cert_pem);
  3702. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3703. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3704. // Update server certificates and client CA using PEM API while server running
  3705. ASSERT_TRUE(
  3706. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3707. // Connect with client certificate
  3708. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3709. cli.enable_server_certificate_verification(false);
  3710. cli.set_connection_timeout(30);
  3711. auto res = cli.Get("/test");
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. ASSERT_EQ(StatusCode::OK_200, res->status);
  3714. ASSERT_TRUE(handler_called);
  3715. EXPECT_EQ("ok", res->body);
  3716. }
  3717. #endif
  3718. TEST(ErrorHandlerTest, ContentLength) {
  3719. Server svr;
  3720. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3721. res.status = StatusCode::OK_200;
  3722. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3723. "text/html"); // <= Content-Length still 13
  3724. });
  3725. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3726. res.set_content("Hello World!\n", "text/plain");
  3727. res.status = 524;
  3728. });
  3729. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3730. auto se = detail::scope_exit([&] {
  3731. svr.stop();
  3732. thread.join();
  3733. ASSERT_FALSE(svr.is_running());
  3734. });
  3735. svr.wait_until_ready();
  3736. {
  3737. Client cli(HOST, PORT);
  3738. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3740. EXPECT_EQ(StatusCode::OK_200, res->status);
  3741. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3742. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3743. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3744. }
  3745. }
  3746. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3747. TEST(ExceptionTest, WithoutExceptionHandler) {
  3748. Server svr;
  3749. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3750. throw std::runtime_error("exception...");
  3751. });
  3752. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3753. throw std::runtime_error("exception\r\n...");
  3754. });
  3755. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3756. auto se = detail::scope_exit([&] {
  3757. svr.stop();
  3758. listen_thread.join();
  3759. ASSERT_FALSE(svr.is_running());
  3760. });
  3761. svr.wait_until_ready();
  3762. Client cli("localhost", PORT);
  3763. {
  3764. auto res = cli.Get("/exception");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3767. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3768. }
  3769. {
  3770. auto res = cli.Get("/unknown");
  3771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3772. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3773. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3774. }
  3775. }
  3776. TEST(ExceptionTest, WithExceptionHandler) {
  3777. Server svr;
  3778. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3779. std::exception_ptr ep) {
  3780. EXPECT_FALSE(ep == nullptr);
  3781. try {
  3782. std::rethrow_exception(ep);
  3783. } catch (std::exception &e) {
  3784. EXPECT_EQ("abc", std::string(e.what()));
  3785. } catch (...) {}
  3786. res.status = StatusCode::InternalServerError_500;
  3787. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3788. "text/html"); // <= Content-Length still 13 at this point
  3789. });
  3790. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3791. res.set_content("Hello World!\n", "text/plain");
  3792. throw std::runtime_error("abc");
  3793. });
  3794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3795. auto se = detail::scope_exit([&] {
  3796. svr.stop();
  3797. thread.join();
  3798. ASSERT_FALSE(svr.is_running());
  3799. });
  3800. svr.wait_until_ready();
  3801. for (size_t i = 0; i < 10; i++) {
  3802. Client cli(HOST, PORT);
  3803. for (size_t j = 0; j < 100; j++) {
  3804. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3806. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3807. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3808. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3809. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3810. }
  3811. cli.set_keep_alive(true);
  3812. for (size_t j = 0; j < 100; j++) {
  3813. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3815. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3816. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3817. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3818. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3819. }
  3820. }
  3821. }
  3822. TEST(ExceptionTest, AndErrorHandler) {
  3823. Server svr;
  3824. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3825. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3826. });
  3827. svr.set_exception_handler(
  3828. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3829. EXPECT_FALSE(ep == nullptr);
  3830. try {
  3831. std::rethrow_exception(ep);
  3832. } catch (std::exception &e) {
  3833. res.set_content(e.what(), "text/html");
  3834. } catch (...) {}
  3835. res.status = StatusCode::InternalServerError_500;
  3836. });
  3837. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3838. throw std::runtime_error("EXCEPTION");
  3839. });
  3840. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3841. res.set_content("ERROR", "text/html");
  3842. res.status = StatusCode::InternalServerError_500;
  3843. });
  3844. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3845. auto se = detail::scope_exit([&] {
  3846. svr.stop();
  3847. thread.join();
  3848. ASSERT_FALSE(svr.is_running());
  3849. });
  3850. svr.wait_until_ready();
  3851. Client cli(HOST, PORT);
  3852. {
  3853. auto res = cli.Get("/exception");
  3854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3855. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3856. EXPECT_EQ("EXCEPTION", res->body);
  3857. }
  3858. {
  3859. auto res = cli.Get("/error");
  3860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3861. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3862. EXPECT_EQ("ERROR", res->body);
  3863. }
  3864. {
  3865. auto res = cli.Get("/invalid");
  3866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3868. EXPECT_EQ("NOT_FOUND", res->body);
  3869. }
  3870. }
  3871. #endif
  3872. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3873. // process_request() wraps only routing() in a try/catch, so an exception from
  3874. // any other user callback used to unwind into the task queue - which does not
  3875. // catch - and terminate the process. Each test below runs the server on a
  3876. // single worker thread: a guard that catches the exception but still loses the
  3877. // thread would otherwise be hidden by a spare worker serving the follow-up
  3878. // request. Note that a regression here aborts the whole test binary rather
  3879. // than failing one test.
  3880. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3881. Server svr;
  3882. svr.new_task_queue = [] { return new ThreadPool(1); };
  3883. std::atomic<int> reported{0};
  3884. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3885. if (err == Error::UserCallbackException) { reported++; }
  3886. });
  3887. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3888. res.set_content_provider(
  3889. 1024, "text/plain",
  3890. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3891. sink.write("hello", 5);
  3892. throw std::runtime_error("from the content provider");
  3893. });
  3894. });
  3895. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3896. res.set_content("ok", "text/plain");
  3897. });
  3898. auto port = svr.bind_to_any_port(HOST);
  3899. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3900. auto se = detail::scope_exit([&] {
  3901. svr.stop();
  3902. listen_thread.join();
  3903. ASSERT_FALSE(svr.is_running());
  3904. });
  3905. svr.wait_until_ready();
  3906. {
  3907. Client cli(HOST, port);
  3908. cli.set_read_timeout(5, 0);
  3909. EXPECT_FALSE(cli.Get("/throw"));
  3910. }
  3911. EXPECT_TRUE(svr.is_running());
  3912. EXPECT_EQ(1, reported.load());
  3913. // A request on a fresh connection is still served.
  3914. {
  3915. Client cli(HOST, port);
  3916. auto res = cli.Get("/ok");
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ(StatusCode::OK_200, res->status);
  3919. EXPECT_EQ("ok", res->body);
  3920. }
  3921. }
  3922. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3923. Server svr;
  3924. svr.new_task_queue = [] { return new ThreadPool(1); };
  3925. std::atomic<bool> should_throw{true};
  3926. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3927. res.set_content("hi", "text/plain");
  3928. });
  3929. svr.set_post_routing_handler(
  3930. [&](const Request & /*req*/, Response & /*res*/) {
  3931. if (should_throw) {
  3932. throw std::runtime_error("from the post-routing handler");
  3933. }
  3934. });
  3935. auto port = svr.bind_to_any_port(HOST);
  3936. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. listen_thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli(HOST, port);
  3945. cli.set_read_timeout(5, 0);
  3946. EXPECT_FALSE(cli.Get("/hi"));
  3947. }
  3948. EXPECT_TRUE(svr.is_running());
  3949. should_throw = false;
  3950. {
  3951. Client cli(HOST, port);
  3952. auto res = cli.Get("/hi");
  3953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. EXPECT_EQ("hi", res->body);
  3956. }
  3957. }
  3958. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3959. // The guard reports the caught exception through the error logger, which is
  3960. // a user callback too. A logger that throws has to be contained as well, or
  3961. // the process would terminate from inside the catch.
  3962. Server svr;
  3963. svr.new_task_queue = [] { return new ThreadPool(1); };
  3964. std::atomic<int> reported{0};
  3965. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3966. if (err == Error::UserCallbackException) {
  3967. reported++;
  3968. throw std::runtime_error("from the error logger");
  3969. }
  3970. });
  3971. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3972. res.set_content_provider(
  3973. 1024, "text/plain",
  3974. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3975. sink.write("hello", 5);
  3976. throw std::runtime_error("from the content provider");
  3977. });
  3978. });
  3979. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3980. res.set_content("ok", "text/plain");
  3981. });
  3982. auto port = svr.bind_to_any_port(HOST);
  3983. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3984. auto se = detail::scope_exit([&] {
  3985. svr.stop();
  3986. listen_thread.join();
  3987. ASSERT_FALSE(svr.is_running());
  3988. });
  3989. svr.wait_until_ready();
  3990. {
  3991. Client cli(HOST, port);
  3992. cli.set_read_timeout(5, 0);
  3993. EXPECT_FALSE(cli.Get("/throw"));
  3994. }
  3995. EXPECT_TRUE(svr.is_running());
  3996. EXPECT_EQ(1, reported.load());
  3997. {
  3998. Client cli(HOST, port);
  3999. auto res = cli.Get("/ok");
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. EXPECT_EQ("ok", res->body);
  4003. }
  4004. }
  4005. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4006. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4007. // so the exception unwinds through the ws::WebSocket object on its way to
  4008. // the guard. None of the HTTP cases above cross that.
  4009. Server svr;
  4010. svr.new_task_queue = [] { return new ThreadPool(1); };
  4011. std::atomic<int> reported{0};
  4012. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4013. if (err == Error::UserCallbackException) { reported++; }
  4014. });
  4015. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4016. throw std::runtime_error("from the WebSocket handler");
  4017. });
  4018. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4019. res.set_content("ok", "text/plain");
  4020. });
  4021. auto port = svr.bind_to_any_port(HOST);
  4022. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4023. auto se = detail::scope_exit([&] {
  4024. svr.stop();
  4025. listen_thread.join();
  4026. ASSERT_FALSE(svr.is_running());
  4027. });
  4028. svr.wait_until_ready();
  4029. {
  4030. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4031. "/ws");
  4032. auto res = client.connect();
  4033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4034. // The server dropped the connection instead of dying.
  4035. std::string msg;
  4036. EXPECT_FALSE(client.read(msg));
  4037. client.close();
  4038. }
  4039. EXPECT_TRUE(svr.is_running());
  4040. EXPECT_EQ(1, reported.load());
  4041. {
  4042. Client cli(HOST, port);
  4043. auto res = cli.Get("/ok");
  4044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4045. EXPECT_EQ(StatusCode::OK_200, res->status);
  4046. EXPECT_EQ("ok", res->body);
  4047. }
  4048. }
  4049. #ifdef CPPHTTPLIB_SSL_ENABLED
  4050. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4051. // SSLServer::process_and_close_socket() is a separate overload with its own
  4052. // guard, so it is exercised on its own.
  4053. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4054. ASSERT_TRUE(svr.is_valid());
  4055. svr.new_task_queue = [] { return new ThreadPool(1); };
  4056. std::atomic<int> reported{0};
  4057. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4058. if (err == Error::UserCallbackException) { reported++; }
  4059. });
  4060. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4061. res.set_content_provider(
  4062. 1024, "text/plain",
  4063. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4064. sink.write("hello", 5);
  4065. throw std::runtime_error("from the content provider");
  4066. });
  4067. });
  4068. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4069. res.set_content("ok", "text/plain");
  4070. });
  4071. auto port = svr.bind_to_any_port(HOST);
  4072. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4073. auto se = detail::scope_exit([&] {
  4074. svr.stop();
  4075. listen_thread.join();
  4076. ASSERT_FALSE(svr.is_running());
  4077. });
  4078. svr.wait_until_ready();
  4079. {
  4080. SSLClient cli(HOST, port);
  4081. cli.enable_server_certificate_verification(false);
  4082. cli.set_read_timeout(5, 0);
  4083. EXPECT_FALSE(cli.Get("/throw"));
  4084. }
  4085. EXPECT_TRUE(svr.is_running());
  4086. EXPECT_EQ(1, reported.load());
  4087. {
  4088. SSLClient cli(HOST, port);
  4089. cli.enable_server_certificate_verification(false);
  4090. auto res = cli.Get("/ok");
  4091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4092. EXPECT_EQ(StatusCode::OK_200, res->status);
  4093. EXPECT_EQ("ok", res->body);
  4094. }
  4095. }
  4096. #endif
  4097. #endif
  4098. TEST(NoContentTest, ContentLength) {
  4099. Server svr;
  4100. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4101. res.status = StatusCode::NoContent_204;
  4102. });
  4103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4104. auto se = detail::scope_exit([&] {
  4105. svr.stop();
  4106. thread.join();
  4107. ASSERT_FALSE(svr.is_running());
  4108. });
  4109. svr.wait_until_ready();
  4110. {
  4111. Client cli(HOST, PORT);
  4112. auto res = cli.Get("/hi");
  4113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4114. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4115. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4116. }
  4117. }
  4118. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4119. #ifdef CPPHTTPLIB_SSL_ENABLED
  4120. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4121. ASSERT_TRUE(svr.is_valid());
  4122. #else
  4123. Server svr;
  4124. #endif
  4125. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4126. if (req.path == "/routing_handler") {
  4127. res.set_header("PRE_ROUTING", "on");
  4128. res.set_content("Routing Handler", "text/plain");
  4129. return httplib::Server::HandlerResponse::Handled;
  4130. }
  4131. return httplib::Server::HandlerResponse::Unhandled;
  4132. });
  4133. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4134. res.set_content("Error", "text/html");
  4135. });
  4136. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4137. if (req.path == "/routing_handler") {
  4138. res.set_header("POST_ROUTING", "on");
  4139. }
  4140. });
  4141. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4142. res.set_content("Hello World!\n", "text/plain");
  4143. });
  4144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4145. auto se = detail::scope_exit([&] {
  4146. svr.stop();
  4147. thread.join();
  4148. ASSERT_FALSE(svr.is_running());
  4149. });
  4150. svr.wait_until_ready();
  4151. {
  4152. #ifdef CPPHTTPLIB_SSL_ENABLED
  4153. SSLClient cli(HOST, PORT);
  4154. cli.enable_server_certificate_verification(false);
  4155. #else
  4156. Client cli(HOST, PORT);
  4157. #endif
  4158. auto res = cli.Get("/routing_handler");
  4159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4160. EXPECT_EQ(StatusCode::OK_200, res->status);
  4161. EXPECT_EQ("Routing Handler", res->body);
  4162. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4163. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4164. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4165. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4166. }
  4167. {
  4168. #ifdef CPPHTTPLIB_SSL_ENABLED
  4169. SSLClient cli(HOST, PORT);
  4170. cli.enable_server_certificate_verification(false);
  4171. #else
  4172. Client cli(HOST, PORT);
  4173. #endif
  4174. auto res = cli.Get("/hi");
  4175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4176. EXPECT_EQ(StatusCode::OK_200, res->status);
  4177. EXPECT_EQ("Hello World!\n", res->body);
  4178. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4179. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4180. }
  4181. {
  4182. #ifdef CPPHTTPLIB_SSL_ENABLED
  4183. SSLClient cli(HOST, PORT);
  4184. cli.enable_server_certificate_verification(false);
  4185. #else
  4186. Client cli(HOST, PORT);
  4187. #endif
  4188. auto res = cli.Get("/aaa");
  4189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4190. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4191. EXPECT_EQ("Error", res->body);
  4192. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4193. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4194. }
  4195. }
  4196. TEST(RequestHandlerTest, PreRequestHandler) {
  4197. auto route_path = "/user/:user";
  4198. Server svr;
  4199. svr.Get("/hi", [](const Request &, Response &res) {
  4200. res.set_content("hi", "text/plain");
  4201. });
  4202. svr.Get(route_path, [](const Request &req, Response &res) {
  4203. res.set_content(req.path_params.at("user"), "text/plain");
  4204. });
  4205. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4206. if (req.matched_route == route_path) {
  4207. auto user = req.path_params.at("user");
  4208. if (user != "john") {
  4209. res.status = StatusCode::Forbidden_403;
  4210. res.set_content("error", "text/html");
  4211. return Server::HandlerResponse::Handled;
  4212. }
  4213. }
  4214. return Server::HandlerResponse::Unhandled;
  4215. });
  4216. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4217. auto se = detail::scope_exit([&] {
  4218. svr.stop();
  4219. thread.join();
  4220. ASSERT_FALSE(svr.is_running());
  4221. });
  4222. svr.wait_until_ready();
  4223. Client cli(HOST, PORT);
  4224. {
  4225. auto res = cli.Get("/hi");
  4226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4227. EXPECT_EQ(StatusCode::OK_200, res->status);
  4228. EXPECT_EQ("hi", res->body);
  4229. }
  4230. {
  4231. auto res = cli.Get("/user/john");
  4232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4233. EXPECT_EQ(StatusCode::OK_200, res->status);
  4234. EXPECT_EQ("john", res->body);
  4235. }
  4236. {
  4237. auto res = cli.Get("/user/invalid-user");
  4238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4239. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4240. EXPECT_EQ("error", res->body);
  4241. }
  4242. }
  4243. // The pre-request handler must run before the request body is read, so a
  4244. // rejected request never forces the server to buffer a (potentially large)
  4245. // body. Here the posted body is larger than the payload limit: if the body
  4246. // were read first the server would answer 413, but because the pre-request
  4247. // handler runs first it answers 403 and the body is never read.
  4248. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4249. Server svr;
  4250. svr.set_payload_max_length(8);
  4251. auto handler_ran = false;
  4252. svr.Post("/reject", [&](const Request &req, Response &res) {
  4253. handler_ran = true;
  4254. res.set_content(req.body, "text/plain");
  4255. });
  4256. svr.Post("/accept", [](const Request &req, Response &res) {
  4257. res.set_content(req.body, "text/plain");
  4258. });
  4259. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4260. if (req.matched_route == "/reject") {
  4261. res.status = StatusCode::Forbidden_403;
  4262. res.set_content("denied", "text/plain");
  4263. return Server::HandlerResponse::Handled;
  4264. }
  4265. return Server::HandlerResponse::Unhandled;
  4266. });
  4267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4268. auto se = detail::scope_exit([&] {
  4269. svr.stop();
  4270. thread.join();
  4271. ASSERT_FALSE(svr.is_running());
  4272. });
  4273. svr.wait_until_ready();
  4274. Client cli(HOST, PORT);
  4275. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4276. // rejects with 403 before the body is read, so 413 is never reached.
  4277. {
  4278. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4280. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4281. EXPECT_EQ("denied", res->body);
  4282. EXPECT_FALSE(handler_ran);
  4283. }
  4284. // An approved route still reads the body and enforces the payload limit.
  4285. {
  4286. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4288. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4289. }
  4290. }
  4291. TEST(UserDataTest, BasicOperations) {
  4292. httplib::UserData ud;
  4293. // Initially empty
  4294. EXPECT_FALSE(ud.has("key"));
  4295. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4296. // set and get
  4297. ud.set("key", 42);
  4298. EXPECT_TRUE(ud.has("key"));
  4299. auto *p = ud.get<int>("key");
  4300. ASSERT_NE(nullptr, p);
  4301. EXPECT_EQ(42, *p);
  4302. // Type mismatch → nullptr
  4303. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4304. // Overwrite with different type
  4305. ud.set("key", std::string("hello"));
  4306. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4307. auto *s = ud.get<std::string>("key");
  4308. ASSERT_NE(nullptr, s);
  4309. EXPECT_EQ("hello", *s);
  4310. // erase
  4311. ud.erase("key");
  4312. EXPECT_FALSE(ud.has("key"));
  4313. // clear
  4314. ud.set("a", 1);
  4315. ud.set("b", 2);
  4316. ud.clear();
  4317. EXPECT_FALSE(ud.has("a"));
  4318. EXPECT_FALSE(ud.has("b"));
  4319. }
  4320. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4321. struct AuthCtx {
  4322. std::string user_id;
  4323. };
  4324. Server svr;
  4325. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4326. res.user_data.set("auth", AuthCtx{"alice"});
  4327. return Server::HandlerResponse::Unhandled;
  4328. });
  4329. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4330. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4331. ASSERT_NE(nullptr, ctx);
  4332. res.set_content("Hello " + ctx->user_id, "text/plain");
  4333. });
  4334. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4335. auto se = detail::scope_exit([&] {
  4336. svr.stop();
  4337. thread.join();
  4338. ASSERT_FALSE(svr.is_running());
  4339. });
  4340. svr.wait_until_ready();
  4341. Client cli(HOST, PORT);
  4342. auto res = cli.Get("/me");
  4343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. EXPECT_EQ("Hello alice", res->body);
  4346. }
  4347. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4348. struct RoleCtx {
  4349. std::string role;
  4350. };
  4351. Server svr;
  4352. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4353. res.user_data.set("role", RoleCtx{"admin"});
  4354. return Server::HandlerResponse::Unhandled;
  4355. });
  4356. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4357. auto *ctx = res.user_data.get<RoleCtx>("role");
  4358. ASSERT_NE(nullptr, ctx);
  4359. res.set_content(ctx->role, "text/plain");
  4360. });
  4361. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4362. auto se = detail::scope_exit([&] {
  4363. svr.stop();
  4364. thread.join();
  4365. ASSERT_FALSE(svr.is_running());
  4366. });
  4367. svr.wait_until_ready();
  4368. Client cli(HOST, PORT);
  4369. auto res = cli.Get("/role");
  4370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4371. EXPECT_EQ(StatusCode::OK_200, res->status);
  4372. EXPECT_EQ("admin", res->body);
  4373. }
  4374. TEST(InvalidFormatTest, StatusCode) {
  4375. Server svr;
  4376. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4377. res.set_content("Hello World!\n", "text/plain");
  4378. res.status = 9999; // Status should be a three-digit code...
  4379. });
  4380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4381. auto se = detail::scope_exit([&] {
  4382. svr.stop();
  4383. thread.join();
  4384. ASSERT_FALSE(svr.is_running());
  4385. });
  4386. svr.wait_until_ready();
  4387. {
  4388. Client cli(HOST, PORT);
  4389. auto res = cli.Get("/hi");
  4390. ASSERT_FALSE(res);
  4391. }
  4392. }
  4393. TEST(URLFragmentTest, WithFragment) {
  4394. Server svr;
  4395. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4396. EXPECT_TRUE(req.target == "/hi");
  4397. });
  4398. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4399. auto se = detail::scope_exit([&] {
  4400. svr.stop();
  4401. thread.join();
  4402. ASSERT_FALSE(svr.is_running());
  4403. });
  4404. svr.wait_until_ready();
  4405. {
  4406. Client cli(HOST, PORT);
  4407. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4408. EXPECT_TRUE(res);
  4409. EXPECT_EQ(StatusCode::OK_200, res->status);
  4410. res = cli.Get("/hi%23key1=val1=key2=val2");
  4411. EXPECT_TRUE(res);
  4412. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4413. }
  4414. }
  4415. TEST(HeaderWriter, SetHeaderWriter) {
  4416. Server svr;
  4417. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4418. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4419. return detail::write_headers(strm, hdrs);
  4420. });
  4421. svr.Get("/hi", [](const Request &req, Response &res) {
  4422. auto it = req.headers.find("CustomClientHeader");
  4423. EXPECT_TRUE(it != req.headers.end());
  4424. EXPECT_EQ(it->second, "CustomClientValue");
  4425. res.set_content("Hello World!\n", "text/plain");
  4426. });
  4427. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4428. auto se = detail::scope_exit([&] {
  4429. svr.stop();
  4430. thread.join();
  4431. ASSERT_FALSE(svr.is_running());
  4432. });
  4433. svr.wait_until_ready();
  4434. {
  4435. Client cli(HOST, PORT);
  4436. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4437. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4438. return detail::write_headers(strm, hdrs);
  4439. });
  4440. auto res = cli.Get("/hi");
  4441. EXPECT_TRUE(res);
  4442. EXPECT_EQ(StatusCode::OK_200, res->status);
  4443. auto it = res->headers.find("CustomServerHeader");
  4444. EXPECT_TRUE(it != res->headers.end());
  4445. EXPECT_EQ(it->second, "CustomServerValue");
  4446. }
  4447. }
  4448. class ServerTest : public ::testing::Test {
  4449. protected:
  4450. ServerTest()
  4451. : cli_(HOST, PORT)
  4452. #ifdef CPPHTTPLIB_SSL_ENABLED
  4453. ,
  4454. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4455. #endif
  4456. {
  4457. #ifdef CPPHTTPLIB_SSL_ENABLED
  4458. cli_.enable_server_certificate_verification(false);
  4459. #endif
  4460. // Allow LARGE_DATA (100MB) responses
  4461. cli_.set_payload_max_length(200 * 1024 * 1024);
  4462. }
  4463. virtual void SetUp() {
  4464. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4465. svr_.set_payload_max_length(200 * 1024 * 1024);
  4466. svr_.set_mount_point("/", "./www");
  4467. svr_.set_mount_point("/mount", "./www2");
  4468. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4469. svr_.Get("/hi",
  4470. [&](const Request & /*req*/, Response &res) {
  4471. res.set_content("Hello World!", "text/plain");
  4472. })
  4473. .Get("/file_content",
  4474. [&](const Request & /*req*/, Response &res) {
  4475. res.set_file_content("./www/dir/test.html");
  4476. })
  4477. .Get("/file_content_with_content_type",
  4478. [&](const Request & /*req*/, Response &res) {
  4479. res.set_file_content("./www/file", "text/plain");
  4480. })
  4481. .Get("/invalid_file_content",
  4482. [&](const Request & /*req*/, Response &res) {
  4483. res.set_file_content("./www/dir/invalid_file_path");
  4484. })
  4485. .Get("/http_response_splitting",
  4486. [&](const Request & /*req*/, Response &res) {
  4487. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4488. EXPECT_EQ(0U, res.headers.size());
  4489. EXPECT_FALSE(res.has_header("a"));
  4490. res.set_header("a", "1\nSet-Cookie: a=1");
  4491. EXPECT_EQ(0U, res.headers.size());
  4492. EXPECT_FALSE(res.has_header("a"));
  4493. res.set_header("a", "1\rSet-Cookie: a=1");
  4494. EXPECT_EQ(0U, res.headers.size());
  4495. EXPECT_FALSE(res.has_header("a"));
  4496. res.set_header("a\r\nb", "0");
  4497. EXPECT_EQ(0U, res.headers.size());
  4498. EXPECT_FALSE(res.has_header("a"));
  4499. res.set_header("a\rb", "0");
  4500. EXPECT_EQ(0U, res.headers.size());
  4501. EXPECT_FALSE(res.has_header("a"));
  4502. res.set_header("a\nb", "0");
  4503. EXPECT_EQ(0U, res.headers.size());
  4504. EXPECT_FALSE(res.has_header("a"));
  4505. res.set_redirect("1\r\nSet-Cookie: a=1");
  4506. EXPECT_EQ(0U, res.headers.size());
  4507. EXPECT_FALSE(res.has_header("Location"));
  4508. })
  4509. .Get("/slow",
  4510. [&](const Request & /*req*/, Response &res) {
  4511. std::this_thread::sleep_for(std::chrono::seconds(4));
  4512. res.set_content("slow", "text/plain");
  4513. })
  4514. #if 0
  4515. .Post("/slowpost",
  4516. [&](const Request & /*req*/, Response &res) {
  4517. std::this_thread::sleep_for(std::chrono::seconds(2));
  4518. res.set_content("slow", "text/plain");
  4519. })
  4520. #endif
  4521. .Get("/remote_addr",
  4522. [&](const Request &req, Response &res) {
  4523. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4524. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4525. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4526. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4527. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4528. #endif
  4529. res.set_content(req.remote_addr, "text/plain");
  4530. })
  4531. .Get("/local_addr",
  4532. [&](const Request &req, Response &res) {
  4533. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4534. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4535. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4536. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4537. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4538. #endif
  4539. auto local_addr = req.local_addr;
  4540. auto local_port = std::to_string(req.local_port);
  4541. res.set_content(local_addr.append(":").append(local_port),
  4542. "text/plain");
  4543. })
  4544. .Get("/endwith%",
  4545. [&](const Request & /*req*/, Response &res) {
  4546. res.set_content("Hello World!", "text/plain");
  4547. })
  4548. .Get("/a\\+\\+b",
  4549. [&](const Request &req, Response &res) {
  4550. ASSERT_TRUE(req.has_param("a +b"));
  4551. auto val = req.get_param_value("a +b");
  4552. res.set_content(val, "text/plain");
  4553. })
  4554. .Get("/", [&](const Request & /*req*/,
  4555. Response &res) { res.set_redirect("/hi"); })
  4556. .Post("/1",
  4557. [](const Request & /*req*/, Response &res) {
  4558. res.set_redirect("/2", StatusCode::SeeOther_303);
  4559. })
  4560. .Get("/2",
  4561. [](const Request & /*req*/, Response &res) {
  4562. res.set_content("redirected.", "text/plain");
  4563. res.status = StatusCode::OK_200;
  4564. })
  4565. .Post("/person",
  4566. [&](const Request &req, Response &res) {
  4567. if (req.has_param("name") && req.has_param("note")) {
  4568. persons_[req.get_param_value("name")] =
  4569. req.get_param_value("note");
  4570. } else {
  4571. res.status = StatusCode::BadRequest_400;
  4572. }
  4573. })
  4574. .Put("/person",
  4575. [&](const Request &req, Response &res) {
  4576. if (req.has_param("name") && req.has_param("note")) {
  4577. persons_[req.get_param_value("name")] =
  4578. req.get_param_value("note");
  4579. } else {
  4580. res.status = StatusCode::BadRequest_400;
  4581. }
  4582. })
  4583. .Get("/person/(.*)",
  4584. [&](const Request &req, Response &res) {
  4585. string name = req.matches[1];
  4586. if (persons_.find(name) != persons_.end()) {
  4587. auto note = persons_[name];
  4588. res.set_content(note, "text/plain");
  4589. } else {
  4590. res.status = StatusCode::NotFound_404;
  4591. }
  4592. })
  4593. .Delete("/person",
  4594. [&](const Request &req, Response &res) {
  4595. if (req.has_param("name")) {
  4596. string name = req.get_param_value("name");
  4597. if (persons_.find(name) != persons_.end()) {
  4598. persons_.erase(name);
  4599. res.set_content("DELETED", "text/plain");
  4600. } else {
  4601. res.status = StatusCode::NotFound_404;
  4602. }
  4603. } else {
  4604. res.status = StatusCode::BadRequest_400;
  4605. }
  4606. })
  4607. .Post("/x-www-form-urlencoded-json",
  4608. [&](const Request &req, Response &res) {
  4609. auto json = req.get_param_value("json");
  4610. ASSERT_EQ(JSON_DATA, json);
  4611. res.set_content(json, "appliation/json");
  4612. res.status = StatusCode::OK_200;
  4613. })
  4614. .Get("/streamed-chunked",
  4615. [&](const Request & /*req*/, Response &res) {
  4616. res.set_chunked_content_provider(
  4617. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4618. sink.os << "123";
  4619. sink.os << "456";
  4620. sink.os << "789";
  4621. sink.done();
  4622. return true;
  4623. });
  4624. })
  4625. .Get("/streamed-chunked-with-prohibited-trailer",
  4626. [&](const Request & /*req*/, Response &res) {
  4627. auto i = new int(0);
  4628. // Declare both a prohibited trailer (Content-Length) and an
  4629. // allowed one
  4630. res.set_header("Trailer", "Content-Length, X-Allowed");
  4631. res.set_chunked_content_provider(
  4632. "text/plain",
  4633. [i](size_t /*offset*/, DataSink &sink) {
  4634. switch (*i) {
  4635. case 0: sink.os << "123"; break;
  4636. case 1: sink.os << "456"; break;
  4637. case 2: sink.os << "789"; break;
  4638. case 3: {
  4639. sink.done_with_trailer(
  4640. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4641. } break;
  4642. }
  4643. (*i)++;
  4644. return true;
  4645. },
  4646. [i](bool success) {
  4647. EXPECT_TRUE(success);
  4648. delete i;
  4649. });
  4650. })
  4651. .Get("/streamed-chunked2",
  4652. [&](const Request & /*req*/, Response &res) {
  4653. auto i = new int(0);
  4654. res.set_chunked_content_provider(
  4655. "text/plain",
  4656. [i](size_t /*offset*/, DataSink &sink) {
  4657. switch (*i) {
  4658. case 0: sink.os << "123"; break;
  4659. case 1: sink.os << "456"; break;
  4660. case 2: sink.os << "789"; break;
  4661. case 3: sink.done(); break;
  4662. }
  4663. (*i)++;
  4664. return true;
  4665. },
  4666. [i](bool success) {
  4667. EXPECT_TRUE(success);
  4668. delete i;
  4669. });
  4670. })
  4671. .Get("/streamed-chunked-with-trailer",
  4672. [&](const Request & /*req*/, Response &res) {
  4673. auto i = new int(0);
  4674. res.set_header("Trailer", "Dummy1, Dummy2");
  4675. res.set_chunked_content_provider(
  4676. "text/plain",
  4677. [i](size_t /*offset*/, DataSink &sink) {
  4678. switch (*i) {
  4679. case 0: sink.os << "123"; break;
  4680. case 1: sink.os << "456"; break;
  4681. case 2: sink.os << "789"; break;
  4682. case 3: {
  4683. sink.done_with_trailer(
  4684. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4685. } break;
  4686. }
  4687. (*i)++;
  4688. return true;
  4689. },
  4690. [i](bool success) {
  4691. EXPECT_TRUE(success);
  4692. delete i;
  4693. });
  4694. })
  4695. .Get("/streamed",
  4696. [&](const Request & /*req*/, Response &res) {
  4697. res.set_content_provider(
  4698. 6, "text/plain",
  4699. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4700. sink.os << (offset < 3 ? "a" : "b");
  4701. return true;
  4702. });
  4703. })
  4704. .Get("/streamed-without-length",
  4705. [&](const Request & /*req*/, Response &res) {
  4706. auto data = new std::string("abcdefg");
  4707. res.set_content_provider(
  4708. "text/plain",
  4709. [data](size_t offset, DataSink &sink) {
  4710. if (offset < data->size()) {
  4711. sink.os << data->substr(offset);
  4712. }
  4713. sink.done();
  4714. return true;
  4715. },
  4716. [data](bool success) {
  4717. EXPECT_TRUE(success);
  4718. delete data;
  4719. });
  4720. })
  4721. .Get("/streamed-with-range",
  4722. [&](const Request &req, Response &res) {
  4723. auto data = new std::string("abcdefg");
  4724. // An explicit status keeps the server from picking the 206 it
  4725. // would otherwise choose for a ranged request, so the response
  4726. // is not a partial representation.
  4727. auto status = req.get_param_value("status");
  4728. if (status == "200") {
  4729. res.status = StatusCode::OK_200;
  4730. } else if (status == "403") {
  4731. res.status = StatusCode::Forbidden_403;
  4732. }
  4733. res.set_content_provider(
  4734. data->size(), "text/plain",
  4735. [data](size_t offset, size_t length, DataSink &sink) {
  4736. size_t DATA_CHUNK_SIZE = 4;
  4737. const auto &d = *data;
  4738. auto out_len =
  4739. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4740. auto ret =
  4741. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4742. EXPECT_TRUE(ret);
  4743. return true;
  4744. },
  4745. [data, &req](bool success) {
  4746. EXPECT_EQ(success, !req.has_param("error"));
  4747. delete data;
  4748. });
  4749. })
  4750. .Get("/streamed-cancel",
  4751. [&](const Request & /*req*/, Response &res) {
  4752. res.set_content_provider(
  4753. size_t(-1), "text/plain",
  4754. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4755. sink.os << "data_chunk";
  4756. return true;
  4757. });
  4758. })
  4759. .Get("/regex-with-delimiter",
  4760. [&](const Request &req, Response & /*res*/) {
  4761. ASSERT_TRUE(req.has_param("key"));
  4762. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4763. })
  4764. .Get("/with-range",
  4765. [&](const Request & /*req*/, Response &res) {
  4766. res.set_content("abcdefg", "text/plain");
  4767. })
  4768. .Get("/test-start-time",
  4769. [&](const Request &req, Response & /*res*/) {
  4770. EXPECT_NE(req.start_time_,
  4771. std::chrono::steady_clock::time_point::min());
  4772. })
  4773. .Get("/with-range-customized-response",
  4774. [&](const Request & /*req*/, Response &res) {
  4775. res.status = StatusCode::BadRequest_400;
  4776. res.set_content(JSON_DATA, "application/json");
  4777. })
  4778. .Post("/chunked",
  4779. [&](const Request &req, Response & /*res*/) {
  4780. EXPECT_EQ(req.body, "dechunked post body");
  4781. })
  4782. .Post("/large-chunked",
  4783. [&](const Request &req, Response & /*res*/) {
  4784. std::string expected(6 * 30 * 1024u, 'a');
  4785. EXPECT_EQ(req.body, expected);
  4786. })
  4787. .Post("/multipart",
  4788. [&](const Request &req, Response & /*res*/) {
  4789. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4790. req.form.get_field_count("text2") +
  4791. req.form.get_field_count("file3") +
  4792. req.form.get_field_count("file4"));
  4793. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4794. req.form.get_file_count("file2"));
  4795. ASSERT_TRUE(!req.form.has_file("???"));
  4796. ASSERT_TRUE(!req.form.has_field("???"));
  4797. ASSERT_TRUE(req.body.empty());
  4798. {
  4799. const auto &text = req.form.get_field("text1");
  4800. EXPECT_EQ("text default", text);
  4801. }
  4802. {
  4803. const auto &text = req.form.get_field("text2");
  4804. EXPECT_EQ("aωb", text);
  4805. }
  4806. {
  4807. const auto &file = req.form.get_file("file1");
  4808. EXPECT_EQ("hello.txt", file.filename);
  4809. EXPECT_EQ("text/plain", file.content_type);
  4810. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4811. }
  4812. {
  4813. const auto &file = req.form.get_file("file2");
  4814. EXPECT_EQ("world.json", file.filename);
  4815. EXPECT_EQ("application/json", file.content_type);
  4816. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4817. }
  4818. {
  4819. const auto &text = req.form.get_field("file3");
  4820. EXPECT_EQ(0u, text.size());
  4821. }
  4822. {
  4823. const auto &text = req.form.get_field("file4");
  4824. EXPECT_EQ(0u, text.size());
  4825. }
  4826. })
  4827. .Post("/multipart/multi_file_values",
  4828. [&](const Request &req, Response & /*res*/) {
  4829. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4830. req.form.get_field_count("multi_text1"));
  4831. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4832. ASSERT_TRUE(!req.form.has_file("???"));
  4833. ASSERT_TRUE(!req.form.has_field("???"));
  4834. ASSERT_TRUE(req.body.empty());
  4835. {
  4836. const auto &text = req.form.get_field("text");
  4837. EXPECT_EQ("default text", text);
  4838. }
  4839. {
  4840. const auto &text1_values = req.form.get_fields("multi_text1");
  4841. EXPECT_EQ(2u, text1_values.size());
  4842. EXPECT_EQ("aaaaa", text1_values[0]);
  4843. EXPECT_EQ("bbbbb", text1_values[1]);
  4844. }
  4845. {
  4846. const auto &file1_values = req.form.get_files("multi_file1");
  4847. EXPECT_EQ(2u, file1_values.size());
  4848. auto file1 = file1_values[0];
  4849. EXPECT_EQ(file1.filename, "hello.txt");
  4850. EXPECT_EQ(file1.content_type, "text/plain");
  4851. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4852. auto file2 = file1_values[1];
  4853. EXPECT_EQ(file2.filename, "world.json");
  4854. EXPECT_EQ(file2.content_type, "application/json");
  4855. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4856. }
  4857. })
  4858. .Post("/empty",
  4859. [&](const Request &req, Response &res) {
  4860. EXPECT_EQ(req.body, "");
  4861. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4862. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4863. res.set_content("empty", "text/plain");
  4864. })
  4865. .Post("/empty-no-content-type",
  4866. [&](const Request &req, Response &res) {
  4867. EXPECT_EQ(req.body, "");
  4868. EXPECT_FALSE(req.has_header("Content-Type"));
  4869. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4870. res.set_content("empty-no-content-type", "text/plain");
  4871. })
  4872. .Post("/path-only",
  4873. [&](const Request &req, Response &res) {
  4874. EXPECT_EQ(req.body, "");
  4875. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4877. res.set_content("path-only", "text/plain");
  4878. })
  4879. .Post("/path-headers-only",
  4880. [&](const Request &req, Response &res) {
  4881. EXPECT_EQ(req.body, "");
  4882. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4883. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4884. EXPECT_EQ("world", req.get_header_value("hello"));
  4885. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4886. res.set_content("path-headers-only", "text/plain");
  4887. })
  4888. .Post("/post-large",
  4889. [&](const Request &req, Response &res) {
  4890. EXPECT_EQ(req.body, LARGE_DATA);
  4891. res.set_content(req.body, "text/plain");
  4892. })
  4893. .Post("/post-loopback",
  4894. [&](const Request &, Response &res,
  4895. ContentReader const &content_reader) {
  4896. std::string body;
  4897. content_reader([&](const char *data, size_t data_length) {
  4898. body.append(data, data_length);
  4899. return true;
  4900. });
  4901. res.set_content(body, "text/plain");
  4902. })
  4903. .Put("/put-loopback",
  4904. [&](const Request &, Response &res,
  4905. ContentReader const &content_reader) {
  4906. std::string body;
  4907. content_reader([&](const char *data, size_t data_length) {
  4908. body.append(data, data_length);
  4909. return true;
  4910. });
  4911. res.set_content(body, "text/plain");
  4912. })
  4913. .Patch("/patch-loopback",
  4914. [&](const Request &, Response &res,
  4915. ContentReader const &content_reader) {
  4916. std::string body;
  4917. content_reader([&](const char *data, size_t data_length) {
  4918. body.append(data, data_length);
  4919. return true;
  4920. });
  4921. res.set_content(body, "text/plain");
  4922. })
  4923. .Put("/empty-no-content-type",
  4924. [&](const Request &req, Response &res) {
  4925. EXPECT_EQ(req.body, "");
  4926. EXPECT_FALSE(req.has_header("Content-Type"));
  4927. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4928. res.set_content("empty-no-content-type", "text/plain");
  4929. })
  4930. .Put("/put",
  4931. [&](const Request &req, Response &res) {
  4932. EXPECT_EQ(req.body, "PUT");
  4933. res.set_content(req.body, "text/plain");
  4934. })
  4935. .Put("/put-large",
  4936. [&](const Request &req, Response &res) {
  4937. EXPECT_EQ(req.body, LARGE_DATA);
  4938. res.set_content(req.body, "text/plain");
  4939. })
  4940. .Patch("/patch",
  4941. [&](const Request &req, Response &res) {
  4942. EXPECT_EQ(req.body, "PATCH");
  4943. res.set_content(req.body, "text/plain");
  4944. })
  4945. .Delete("/delete",
  4946. [&](const Request & /*req*/, Response &res) {
  4947. res.set_content("DELETE", "text/plain");
  4948. })
  4949. .Delete("/delete-body",
  4950. [&](const Request &req, Response &res) {
  4951. EXPECT_EQ(req.body, "content");
  4952. res.set_content(req.body, "text/plain");
  4953. })
  4954. .Options(R"(\*)",
  4955. [&](const Request & /*req*/, Response &res) {
  4956. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4957. })
  4958. .CustomRoute("PROPFIND", "/dav/:id",
  4959. [&](const Request &req, Response &res) {
  4960. res.set_header("x-body-size",
  4961. std::to_string(req.body.size()));
  4962. res.set_header("x-matched-route", req.matched_route);
  4963. res.set_header("x-dav-id", req.path_params.at("id"));
  4964. res.status = StatusCode::MultiStatus_207;
  4965. res.set_content(req.body, "application/xml");
  4966. })
  4967. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4968. [&](const Request &req, Response &res) {
  4969. res.set_header("x-dav-match", req.matches[1]);
  4970. res.status = StatusCode::MultiStatus_207;
  4971. })
  4972. .CustomRoute("MKCOL", "/dav-mkcol",
  4973. [&](const Request &req, Response &res) {
  4974. EXPECT_TRUE(req.body.empty());
  4975. res.status = StatusCode::Created_201;
  4976. })
  4977. .CustomRoute(
  4978. "REPORT", "/dav-report",
  4979. [&](const Request & /*req*/, Response &res,
  4980. const ContentReader &content_reader) {
  4981. std::string body;
  4982. content_reader([&](const char *data, size_t data_length) {
  4983. body.append(data, data_length);
  4984. return true;
  4985. });
  4986. res.set_header("x-body-size", std::to_string(body.size()));
  4987. res.status = StatusCode::MultiStatus_207;
  4988. res.set_content(body, "application/xml");
  4989. })
  4990. .Get("/request-target",
  4991. [&](const Request &req, Response & /*res*/) {
  4992. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4993. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4994. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4995. })
  4996. .Get("/long-query-value",
  4997. [&](const Request &req, Response & /*res*/) {
  4998. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4999. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5000. })
  5001. .Get("/too-long-query-value",
  5002. [&](const Request &req, Response & /*res*/) {
  5003. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5004. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5005. })
  5006. .Get("/array-param",
  5007. [&](const Request &req, Response & /*res*/) {
  5008. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5009. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5010. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5011. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5012. })
  5013. .Get("/array-param-values",
  5014. [&](const Request &req, Response & /*res*/) {
  5015. auto values = req.get_param_values("array");
  5016. EXPECT_EQ(3u, values.size());
  5017. EXPECT_EQ("value1", values[0]);
  5018. EXPECT_EQ("value2", values[1]);
  5019. EXPECT_EQ("value3", values[2]);
  5020. auto empty = req.get_param_values("nonexistent");
  5021. EXPECT_TRUE(empty.empty());
  5022. })
  5023. .Post("/validate-no-multiple-headers",
  5024. [&](const Request &req, Response & /*res*/) {
  5025. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5026. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5027. })
  5028. .Post("/content_receiver",
  5029. [&](const Request &req, Response &res,
  5030. const ContentReader &content_reader) {
  5031. if (req.is_multipart_form_data()) {
  5032. std::vector<FormData> items;
  5033. content_reader(
  5034. [&](const FormData &file) {
  5035. items.push_back(file);
  5036. return true;
  5037. },
  5038. [&](const char *data, size_t data_length) {
  5039. items.back().content.append(data, data_length);
  5040. return true;
  5041. });
  5042. EXPECT_EQ(5u, items.size());
  5043. {
  5044. const auto &file = get_file_value(items, "text1");
  5045. EXPECT_TRUE(file.filename.empty());
  5046. EXPECT_EQ("text default", file.content);
  5047. }
  5048. {
  5049. const auto &file = get_file_value(items, "text2");
  5050. EXPECT_TRUE(file.filename.empty());
  5051. EXPECT_EQ("aωb", file.content);
  5052. }
  5053. {
  5054. const auto &file = get_file_value(items, "file1");
  5055. EXPECT_EQ("hello.txt", file.filename);
  5056. EXPECT_EQ("text/plain", file.content_type);
  5057. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5058. }
  5059. {
  5060. const auto &file = get_file_value(items, "file2");
  5061. EXPECT_EQ("world.json", file.filename);
  5062. EXPECT_EQ("application/json", file.content_type);
  5063. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5064. }
  5065. {
  5066. const auto &file = get_file_value(items, "file3");
  5067. EXPECT_TRUE(file.filename.empty());
  5068. EXPECT_EQ("application/octet-stream", file.content_type);
  5069. EXPECT_EQ(0u, file.content.size());
  5070. }
  5071. } else {
  5072. std::string body;
  5073. content_reader([&](const char *data, size_t data_length) {
  5074. EXPECT_EQ(7U, data_length);
  5075. body.append(data, data_length);
  5076. return true;
  5077. });
  5078. EXPECT_EQ(body, "content");
  5079. res.set_content(body, "text/plain");
  5080. }
  5081. })
  5082. .Put("/content_receiver",
  5083. [&](const Request & /*req*/, Response &res,
  5084. const ContentReader &content_reader) {
  5085. std::string body;
  5086. content_reader([&](const char *data, size_t data_length) {
  5087. body.append(data, data_length);
  5088. return true;
  5089. });
  5090. EXPECT_EQ(body, "content");
  5091. res.set_content(body, "text/plain");
  5092. })
  5093. .Patch("/content_receiver",
  5094. [&](const Request & /*req*/, Response &res,
  5095. const ContentReader &content_reader) {
  5096. std::string body;
  5097. content_reader([&](const char *data, size_t data_length) {
  5098. body.append(data, data_length);
  5099. return true;
  5100. });
  5101. EXPECT_EQ(body, "content");
  5102. res.set_content(body, "text/plain");
  5103. })
  5104. .Post("/query-string-and-body",
  5105. [&](const Request &req, Response & /*res*/) {
  5106. ASSERT_TRUE(req.has_param("key"));
  5107. EXPECT_EQ(req.get_param_value("key"), "value");
  5108. EXPECT_EQ(req.body, "content");
  5109. })
  5110. .Get("/last-request",
  5111. [&](const Request &req, Response & /*res*/) {
  5112. EXPECT_EQ("close", req.get_header_value("Connection"));
  5113. })
  5114. .Get(R"(/redirect/(\d+))",
  5115. [&](const Request &req, Response &res) {
  5116. auto num = std::stoi(req.matches[1]) + 1;
  5117. std::string url = "/redirect/" + std::to_string(num);
  5118. res.set_redirect(url);
  5119. })
  5120. .Post("/binary",
  5121. [&](const Request &req, Response &res) {
  5122. EXPECT_EQ(4U, req.body.size());
  5123. EXPECT_EQ("application/octet-stream",
  5124. req.get_header_value("Content-Type"));
  5125. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5126. res.set_content(req.body, "application/octet-stream");
  5127. })
  5128. .Put("/binary",
  5129. [&](const Request &req, Response &res) {
  5130. EXPECT_EQ(4U, req.body.size());
  5131. EXPECT_EQ("application/octet-stream",
  5132. req.get_header_value("Content-Type"));
  5133. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5134. res.set_content(req.body, "application/octet-stream");
  5135. })
  5136. .Patch("/binary",
  5137. [&](const Request &req, Response &res) {
  5138. EXPECT_EQ(4U, req.body.size());
  5139. EXPECT_EQ("application/octet-stream",
  5140. req.get_header_value("Content-Type"));
  5141. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5142. res.set_content(req.body, "application/octet-stream");
  5143. })
  5144. .Delete("/binary",
  5145. [&](const Request &req, Response &res) {
  5146. EXPECT_EQ(4U, req.body.size());
  5147. EXPECT_EQ("application/octet-stream",
  5148. req.get_header_value("Content-Type"));
  5149. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5150. res.set_content(req.body, "application/octet-stream");
  5151. })
  5152. .Get("/issue1772",
  5153. [&](const Request & /*req*/, Response &res) {
  5154. res.status = 401;
  5155. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5156. })
  5157. .Delete("/issue609",
  5158. [](const httplib::Request &, httplib::Response &res,
  5159. const httplib::ContentReader &) {
  5160. res.set_content("ok", "text/plain");
  5161. })
  5162. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5163. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5164. .Get("/compress",
  5165. [&](const Request & /*req*/, Response &res) {
  5166. res.set_content(
  5167. "12345678901234567890123456789012345678901234567890123456789"
  5168. "01234567890123456789012345678901234567890",
  5169. "text/plain");
  5170. })
  5171. .Get("/compress-with-charset",
  5172. [&](const Request & /*req*/, Response &res) {
  5173. res.set_content(
  5174. "12345678901234567890123456789012345678901234567890123456789"
  5175. "01234567890123456789012345678901234567890",
  5176. "application/json; charset=utf-8");
  5177. })
  5178. .Get("/nocompress",
  5179. [&](const Request & /*req*/, Response &res) {
  5180. res.set_content(
  5181. "12345678901234567890123456789012345678901234567890123456789"
  5182. "01234567890123456789012345678901234567890",
  5183. "application/octet-stream");
  5184. })
  5185. .Post("/compress-multipart",
  5186. [&](const Request &req, Response & /*res*/) {
  5187. EXPECT_EQ(2u, req.form.fields.size());
  5188. ASSERT_TRUE(!req.form.has_field("???"));
  5189. {
  5190. const auto &text = req.form.get_field("key1");
  5191. EXPECT_EQ("test", text);
  5192. }
  5193. {
  5194. const auto &text = req.form.get_field("key2");
  5195. EXPECT_EQ("--abcdefg123", text);
  5196. }
  5197. })
  5198. #endif
  5199. ;
  5200. persons_["john"] = "programmer";
  5201. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5202. svr_.wait_until_ready();
  5203. }
  5204. virtual void TearDown() {
  5205. svr_.stop();
  5206. if (!request_threads_.empty()) {
  5207. std::this_thread::sleep_for(std::chrono::seconds(1));
  5208. for (auto &t : request_threads_) {
  5209. t.join();
  5210. }
  5211. }
  5212. t_.join();
  5213. }
  5214. map<string, string> persons_;
  5215. #ifdef CPPHTTPLIB_SSL_ENABLED
  5216. SSLClient cli_;
  5217. SSLServer svr_;
  5218. #else
  5219. Client cli_;
  5220. Server svr_;
  5221. #endif
  5222. thread t_;
  5223. std::vector<thread> request_threads_;
  5224. };
  5225. TEST_F(ServerTest, GetMethod200) {
  5226. auto res = cli_.Get("/hi");
  5227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5228. EXPECT_EQ("HTTP/1.1", res->version);
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. EXPECT_EQ("OK", res->reason);
  5231. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5232. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5233. EXPECT_EQ("Hello World!", res->body);
  5234. }
  5235. TEST_F(ServerTest, GetEmptyFile) {
  5236. auto res = cli_.Get("/empty_file");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. EXPECT_EQ(StatusCode::OK_200, res->status);
  5239. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5240. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5241. EXPECT_EQ("", res->body);
  5242. }
  5243. TEST_F(ServerTest, GetFileContent) {
  5244. auto res = cli_.Get("/file_content");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5248. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5249. EXPECT_EQ("test.html", res->body);
  5250. }
  5251. TEST_F(ServerTest, GetFileContentWithRange) {
  5252. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5255. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5256. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5257. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5258. EXPECT_EQ("est", res->body);
  5259. }
  5260. TEST_F(ServerTest, GetFileContentWithContentType) {
  5261. auto res = cli_.Get("/file_content_with_content_type");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5265. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5266. EXPECT_EQ("file\n", res->body);
  5267. }
  5268. TEST_F(ServerTest, GetInvalidFileContent) {
  5269. auto res = cli_.Get("/invalid_file_content");
  5270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5271. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5272. }
  5273. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5274. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ("HTTP/1.1", res->version);
  5277. EXPECT_EQ(StatusCode::OK_200, res->status);
  5278. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5279. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5280. EXPECT_EQ("Hello World!", res->body);
  5281. }
  5282. TEST_F(ServerTest, GetMethod302) {
  5283. auto res = cli_.Get("/");
  5284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5285. EXPECT_EQ(StatusCode::Found_302, res->status);
  5286. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5287. }
  5288. TEST_F(ServerTest, GetMethod302Redirect) {
  5289. cli_.set_follow_location(true);
  5290. auto res = cli_.Get("/");
  5291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5292. EXPECT_EQ(StatusCode::OK_200, res->status);
  5293. EXPECT_EQ("Hello World!", res->body);
  5294. EXPECT_EQ("/hi", res->location);
  5295. }
  5296. TEST_F(ServerTest, GetMethod404) {
  5297. auto res = cli_.Get("/invalid");
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5300. }
  5301. TEST_F(ServerTest, HeadMethod200) {
  5302. auto res = cli_.Head("/hi");
  5303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5304. EXPECT_EQ(StatusCode::OK_200, res->status);
  5305. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5306. EXPECT_TRUE(res->body.empty());
  5307. }
  5308. TEST_F(ServerTest, HeadMethod200Static) {
  5309. auto res = cli_.Head("/mount/dir/index.html");
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. EXPECT_EQ(StatusCode::OK_200, res->status);
  5312. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5313. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5314. EXPECT_TRUE(res->body.empty());
  5315. }
  5316. TEST_F(ServerTest, HeadMethod404) {
  5317. auto res = cli_.Head("/invalid");
  5318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5320. EXPECT_TRUE(res->body.empty());
  5321. }
  5322. TEST_F(ServerTest, GetMethodPersonJohn) {
  5323. auto res = cli_.Get("/person/john");
  5324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5325. EXPECT_EQ(StatusCode::OK_200, res->status);
  5326. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5327. EXPECT_EQ("programmer", res->body);
  5328. }
  5329. TEST_F(ServerTest, PostMethod1) {
  5330. auto res = cli_.Get("/person/john1");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5333. res = cli_.Post("/person", "name=john1&note=coder",
  5334. "application/x-www-form-urlencoded");
  5335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5336. ASSERT_EQ(StatusCode::OK_200, res->status);
  5337. res = cli_.Get("/person/john1");
  5338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5339. ASSERT_EQ(StatusCode::OK_200, res->status);
  5340. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5341. ASSERT_EQ("coder", res->body);
  5342. }
  5343. TEST_F(ServerTest, PostMethod2) {
  5344. auto res = cli_.Get("/person/john2");
  5345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5346. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5347. Params params;
  5348. params.emplace("name", "john2");
  5349. params.emplace("note", "coder");
  5350. res = cli_.Post("/person", params);
  5351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5352. ASSERT_EQ(StatusCode::OK_200, res->status);
  5353. res = cli_.Get("/person/john2");
  5354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5355. ASSERT_EQ(StatusCode::OK_200, res->status);
  5356. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5357. ASSERT_EQ("coder", res->body);
  5358. }
  5359. TEST_F(ServerTest, PutMethod3) {
  5360. auto res = cli_.Get("/person/john3");
  5361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5362. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5363. Params params;
  5364. params.emplace("name", "john3");
  5365. params.emplace("note", "coder");
  5366. res = cli_.Put("/person", params);
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. ASSERT_EQ(StatusCode::OK_200, res->status);
  5369. res = cli_.Get("/person/john3");
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. ASSERT_EQ(StatusCode::OK_200, res->status);
  5372. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5373. ASSERT_EQ("coder", res->body);
  5374. }
  5375. TEST_F(ServerTest, DeleteMethod1) {
  5376. auto res = cli_.Get("/person/john4");
  5377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5378. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5379. Params params;
  5380. params.emplace("name", "john4");
  5381. params.emplace("note", "coder");
  5382. res = cli_.Post("/person", params);
  5383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5384. ASSERT_EQ(StatusCode::OK_200, res->status);
  5385. res = cli_.Get("/person/john4");
  5386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5387. ASSERT_EQ(StatusCode::OK_200, res->status);
  5388. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5389. ASSERT_EQ("coder", res->body);
  5390. Params delete_params;
  5391. delete_params.emplace("name", "john4");
  5392. res = cli_.Delete("/person", delete_params);
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. ASSERT_EQ(StatusCode::OK_200, res->status);
  5395. ASSERT_EQ("DELETED", res->body);
  5396. res = cli_.Get("/person/john4");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5399. }
  5400. TEST_F(ServerTest, DeleteMethod2) {
  5401. auto res = cli_.Get("/person/john5");
  5402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5403. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5404. Params params;
  5405. params.emplace("name", "john5");
  5406. params.emplace("note", "developer");
  5407. res = cli_.Post("/person", params);
  5408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5409. ASSERT_EQ(StatusCode::OK_200, res->status);
  5410. res = cli_.Get("/person/john5");
  5411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5412. ASSERT_EQ(StatusCode::OK_200, res->status);
  5413. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5414. ASSERT_EQ("developer", res->body);
  5415. Params delete_params;
  5416. delete_params.emplace("name", "john5");
  5417. Headers headers;
  5418. headers.emplace("Custom-Header", "test-value");
  5419. res = cli_.Delete("/person", headers, delete_params);
  5420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5421. ASSERT_EQ(StatusCode::OK_200, res->status);
  5422. ASSERT_EQ("DELETED", res->body);
  5423. res = cli_.Get("/person/john5");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5426. }
  5427. TEST_F(ServerTest, DeleteMethod3) {
  5428. auto res = cli_.Get("/person/john6");
  5429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5430. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5431. Params params;
  5432. params.emplace("name", "john6");
  5433. params.emplace("note", "tester");
  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/john6");
  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("tester", res->body);
  5442. Params delete_params;
  5443. delete_params.emplace("name", "john6");
  5444. Headers headers;
  5445. headers.emplace("Custom-Header", "test-value");
  5446. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5448. ASSERT_EQ(StatusCode::OK_200, res->status);
  5449. ASSERT_EQ("DELETED", res->body);
  5450. res = cli_.Get("/person/john6");
  5451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5452. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5453. }
  5454. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5455. Params params;
  5456. params.emplace("json", JSON_DATA);
  5457. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. ASSERT_EQ(StatusCode::OK_200, res->status);
  5460. ASSERT_EQ(JSON_DATA, res->body);
  5461. }
  5462. TEST_F(ServerTest, PostEmptyContent) {
  5463. auto res = cli_.Post("/empty", "", "text/plain");
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. ASSERT_EQ(StatusCode::OK_200, res->status);
  5466. ASSERT_EQ("empty", res->body);
  5467. }
  5468. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5469. auto res = cli_.Post("/empty-no-content-type");
  5470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5471. ASSERT_EQ(StatusCode::OK_200, res->status);
  5472. ASSERT_EQ("empty-no-content-type", res->body);
  5473. }
  5474. TEST_F(ServerTest, PostPathOnly) {
  5475. auto res = cli_.Post("/path-only");
  5476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5477. ASSERT_EQ(StatusCode::OK_200, res->status);
  5478. ASSERT_EQ("path-only", res->body);
  5479. }
  5480. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5481. auto res = cli_.Post("/path-headers-only",
  5482. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5484. ASSERT_EQ(StatusCode::OK_200, res->status);
  5485. ASSERT_EQ("path-headers-only", res->body);
  5486. }
  5487. TEST_F(ServerTest, PostLarge) {
  5488. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5490. ASSERT_EQ(StatusCode::OK_200, res->status);
  5491. EXPECT_EQ(LARGE_DATA, res->body);
  5492. }
  5493. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5494. auto res = cli_.Put("/empty-no-content-type");
  5495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5496. ASSERT_EQ(StatusCode::OK_200, res->status);
  5497. ASSERT_EQ("empty-no-content-type", res->body);
  5498. }
  5499. TEST_F(ServerTest, GetMethodDir) {
  5500. auto res = cli_.Get("/dir/");
  5501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5502. EXPECT_EQ(StatusCode::OK_200, res->status);
  5503. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5504. auto body = R"(<html>
  5505. <head>
  5506. </head>
  5507. <body>
  5508. <a href="/dir/test.html">Test</a>
  5509. <a href="/hi">hi</a>
  5510. </body>
  5511. </html>
  5512. )";
  5513. EXPECT_EQ(body, res->body);
  5514. }
  5515. TEST_F(ServerTest, GetMethodDirTest) {
  5516. auto res = cli_.Get("/dir/test.html");
  5517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5518. EXPECT_EQ(StatusCode::OK_200, res->status);
  5519. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5520. EXPECT_EQ("test.html", res->body);
  5521. }
  5522. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5523. auto res = cli_.Get("/dir/../dir/test.html");
  5524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5525. EXPECT_EQ(StatusCode::OK_200, res->status);
  5526. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5527. EXPECT_EQ("test.html", res->body);
  5528. }
  5529. TEST_F(ServerTest, GetMethodInvalidPath) {
  5530. auto res = cli_.Get("/dir/../test.html");
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5533. }
  5534. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5535. auto res = cli_.Get("/../www/dir/test.html");
  5536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5537. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5538. }
  5539. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5540. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5543. }
  5544. TEST_F(ServerTest, GetMethodDirMountTest) {
  5545. auto res = cli_.Get("/mount/dir/test.html");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5549. EXPECT_EQ("test.html", res->body);
  5550. }
  5551. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5552. auto res = cli_.Get("/mount/dir/../dir/test.html");
  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. EXPECT_EQ("test.html", res->body);
  5557. }
  5558. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5559. auto res = cli_.Get("/mount/dir/../test.html");
  5560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5562. }
  5563. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5564. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5567. }
  5568. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5569. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5571. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5572. }
  5573. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5574. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5576. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5577. }
  5578. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5579. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5582. }
  5583. TEST_F(ServerTest, PostMethod303) {
  5584. auto res = cli_.Post("/1", "body", "text/plain");
  5585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5586. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5587. EXPECT_EQ("/2", res->get_header_value("Location"));
  5588. }
  5589. TEST_F(ServerTest, PostMethod303Redirect) {
  5590. cli_.set_follow_location(true);
  5591. auto res = cli_.Post("/1", "body", "text/plain");
  5592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5593. EXPECT_EQ(StatusCode::OK_200, res->status);
  5594. EXPECT_EQ("redirected.", res->body);
  5595. EXPECT_EQ("/2", res->location);
  5596. }
  5597. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5598. auto res = cli_.Get("/dir/test.abcde");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5602. EXPECT_EQ("abcde", res->body);
  5603. }
  5604. TEST_F(ServerTest, StaticFileRange) {
  5605. auto res =
  5606. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5608. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5609. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5610. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5611. EXPECT_EQ(true, res->has_header("Content-Range"));
  5612. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5613. EXPECT_EQ(std::string("cd"), res->body);
  5614. }
  5615. TEST_F(ServerTest, StaticFileRanges) {
  5616. auto res = cli_.Get("/dir/test.abcde",
  5617. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5619. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5620. EXPECT_TRUE(
  5621. res->get_header_value("Content-Type")
  5622. .find(
  5623. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5624. 0);
  5625. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5626. }
  5627. TEST_F(ServerTest, StaticFileRangeHead) {
  5628. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5630. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5631. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5632. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5633. EXPECT_EQ(true, res->has_header("Content-Range"));
  5634. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5635. }
  5636. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5637. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5639. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5641. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5642. EXPECT_EQ(true, res->has_header("Content-Range"));
  5643. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5644. res->get_header_value("Content-Range"));
  5645. EXPECT_EQ("LAST\n", res->body);
  5646. }
  5647. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5648. auto res =
  5649. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5652. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5653. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5654. EXPECT_EQ(true, res->has_header("Content-Range"));
  5655. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5656. }
  5657. TEST_F(ServerTest, StaticFileBigFile) {
  5658. auto res = cli_.Get("/dir/1MB.txt");
  5659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5660. EXPECT_EQ(StatusCode::OK_200, res->status);
  5661. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5662. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5663. }
  5664. TEST_F(ServerTest, InvalidBaseDirMount) {
  5665. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5666. }
  5667. TEST_F(ServerTest, Binary) {
  5668. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5669. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5670. "application/octet-stream");
  5671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5672. ASSERT_EQ(StatusCode::OK_200, res->status);
  5673. ASSERT_EQ(4U, res->body.size());
  5674. res = cli_.Put("/binary", binary.data(), binary.size(),
  5675. "application/octet-stream");
  5676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5677. ASSERT_EQ(StatusCode::OK_200, res->status);
  5678. ASSERT_EQ(4U, res->body.size());
  5679. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5680. "application/octet-stream");
  5681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5682. ASSERT_EQ(StatusCode::OK_200, res->status);
  5683. ASSERT_EQ(4U, res->body.size());
  5684. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5685. "application/octet-stream");
  5686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5687. ASSERT_EQ(StatusCode::OK_200, res->status);
  5688. ASSERT_EQ(4U, res->body.size());
  5689. }
  5690. TEST_F(ServerTest, BinaryString) {
  5691. auto binary = std::string("\x00\x01\x02\x03", 4);
  5692. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::OK_200, res->status);
  5695. ASSERT_EQ(4U, res->body.size());
  5696. res = cli_.Put("/binary", binary, "application/octet-stream");
  5697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5698. ASSERT_EQ(StatusCode::OK_200, res->status);
  5699. ASSERT_EQ(4U, res->body.size());
  5700. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5702. ASSERT_EQ(StatusCode::OK_200, res->status);
  5703. ASSERT_EQ(4U, res->body.size());
  5704. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5706. ASSERT_EQ(StatusCode::OK_200, res->status);
  5707. ASSERT_EQ(4U, res->body.size());
  5708. }
  5709. TEST_F(ServerTest, EmptyRequest) {
  5710. auto res = cli_.Get("");
  5711. ASSERT_TRUE(!res);
  5712. EXPECT_EQ(Error::Connection, res.error());
  5713. }
  5714. TEST_F(ServerTest, LongRequest) {
  5715. std::string request;
  5716. for (size_t i = 0; i < 545; i++) {
  5717. request += "/TooLongRequest";
  5718. }
  5719. request += "OK";
  5720. auto res = cli_.Get(request.c_str());
  5721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5723. }
  5724. TEST_F(ServerTest, TooLongRequest) {
  5725. std::string request;
  5726. for (size_t i = 0; i < 546; i++) {
  5727. request += "/TooLongRequest";
  5728. }
  5729. request += "_NG";
  5730. auto start = std::chrono::high_resolution_clock::now();
  5731. cli_.set_keep_alive(true);
  5732. auto res = cli_.Get(request.c_str());
  5733. auto end = std::chrono::high_resolution_clock::now();
  5734. auto elapsed =
  5735. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5736. .count();
  5737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5738. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5739. EXPECT_LE(elapsed, 1000);
  5740. EXPECT_EQ("close", res->get_header_value("Connection"));
  5741. EXPECT_FALSE(cli_.is_socket_open());
  5742. }
  5743. TEST_F(ServerTest, AlmostTooLongRequest) {
  5744. // test for #2046 - URI length check shouldn't include other content on req
  5745. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5746. // leading /, space, HTTP/1.1)
  5747. std::string request =
  5748. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5749. auto res = cli_.Get(request.c_str());
  5750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5752. }
  5753. TEST_F(ServerTest, LongHeader) {
  5754. Request req;
  5755. req.method = "GET";
  5756. req.path = "/hi";
  5757. std::string host_and_port;
  5758. host_and_port += HOST;
  5759. host_and_port += ":";
  5760. host_and_port += std::to_string(PORT);
  5761. req.headers.emplace("Host", host_and_port.c_str());
  5762. req.headers.emplace("Accept", "*/*");
  5763. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5764. req.headers.emplace(
  5765. "Header-Name",
  5766. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5767. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5768. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5794. "@@@@@@@@@@@@@@@@");
  5795. auto res = std::make_shared<Response>();
  5796. auto error = Error::Success;
  5797. auto ret = cli_.send(req, *res, error);
  5798. ASSERT_TRUE(ret);
  5799. EXPECT_EQ(StatusCode::OK_200, res->status);
  5800. }
  5801. TEST_F(ServerTest, LongQueryValue) {
  5802. auto start = std::chrono::high_resolution_clock::now();
  5803. cli_.set_keep_alive(true);
  5804. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5805. auto end = std::chrono::high_resolution_clock::now();
  5806. auto elapsed =
  5807. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5808. .count();
  5809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5810. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5811. EXPECT_LE(elapsed, 1000);
  5812. EXPECT_EQ("close", res->get_header_value("Connection"));
  5813. EXPECT_FALSE(cli_.is_socket_open());
  5814. }
  5815. TEST_F(ServerTest, TooLongQueryValue) {
  5816. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5817. ASSERT_FALSE(res);
  5818. EXPECT_EQ(Error::Read, res.error());
  5819. }
  5820. TEST_F(ServerTest, TooLongHeader) {
  5821. Request req;
  5822. req.method = "GET";
  5823. req.path = "/hi";
  5824. std::string host_and_port;
  5825. host_and_port += HOST;
  5826. host_and_port += ":";
  5827. host_and_port += std::to_string(PORT);
  5828. req.headers.emplace("Host", host_and_port.c_str());
  5829. req.headers.emplace("Accept", "*/*");
  5830. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5831. req.headers.emplace(
  5832. "Header-Name",
  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. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5860. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5861. "@@@@@@@@@@@@@@@@@");
  5862. auto res = std::make_shared<Response>();
  5863. auto error = Error::Success;
  5864. auto ret = cli_.send(req, *res, error);
  5865. ASSERT_TRUE(ret);
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. }
  5868. TEST_F(ServerTest, HeaderCountAtLimit) {
  5869. // Test with headers just under the 100 limit
  5870. httplib::Headers headers;
  5871. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5872. // This should keep us just under the 100 header limit
  5873. for (int i = 0; i < 95; i++) {
  5874. std::string name = "X-Test-Header-" + std::to_string(i);
  5875. std::string value = "value" + std::to_string(i);
  5876. headers.emplace(name, value);
  5877. }
  5878. // This should work fine as we're under the limit
  5879. auto res = cli_.Get("/hi", headers);
  5880. EXPECT_TRUE(res);
  5881. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5882. }
  5883. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5884. // Test with many headers to exceed the 100 limit
  5885. httplib::Headers headers;
  5886. // Add 150 headers to definitely exceed the 100 limit
  5887. for (int i = 0; i < 150; i++) {
  5888. std::string name = "X-Test-Header-" + std::to_string(i);
  5889. std::string value = "value" + std::to_string(i);
  5890. headers.emplace(name, value);
  5891. }
  5892. // This should fail due to exceeding header count limit
  5893. cli_.set_keep_alive(true);
  5894. auto res = cli_.Get("/hi", headers);
  5895. // The server should respond with 400 Bad Request
  5896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5897. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5898. EXPECT_EQ("close", res->get_header_value("Connection"));
  5899. EXPECT_FALSE(cli_.is_socket_open());
  5900. }
  5901. TEST_F(ServerTest, PercentEncoding) {
  5902. auto res = cli_.Get("/e%6edwith%");
  5903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5904. EXPECT_EQ(StatusCode::OK_200, res->status);
  5905. }
  5906. TEST_F(ServerTest, PercentEncodingUnicode) {
  5907. auto res = cli_.Get("/e%u006edwith%");
  5908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5909. EXPECT_EQ(StatusCode::OK_200, res->status);
  5910. }
  5911. TEST_F(ServerTest, InvalidPercentEncoding) {
  5912. auto res = cli_.Get("/%endwith%");
  5913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5914. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5915. }
  5916. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5917. auto res = cli_.Get("/%uendwith%");
  5918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5919. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5920. }
  5921. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5922. auto res = cli_.Get("/hello?aaa=bbb%");
  5923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5924. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5925. }
  5926. TEST_F(ServerTest, PlusSignEncoding) {
  5927. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5929. EXPECT_EQ(StatusCode::OK_200, res->status);
  5930. EXPECT_EQ("a +b", res->body);
  5931. }
  5932. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5933. // This test simulates a potential DoS attack using many headers
  5934. // to verify our security fix prevents memory exhaustion
  5935. httplib::Headers attack_headers;
  5936. // Attempt to add many headers like an attacker would (200 headers to far
  5937. // exceed limit)
  5938. for (int i = 0; i < 200; i++) {
  5939. std::string name = "X-Attack-Header-" + std::to_string(i);
  5940. std::string value = "attack_payload_" + std::to_string(i);
  5941. attack_headers.emplace(name, value);
  5942. }
  5943. // Try to POST with excessive headers
  5944. cli_.set_keep_alive(true);
  5945. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5946. // Should either fail or return 400 Bad Request due to security limit
  5947. if (res) {
  5948. // If we get a response, it should be 400 Bad Request
  5949. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5950. EXPECT_EQ("close", res->get_header_value("Connection"));
  5951. }
  5952. EXPECT_FALSE(cli_.is_socket_open());
  5953. }
  5954. TEST_F(ServerTest, MultipartFormData) {
  5955. UploadFormDataItems items = {
  5956. {"text1", "text default", "", ""},
  5957. {"text2", "aωb", "", ""},
  5958. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5959. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5960. {"file3", "", "", "application/octet-stream"},
  5961. {"file4", "", "", " application/json tmp-string "}};
  5962. auto res = cli_.Post("/multipart", items);
  5963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5964. EXPECT_EQ(StatusCode::OK_200, res->status);
  5965. }
  5966. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5967. UploadFormDataItems items = {
  5968. {"text", "default text", "", ""},
  5969. {"multi_text1", "aaaaa", "", ""},
  5970. {"multi_text1", "bbbbb", "", ""},
  5971. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5972. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5973. "application/json"},
  5974. };
  5975. auto res = cli_.Post("/multipart/multi_file_values", items);
  5976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5977. EXPECT_EQ(StatusCode::OK_200, res->status);
  5978. }
  5979. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5980. auto res = cli_.Get("/hi");
  5981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5982. EXPECT_EQ(StatusCode::OK_200, res->status);
  5983. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5984. EXPECT_EQ("Hello World!", res->body);
  5985. }
  5986. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5987. Request req;
  5988. req.method = "POST";
  5989. req.path = "/chunked";
  5990. std::string host_and_port;
  5991. host_and_port += HOST;
  5992. host_and_port += ":";
  5993. host_and_port += std::to_string(PORT);
  5994. req.headers.emplace("Host", host_and_port.c_str());
  5995. req.headers.emplace("Accept", "*/*");
  5996. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5997. req.headers.emplace("Content-Type", "text/plain");
  5998. req.headers.emplace("Content-Length", "0");
  5999. req.headers.emplace(
  6000. "Transfer-Encoding",
  6001. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6002. // Client does not chunk, so make a chunked body manually.
  6003. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6004. auto res = std::make_shared<Response>();
  6005. auto error = Error::Success;
  6006. auto ret = cli_.send(req, *res, error);
  6007. ASSERT_TRUE(ret);
  6008. EXPECT_EQ(StatusCode::OK_200, res->status);
  6009. }
  6010. template <typename ClientT>
  6011. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6012. int expected_status) {
  6013. Request req;
  6014. req.method = "POST";
  6015. req.path = "/chunked";
  6016. std::string host_and_port;
  6017. host_and_port += HOST;
  6018. host_and_port += ":";
  6019. host_and_port += std::to_string(PORT);
  6020. req.headers.emplace("Host", host_and_port.c_str());
  6021. req.headers.emplace("Content-Length", "0");
  6022. req.headers.emplace("Transfer-Encoding", "chunked");
  6023. req.body = body;
  6024. auto res = std::make_shared<Response>();
  6025. auto error = Error::Success;
  6026. ASSERT_TRUE(cli.send(req, *res, error));
  6027. EXPECT_EQ(expected_status, res->status);
  6028. }
  6029. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6030. // rather than treat them as valid lengths.
  6031. template <typename ClientT>
  6032. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6033. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6034. }
  6035. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6036. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6037. }
  6038. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6039. expect_chunked_body_rejected(
  6040. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6041. }
  6042. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6043. // chunk-size line carries no CR, LF or other control character ahead of its
  6044. // terminator. Such a line must be refused rather than read as extension text.
  6045. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6046. expect_chunked_body_rejected(
  6047. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6048. }
  6049. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6050. expect_chunked_body_rejected(
  6051. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6052. }
  6053. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6054. expect_chunked_body_rejected(
  6055. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6056. }
  6057. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6058. // The literal stays split: a hex escape consumes every hex digit that
  6059. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6060. expect_chunked_body_rejected(
  6061. cli_, "4;a\x01"
  6062. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6063. }
  6064. TEST_F(ServerTest, AcceptsChunkExtension) {
  6065. expect_chunked_body_status(cli_,
  6066. "4;name=value\r\ndech\r\n"
  6067. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6068. "0;last\r\n\r\n",
  6069. StatusCode::OK_200);
  6070. }
  6071. TEST_F(ServerTest, GetStreamed2) {
  6072. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6075. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6076. EXPECT_EQ(true, res->has_header("Content-Range"));
  6077. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6078. EXPECT_EQ(std::string("ab"), res->body);
  6079. }
  6080. TEST_F(ServerTest, GetStreamed) {
  6081. auto res = cli_.Get("/streamed");
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::OK_200, res->status);
  6084. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6085. EXPECT_EQ(std::string("aaabbb"), res->body);
  6086. }
  6087. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6088. auto res = cli_.Get("/streamed-without-length",
  6089. Headers{make_range_header({{0, -1}})});
  6090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6091. EXPECT_EQ(StatusCode::OK_200, res->status);
  6092. EXPECT_EQ(false, res->has_header("Content-Length"));
  6093. EXPECT_EQ(false, res->has_header("Content-Range"));
  6094. EXPECT_EQ(std::string("abcdefg"), res->body);
  6095. }
  6096. TEST_F(ServerTest, GetStreamedWithRange1) {
  6097. auto res =
  6098. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6101. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6102. EXPECT_EQ(true, res->has_header("Content-Range"));
  6103. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6104. EXPECT_EQ(std::string("def"), res->body);
  6105. }
  6106. TEST_F(ServerTest, GetStreamedWithRange2) {
  6107. auto res =
  6108. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6110. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6111. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6112. EXPECT_EQ(true, res->has_header("Content-Range"));
  6113. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6114. EXPECT_EQ(std::string("bcdefg"), res->body);
  6115. }
  6116. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6117. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6119. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6120. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6121. EXPECT_EQ(true, res->has_header("Content-Range"));
  6122. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6123. EXPECT_EQ(std::string("efg"), res->body);
  6124. }
  6125. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6126. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6127. // the entire representation.
  6128. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6129. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6131. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6132. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6133. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6134. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6135. }
  6136. }
  6137. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6138. auto res =
  6139. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6141. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6142. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6143. EXPECT_EQ(false, res->has_header("Content-Range"));
  6144. EXPECT_EQ(0U, res->body.size());
  6145. }
  6146. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6147. // Only a 206 is served as a partial representation. Under any other status
  6148. // `apply_ranges()` reported the full content length, so the body must match
  6149. // that header, and the content provider must never be asked for an offset
  6150. // outside the representation.
  6151. auto check = [&](int status, const char *range) {
  6152. auto path =
  6153. std::string("/streamed-with-range?status=") + std::to_string(status);
  6154. auto ctx = path + " Range: " + range;
  6155. auto res = cli_.Get(path, Headers{{"Range", range}});
  6156. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6157. EXPECT_EQ(status, res->status) << ctx;
  6158. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6160. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6161. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6162. };
  6163. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6164. check(403, "bytes=3-5");
  6165. // The offset is far past the representation.
  6166. check(403, "bytes=100000-100200");
  6167. // `first_pos` is still -1 here, and the bounds asserts in
  6168. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6169. check(403, "bytes=-3");
  6170. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6171. // multipart branch would have written one that is empty.
  6172. check(403, "bytes=1-2, 4-5");
  6173. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6174. // covers the whole representation.
  6175. check(200, "bytes=3-5");
  6176. check(200, "bytes=1-2, 4-5");
  6177. }
  6178. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6179. auto res =
  6180. cli_.Get("/streamed-with-range",
  6181. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6182. "92233720368547758079223372036854775807"}});
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6185. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6186. EXPECT_EQ(false, res->has_header("Content-Range"));
  6187. EXPECT_EQ(0U, res->body.size());
  6188. }
  6189. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6190. auto res = cli_.Get(
  6191. "/with-range",
  6192. Headers{{"Range",
  6193. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6194. {"Accept-Encoding", ""}});
  6195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6197. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6198. EXPECT_EQ(true, res->has_header("Content-Range"));
  6199. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6200. EXPECT_EQ(std::string("abcdefg"), res->body);
  6201. }
  6202. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6203. auto res = cli_.Get("/with-range", Headers{
  6204. {"Range", "bytes=0-"},
  6205. {"Accept-Encoding", ""},
  6206. });
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6209. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6210. EXPECT_EQ(true, res->has_header("Content-Range"));
  6211. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6212. EXPECT_EQ(std::string("abcdefg"), res->body);
  6213. }
  6214. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6215. auto res = cli_.Get("/streamed-with-range",
  6216. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6218. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6219. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6220. EXPECT_EQ(false, res->has_header("Content-Range"));
  6221. EXPECT_EQ(267U, res->body.size());
  6222. // Check that both range contents are present
  6223. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6224. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6225. // Check that Content-Range headers are present for both ranges
  6226. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6227. std::string::npos);
  6228. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6229. std::string::npos);
  6230. }
  6231. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6232. Ranges ranges;
  6233. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6234. ranges.emplace_back(0, -1);
  6235. }
  6236. auto res = cli_.Get("/streamed-with-range?error",
  6237. Headers{{make_range_header(ranges)}});
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6240. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6241. EXPECT_EQ(false, res->has_header("Content-Range"));
  6242. EXPECT_EQ(0U, res->body.size());
  6243. }
  6244. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6245. auto res = cli_.Get("/streamed-with-range",
  6246. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6249. EXPECT_EQ(5U, res->body.size());
  6250. // Check that overlapping ranges are coalesced into a single range
  6251. EXPECT_EQ("bcdef", res->body);
  6252. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6253. // Should be single range, not multipart
  6254. EXPECT_TRUE(res->has_header("Content-Range"));
  6255. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6256. }
  6257. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6258. auto res = cli_.Get("/streamed-with-range",
  6259. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6261. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6262. EXPECT_EQ(268U, res->body.size());
  6263. // Check that both range contents are present
  6264. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6265. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6266. // Check that Content-Range headers are present for both ranges
  6267. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6268. std::string::npos);
  6269. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6270. std::string::npos);
  6271. }
  6272. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6273. auto res = cli_.Get("/streamed-with-range",
  6274. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6277. EXPECT_EQ(269U, res->body.size());
  6278. // Check that both duplicate range contents are present
  6279. size_t first_abc = res->body.find("abc\r\n");
  6280. EXPECT_TRUE(first_abc != std::string::npos);
  6281. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6282. EXPECT_TRUE(second_abc != std::string::npos);
  6283. // Check that Content-Range headers are present for both ranges
  6284. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6285. EXPECT_TRUE(first_range != std::string::npos);
  6286. size_t second_range =
  6287. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6288. EXPECT_TRUE(second_range != std::string::npos);
  6289. }
  6290. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6291. auto res =
  6292. cli_.Get("/streamed-with-range?error",
  6293. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6296. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ(false, res->has_header("Content-Range"));
  6298. EXPECT_EQ(0U, res->body.size());
  6299. }
  6300. TEST_F(ServerTest, GetStreamedEndless) {
  6301. uint64_t offset = 0;
  6302. auto res = cli_.Get("/streamed-cancel",
  6303. [&](const char * /*data*/, uint64_t data_length) {
  6304. if (offset < 100) {
  6305. offset += data_length;
  6306. return true;
  6307. }
  6308. return false;
  6309. });
  6310. ASSERT_TRUE(!res);
  6311. EXPECT_EQ(Error::Canceled, res.error());
  6312. }
  6313. TEST_F(ServerTest, ClientStop) {
  6314. std::atomic_size_t count{4};
  6315. std::vector<std::thread> threads;
  6316. for (auto i = count.load(); i != 0; --i) {
  6317. threads.emplace_back([&]() {
  6318. auto res = cli_.Get("/streamed-cancel",
  6319. [&](const char *, uint64_t) { return true; });
  6320. --count;
  6321. ASSERT_TRUE(!res);
  6322. EXPECT_TRUE(res.error() == Error::Canceled ||
  6323. res.error() == Error::Read || res.error() == Error::Write);
  6324. });
  6325. }
  6326. std::this_thread::sleep_for(std::chrono::seconds(2));
  6327. while (count != 0) {
  6328. cli_.stop();
  6329. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6330. }
  6331. for (auto &t : threads) {
  6332. t.join();
  6333. }
  6334. }
  6335. TEST_F(ServerTest, GetWithRange1) {
  6336. auto res = cli_.Get("/with-range", Headers{
  6337. make_range_header({{3, 5}}),
  6338. {"Accept-Encoding", ""},
  6339. });
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6342. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6343. EXPECT_EQ(true, res->has_header("Content-Range"));
  6344. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6345. EXPECT_EQ(std::string("def"), res->body);
  6346. }
  6347. TEST_F(ServerTest, GetWithRange2) {
  6348. auto res = cli_.Get("/with-range", Headers{
  6349. make_range_header({{1, -1}}),
  6350. {"Accept-Encoding", ""},
  6351. });
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6354. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6355. EXPECT_EQ(true, res->has_header("Content-Range"));
  6356. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6357. EXPECT_EQ(std::string("bcdefg"), res->body);
  6358. }
  6359. TEST_F(ServerTest, GetWithRange3) {
  6360. auto res = cli_.Get("/with-range", Headers{
  6361. make_range_header({{0, 0}}),
  6362. {"Accept-Encoding", ""},
  6363. });
  6364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6365. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6366. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6367. EXPECT_EQ(true, res->has_header("Content-Range"));
  6368. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6369. EXPECT_EQ(std::string("a"), res->body);
  6370. }
  6371. TEST_F(ServerTest, GetWithRange4) {
  6372. auto res = cli_.Get("/with-range", Headers{
  6373. make_range_header({{-1, 2}}),
  6374. {"Accept-Encoding", ""},
  6375. });
  6376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6377. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6378. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6379. EXPECT_EQ(true, res->has_header("Content-Range"));
  6380. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6381. EXPECT_EQ(std::string("fg"), res->body);
  6382. }
  6383. TEST_F(ServerTest, GetWithRange5) {
  6384. auto res = cli_.Get("/with-range", Headers{
  6385. make_range_header({{0, 5}}),
  6386. {"Accept-Encoding", ""},
  6387. });
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6390. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6391. EXPECT_EQ(true, res->has_header("Content-Range"));
  6392. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6393. EXPECT_EQ(std::string("abcdef"), res->body);
  6394. }
  6395. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6396. auto res =
  6397. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6400. }
  6401. TEST_F(ServerTest, GetWithRangeMultipart) {
  6402. auto res =
  6403. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6406. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6407. EXPECT_EQ(false, res->has_header("Content-Range"));
  6408. EXPECT_EQ(267U, res->body.size());
  6409. }
  6410. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6411. auto res = cli_.Get("/with-range",
  6412. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6415. }
  6416. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6417. auto res = cli_.Get("/with-range-customized-response",
  6418. Headers{{make_range_header({{1, 2}})}});
  6419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6420. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6421. EXPECT_EQ(true, res->has_header("Content-Length"));
  6422. EXPECT_EQ(false, res->has_header("Content-Range"));
  6423. EXPECT_EQ(JSON_DATA, res->body);
  6424. }
  6425. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6426. auto res = cli_.Get("/with-range-customized-response",
  6427. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6430. EXPECT_EQ(true, res->has_header("Content-Length"));
  6431. EXPECT_EQ(false, res->has_header("Content-Range"));
  6432. EXPECT_EQ(JSON_DATA, res->body);
  6433. }
  6434. TEST_F(ServerTest, Issue1772) {
  6435. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6438. }
  6439. TEST_F(ServerTest, Issue609) {
  6440. auto res = cli_.Delete("/issue609");
  6441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6442. EXPECT_EQ(StatusCode::OK_200, res->status);
  6443. EXPECT_EQ(std::string("ok"), res->body);
  6444. }
  6445. TEST_F(ServerTest, GetStreamedChunked) {
  6446. auto res = cli_.Get("/streamed-chunked");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. EXPECT_EQ(StatusCode::OK_200, res->status);
  6449. EXPECT_EQ(std::string("123456789"), res->body);
  6450. }
  6451. TEST_F(ServerTest, GetStreamedChunked2) {
  6452. auto res = cli_.Get("/streamed-chunked2");
  6453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6454. EXPECT_EQ(StatusCode::OK_200, res->status);
  6455. EXPECT_EQ(std::string("123456789"), res->body);
  6456. }
  6457. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6458. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6460. EXPECT_EQ(StatusCode::OK_200, res->status);
  6461. EXPECT_EQ(std::string("123456789"), res->body);
  6462. EXPECT_TRUE(res->has_header("Trailer"));
  6463. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6464. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6465. // Trailers are now stored separately from headers (security fix)
  6466. EXPECT_EQ(2U, res->trailers.size());
  6467. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6468. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6469. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6470. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6471. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6472. // Verify trailers are NOT in headers (security verification)
  6473. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6474. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6475. }
  6476. TEST_F(ServerTest, LargeChunkedPost) {
  6477. Request req;
  6478. req.method = "POST";
  6479. req.path = "/large-chunked";
  6480. std::string host_and_port;
  6481. host_and_port += HOST;
  6482. host_and_port += ":";
  6483. host_and_port += std::to_string(PORT);
  6484. req.headers.emplace("Host", host_and_port.c_str());
  6485. req.headers.emplace("Accept", "*/*");
  6486. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6487. req.headers.emplace("Content-Type", "text/plain");
  6488. req.headers.emplace("Content-Length", "0");
  6489. req.headers.emplace("Transfer-Encoding", "chunked");
  6490. std::string long_string(30 * 1024u, 'a');
  6491. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6492. // Attempt to make a large enough post to exceed OS buffers, to test that
  6493. // the server handles short reads if the full chunk data isn't available.
  6494. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6495. auto res = std::make_shared<Response>();
  6496. auto error = Error::Success;
  6497. auto ret = cli_.send(req, *res, error);
  6498. ASSERT_TRUE(ret);
  6499. EXPECT_EQ(StatusCode::OK_200, res->status);
  6500. }
  6501. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6502. auto res = cli_.Get("/remote_addr");
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::OK_200, res->status);
  6505. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6506. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6507. }
  6508. TEST_F(ServerTest, GetMethodLocalAddr) {
  6509. auto res = cli_.Get("/local_addr");
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6513. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6514. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6515. }
  6516. TEST_F(ServerTest, HTTPResponseSplitting) {
  6517. auto res = cli_.Get("/http_response_splitting");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. EXPECT_EQ(StatusCode::OK_200, res->status);
  6520. }
  6521. TEST_F(ServerTest, SlowRequest) {
  6522. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6523. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6524. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6525. }
  6526. #if 0
  6527. TEST_F(ServerTest, SlowPost) {
  6528. char buffer[64 * 1024];
  6529. memset(buffer, 0x42, sizeof(buffer));
  6530. auto res = cli_.Post(
  6531. "/slowpost", 64 * 1024 * 1024,
  6532. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6533. auto ret = sink.write(buffer, sizeof(buffer));
  6534. EXPECT_TRUE(ret);
  6535. return true;
  6536. },
  6537. "text/plain");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. EXPECT_EQ(StatusCode::OK_200, res->status);
  6540. }
  6541. TEST_F(ServerTest, SlowPostFail) {
  6542. char buffer[64 * 1024];
  6543. memset(buffer, 0x42, sizeof(buffer));
  6544. cli_.set_write_timeout(std::chrono::seconds(0));
  6545. auto res = cli_.Post(
  6546. "/slowpost", 64 * 1024 * 1024,
  6547. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6548. sink.write(buffer, sizeof(buffer));
  6549. return true;
  6550. },
  6551. "text/plain");
  6552. ASSERT_TRUE(!res);
  6553. EXPECT_EQ(Error::Write, res.error());
  6554. }
  6555. #endif
  6556. TEST_F(ServerTest, Put) {
  6557. auto res = cli_.Put("/put", "PUT", "text/plain");
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. EXPECT_EQ(StatusCode::OK_200, res->status);
  6560. EXPECT_EQ("PUT", res->body);
  6561. }
  6562. TEST_F(ServerTest, PutWithContentProvider) {
  6563. auto res = cli_.Put(
  6564. "/put", 3,
  6565. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6566. sink.os << "PUT";
  6567. return true;
  6568. },
  6569. "text/plain");
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. EXPECT_EQ("PUT", res->body);
  6573. }
  6574. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6575. auto res = cli_.Post(
  6576. "/post", 42,
  6577. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6578. return false;
  6579. },
  6580. "text/plain");
  6581. ASSERT_TRUE(!res);
  6582. EXPECT_EQ(Error::Canceled, res.error());
  6583. }
  6584. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6585. auto res = cli_.Put(
  6586. "/put",
  6587. [](size_t /*offset*/, DataSink &sink) {
  6588. sink.os << "PUT";
  6589. sink.done();
  6590. return true;
  6591. },
  6592. "text/plain");
  6593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6594. EXPECT_EQ(StatusCode::OK_200, res->status);
  6595. EXPECT_EQ("PUT", res->body);
  6596. }
  6597. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6598. auto res = cli_.Post(
  6599. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6600. "text/plain");
  6601. ASSERT_TRUE(!res);
  6602. EXPECT_EQ(Error::Canceled, res.error());
  6603. }
  6604. TEST_F(ServerTest, PostLoopBack) {
  6605. std::string body;
  6606. auto res = cli_.Post(
  6607. "/post-loopback", 9,
  6608. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6609. EXPECT_EQ(9u, length);
  6610. sink.write("123", 3);
  6611. sink.write("456", 3);
  6612. sink.write("789", 3);
  6613. return true;
  6614. },
  6615. "text/plain",
  6616. [&body](const char *data, size_t data_length) {
  6617. body.append(data, data_length);
  6618. return true;
  6619. });
  6620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6621. EXPECT_EQ(StatusCode::OK_200, res->status);
  6622. EXPECT_EQ("123456789", body);
  6623. }
  6624. TEST_F(ServerTest, PutLoopBack) {
  6625. std::string body;
  6626. auto res = cli_.Put(
  6627. "/put-loopback", 9,
  6628. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6629. EXPECT_EQ(9u, length);
  6630. sink.write("123", 3);
  6631. sink.write("456", 3);
  6632. sink.write("789", 3);
  6633. return true;
  6634. },
  6635. "text/plain",
  6636. [&body](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. EXPECT_EQ(StatusCode::OK_200, res->status);
  6642. EXPECT_EQ("123456789", body);
  6643. }
  6644. TEST_F(ServerTest, PatchLoopBack) {
  6645. std::string body;
  6646. auto res = cli_.Patch(
  6647. "/patch-loopback", 9,
  6648. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6649. EXPECT_EQ(9u, length);
  6650. sink.write("123", 3);
  6651. sink.write("456", 3);
  6652. sink.write("789", 3);
  6653. return true;
  6654. },
  6655. "text/plain",
  6656. [&body](const char *data, size_t data_length) {
  6657. body.append(data, data_length);
  6658. return true;
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::OK_200, res->status);
  6662. EXPECT_EQ("123456789", body);
  6663. }
  6664. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6665. std::string body;
  6666. auto res = cli_.Post(
  6667. "/post-loopback",
  6668. [](size_t /*offset*/, DataSink &sink) {
  6669. sink.write("123", 3);
  6670. sink.write("456", 3);
  6671. sink.write("789", 3);
  6672. sink.done();
  6673. return true;
  6674. },
  6675. "text/plain",
  6676. [&body](const char *data, size_t data_length) {
  6677. body.append(data, data_length);
  6678. return true;
  6679. });
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ(StatusCode::OK_200, res->status);
  6682. EXPECT_EQ("123456789", body);
  6683. }
  6684. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6685. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6686. cli_.set_compress(true);
  6687. auto res = cli_.Put(
  6688. "/put", 3,
  6689. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6690. sink.os << "PUT";
  6691. return true;
  6692. },
  6693. "text/plain");
  6694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6695. EXPECT_EQ(StatusCode::OK_200, res->status);
  6696. EXPECT_EQ("PUT", res->body);
  6697. }
  6698. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6699. cli_.set_compress(true);
  6700. auto res = cli_.Post(
  6701. "/post", 42,
  6702. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6703. return false;
  6704. },
  6705. "text/plain");
  6706. ASSERT_TRUE(!res);
  6707. EXPECT_EQ(Error::Canceled, res.error());
  6708. }
  6709. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6710. cli_.set_compress(true);
  6711. auto res = cli_.Put(
  6712. "/put",
  6713. [](size_t /*offset*/, DataSink &sink) {
  6714. sink.os << "PUT";
  6715. sink.done();
  6716. return true;
  6717. },
  6718. "text/plain");
  6719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6720. EXPECT_EQ(StatusCode::OK_200, res->status);
  6721. EXPECT_EQ("PUT", res->body);
  6722. }
  6723. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6724. cli_.set_compress(true);
  6725. auto res = cli_.Post(
  6726. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6727. "text/plain");
  6728. ASSERT_TRUE(!res);
  6729. EXPECT_EQ(Error::Canceled, res.error());
  6730. }
  6731. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6732. cli_.set_compress(true);
  6733. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. EXPECT_EQ(LARGE_DATA, res->body);
  6737. }
  6738. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6739. #ifdef CPPHTTPLIB_SSL_ENABLED
  6740. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6741. Client cli(s.c_str());
  6742. cli.enable_server_certificate_verification(false);
  6743. #else
  6744. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6745. Client cli(s.c_str());
  6746. #endif
  6747. cli.set_compress(true);
  6748. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ(LARGE_DATA, res->body);
  6752. // The compressed size should be less than a 10th of the original. May vary
  6753. // depending on the zlib library.
  6754. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6755. static_cast<uint64_t>(10 * 1024 * 1024));
  6756. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6757. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6758. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6759. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6760. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6761. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6762. #endif
  6763. }
  6764. TEST_F(ServerTest, PutContentWithDeflate) {
  6765. cli_.set_compress(false);
  6766. Headers headers;
  6767. headers.emplace("Content-Encoding", "deflate");
  6768. // PUT in deflate format:
  6769. auto res = cli_.Put("/put", headers,
  6770. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::OK_200, res->status);
  6773. EXPECT_EQ("PUT", res->body);
  6774. }
  6775. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6776. Headers headers;
  6777. headers.emplace("Accept-Encoding", "gzip, deflate");
  6778. auto res = cli_.Get("/streamed-chunked", headers);
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::OK_200, res->status);
  6781. EXPECT_EQ(std::string("123456789"), res->body);
  6782. }
  6783. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6784. Headers headers;
  6785. headers.emplace("Accept-Encoding", "gzip, deflate");
  6786. auto res = cli_.Get("/streamed-chunked2", headers);
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. EXPECT_EQ(std::string("123456789"), res->body);
  6790. }
  6791. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6792. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::OK_200, res->status);
  6795. }
  6796. TEST(GzipDecompressor, ChunkedDecompression) {
  6797. std::string data;
  6798. for (size_t i = 0; i < 32 * 1024; ++i) {
  6799. data.push_back(static_cast<char>('a' + i % 26));
  6800. }
  6801. std::string compressed_data;
  6802. {
  6803. httplib::detail::gzip_compressor compressor;
  6804. bool result = compressor.compress(
  6805. data.data(), data.size(),
  6806. /*last=*/true,
  6807. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6808. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6809. compressed_data_size);
  6810. return true;
  6811. });
  6812. ASSERT_TRUE(result);
  6813. }
  6814. std::string decompressed_data;
  6815. {
  6816. httplib::detail::gzip_decompressor decompressor;
  6817. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6818. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6819. size_t chunk_size = 130;
  6820. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6821. chunk_begin += chunk_size) {
  6822. size_t current_chunk_size =
  6823. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6824. bool result = decompressor.decompress(
  6825. compressed_data.data() + chunk_begin, current_chunk_size,
  6826. [&](const char *decompressed_data_chunk,
  6827. size_t decompressed_data_chunk_size) {
  6828. decompressed_data.insert(decompressed_data.size(),
  6829. decompressed_data_chunk,
  6830. decompressed_data_chunk_size);
  6831. return true;
  6832. });
  6833. ASSERT_TRUE(result);
  6834. }
  6835. }
  6836. ASSERT_EQ(data, decompressed_data);
  6837. }
  6838. TEST(GzipDecompressor, DeflateDecompression) {
  6839. std::string original_text = "Raw deflate without gzip";
  6840. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6841. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6842. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6843. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6844. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6845. std::string decompressed_data;
  6846. {
  6847. httplib::detail::gzip_decompressor decompressor;
  6848. bool result = decompressor.decompress(
  6849. compressed_data.data(), compressed_data.size(),
  6850. [&](const char *decompressed_data_chunk,
  6851. size_t decompressed_data_chunk_size) {
  6852. decompressed_data.insert(decompressed_data.size(),
  6853. decompressed_data_chunk,
  6854. decompressed_data_chunk_size);
  6855. return true;
  6856. });
  6857. ASSERT_TRUE(result);
  6858. }
  6859. ASSERT_EQ(original_text, decompressed_data);
  6860. }
  6861. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6862. std::string original_text = "Raw deflate without gzip";
  6863. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6864. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6865. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6866. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6867. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6868. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6869. std::string decompressed_data;
  6870. {
  6871. httplib::detail::gzip_decompressor decompressor;
  6872. bool result = decompressor.decompress(
  6873. compressed_data.data(), compressed_data.size(),
  6874. [&](const char *decompressed_data_chunk,
  6875. size_t decompressed_data_chunk_size) {
  6876. decompressed_data.insert(decompressed_data.size(),
  6877. decompressed_data_chunk,
  6878. decompressed_data_chunk_size);
  6879. return true;
  6880. });
  6881. ASSERT_TRUE(result);
  6882. }
  6883. ASSERT_EQ(original_text, decompressed_data);
  6884. }
  6885. #endif
  6886. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6887. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6888. Headers headers;
  6889. headers.emplace("Accept-Encoding", "br");
  6890. auto res = cli_.Get("/streamed-chunked", headers);
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. EXPECT_EQ(StatusCode::OK_200, res->status);
  6893. EXPECT_EQ(std::string("123456789"), res->body);
  6894. }
  6895. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6896. Headers headers;
  6897. headers.emplace("Accept-Encoding", "br");
  6898. auto res = cli_.Get("/streamed-chunked2", headers);
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. EXPECT_EQ(std::string("123456789"), res->body);
  6902. }
  6903. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6904. cli_.set_compress(true);
  6905. auto res = cli_.Put(
  6906. "/put", 3,
  6907. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6908. sink.os << "PUT";
  6909. return true;
  6910. },
  6911. "text/plain");
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. EXPECT_EQ("PUT", res->body);
  6915. }
  6916. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6917. cli_.set_compress(true);
  6918. auto res = cli_.Put(
  6919. "/put",
  6920. [](size_t /*offset*/, DataSink &sink) {
  6921. sink.os << "PUT";
  6922. sink.done();
  6923. return true;
  6924. },
  6925. "text/plain");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. EXPECT_EQ(StatusCode::OK_200, res->status);
  6928. EXPECT_EQ("PUT", res->body);
  6929. }
  6930. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6931. cli_.set_compress(true);
  6932. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. EXPECT_EQ(StatusCode::OK_200, res->status);
  6935. EXPECT_EQ(LARGE_DATA, res->body);
  6936. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6937. }
  6938. #endif
  6939. TEST_F(ServerTest, Patch) {
  6940. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::OK_200, res->status);
  6943. EXPECT_EQ("PATCH", res->body);
  6944. }
  6945. TEST_F(ServerTest, Delete) {
  6946. auto res = cli_.Delete("/delete");
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. EXPECT_EQ("DELETE", res->body);
  6950. }
  6951. TEST_F(ServerTest, DeleteContentReceiver) {
  6952. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. EXPECT_EQ(StatusCode::OK_200, res->status);
  6955. EXPECT_EQ("content", res->body);
  6956. }
  6957. TEST_F(ServerTest, Options) {
  6958. auto res = cli_.Options("*");
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. EXPECT_EQ(StatusCode::OK_200, res->status);
  6961. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6962. EXPECT_TRUE(res->body.empty());
  6963. }
  6964. TEST_F(ServerTest, URL) {
  6965. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. }
  6969. TEST_F(ServerTest, ArrayParam) {
  6970. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::OK_200, res->status);
  6973. }
  6974. TEST_F(ServerTest, ArrayParamValues) {
  6975. auto res =
  6976. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. TEST_F(ServerTest, NoMultipleHeaders) {
  6981. Headers headers = {{"Content-Length", "5"}};
  6982. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6983. "text/plain");
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. EXPECT_EQ(StatusCode::OK_200, res->status);
  6986. }
  6987. TEST_F(ServerTest, PostContentReceiver) {
  6988. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6990. ASSERT_EQ(StatusCode::OK_200, res->status);
  6991. ASSERT_EQ("content", res->body);
  6992. }
  6993. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6994. UploadFormDataItems items = {
  6995. {"text1", "text default", "", ""},
  6996. {"text2", "aωb", "", ""},
  6997. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6998. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6999. {"file3", "", "", "application/octet-stream"},
  7000. };
  7001. auto res = cli_.Post("/content_receiver", items);
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. }
  7005. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7006. UploadFormDataItems items = {
  7007. {"text1", "text default", "", ""},
  7008. {"text2", "aωb", "", ""},
  7009. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7010. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7011. {"file3", "", "", "application/octet-stream"},
  7012. };
  7013. auto boundary = std::string("+++++");
  7014. std::string body;
  7015. for (const auto &item : items) {
  7016. body += "--" + boundary + "\r\n";
  7017. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7018. if (!item.filename.empty()) {
  7019. body += "; filename=\"" + item.filename + "\"";
  7020. }
  7021. body += "\r\n";
  7022. if (!item.content_type.empty()) {
  7023. body += "Content-Type: " + item.content_type + "\r\n";
  7024. }
  7025. body += "\r\n";
  7026. body += item.content + "\r\n";
  7027. }
  7028. body += "--" + boundary + "--\r\n";
  7029. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7030. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::OK_200, res->status);
  7033. }
  7034. TEST(MultipartFormDataTest, FieldEscaping) {
  7035. Server svr;
  7036. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7037. const ContentReader &content_reader) {
  7038. ASSERT_TRUE(req.is_multipart_form_data());
  7039. std::vector<FormData> received;
  7040. content_reader(
  7041. [&](const FormData &file) {
  7042. received.push_back(file);
  7043. return true;
  7044. },
  7045. [&](const char *data, size_t data_length) {
  7046. received.back().content.append(data, data_length);
  7047. return true;
  7048. });
  7049. // '"', CR and LF in names and filenames are escaped following the
  7050. // WHATWG HTML standard, so each part still parses as a single part
  7051. // with no injected headers. Content types get CR/LF escaped too,
  7052. // while '"' (legal there, e.g. quoted charset) is preserved.
  7053. ASSERT_EQ(4U, received.size());
  7054. EXPECT_EQ("na%22me", received[0].name);
  7055. EXPECT_EQ("quoted name", received[0].content);
  7056. EXPECT_EQ("file", received[1].name);
  7057. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7058. received[1].filename);
  7059. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7060. EXPECT_EQ("injected", received[1].content);
  7061. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7062. EXPECT_EQ("my%22file.txt", received[2].filename);
  7063. EXPECT_EQ("cr lf name", received[2].content);
  7064. EXPECT_EQ("typed", received[3].name);
  7065. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7066. received[3].content_type);
  7067. EXPECT_EQ("typed content", received[3].content);
  7068. });
  7069. auto port = svr.bind_to_any_port("localhost");
  7070. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7071. auto se = detail::scope_exit([&] {
  7072. svr.stop();
  7073. t.join();
  7074. ASSERT_FALSE(svr.is_running());
  7075. });
  7076. svr.wait_until_ready();
  7077. Client cli("localhost", port);
  7078. UploadFormDataItems items = {
  7079. {"na\"me", "quoted name", "", ""},
  7080. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7081. "application/octet-stream"},
  7082. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7083. {"typed", "typed content", "",
  7084. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7085. };
  7086. auto res = cli.Post("/post", items);
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::OK_200, res->status);
  7089. }
  7090. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7091. const UploadFormDataItems items = {
  7092. {"name1", "Content 1", "", ""},
  7093. {"name2", "Content 2", "file2.txt", "text/plain"},
  7094. };
  7095. Server svr;
  7096. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7097. const ContentReader &content_reader) {
  7098. ASSERT_TRUE(req.is_multipart_form_data());
  7099. std::vector<FormData> received;
  7100. content_reader(
  7101. [&](const FormData &file) {
  7102. received.push_back(file);
  7103. return true;
  7104. },
  7105. [&](const char *data, size_t data_length) {
  7106. received.back().content.append(data, data_length);
  7107. return true;
  7108. });
  7109. ASSERT_EQ(2U, received.size());
  7110. EXPECT_EQ("name1", received[0].name);
  7111. EXPECT_EQ("Content 1", received[0].content);
  7112. EXPECT_EQ("name2", received[1].name);
  7113. EXPECT_EQ("Content 2", received[1].content);
  7114. EXPECT_EQ("file2.txt", received[1].filename);
  7115. EXPECT_EQ("text/plain", received[1].content_type);
  7116. });
  7117. auto port = svr.bind_to_any_port("localhost");
  7118. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7119. auto se = detail::scope_exit([&] {
  7120. svr.stop();
  7121. t.join();
  7122. ASSERT_FALSE(svr.is_running());
  7123. });
  7124. svr.wait_until_ready();
  7125. Client cli("localhost", port);
  7126. // Whole-body serialization with a generated boundary
  7127. {
  7128. MultipartFormDataWriter writer;
  7129. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7130. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7131. writer.content_type());
  7132. auto body = writer.serialize(items);
  7133. EXPECT_EQ(body.size(), writer.content_length(items));
  7134. auto res = cli.Post("/post", body, writer.content_type());
  7135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7136. EXPECT_EQ(StatusCode::OK_200, res->status);
  7137. }
  7138. // Per-part framing with a custom boundary via a content provider
  7139. {
  7140. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7141. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7142. MultipartFormDataWriter writer("custom-boundary_123");
  7143. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7144. std::string body;
  7145. for (const auto &item : items) {
  7146. body += writer.item_begin(item);
  7147. body += item.content;
  7148. body += MultipartFormDataWriter::item_end();
  7149. }
  7150. body += writer.finish();
  7151. EXPECT_EQ(body.size(), writer.content_length(items));
  7152. auto res = cli.Post(
  7153. "/post", body.size(),
  7154. [&](size_t offset, size_t length, DataSink &sink) {
  7155. sink.write(body.data() + offset, length);
  7156. return true;
  7157. },
  7158. writer.content_type());
  7159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7160. EXPECT_EQ(StatusCode::OK_200, res->status);
  7161. }
  7162. }
  7163. TEST_F(ServerTest, PostContentReceiverGzip) {
  7164. cli_.set_compress(true);
  7165. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. ASSERT_EQ(StatusCode::OK_200, res->status);
  7168. ASSERT_EQ("content", res->body);
  7169. }
  7170. TEST_F(ServerTest, PutContentReceiver) {
  7171. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. ASSERT_EQ(StatusCode::OK_200, res->status);
  7174. ASSERT_EQ("content", res->body);
  7175. }
  7176. TEST_F(ServerTest, PatchContentReceiver) {
  7177. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. ASSERT_EQ(StatusCode::OK_200, res->status);
  7180. ASSERT_EQ("content", res->body);
  7181. }
  7182. template <typename ClientType>
  7183. void TestWithHeadersAndContentReceiver(
  7184. ClientType &cli,
  7185. std::function<Result(ClientType &, const std::string &, const Headers &,
  7186. const std::string &, const std::string &,
  7187. ContentReceiver, DownloadProgress)>
  7188. request_func) {
  7189. Headers headers;
  7190. headers.emplace("X-Custom-Header", "test-value");
  7191. std::string received_body;
  7192. auto res = request_func(
  7193. cli, "/content_receiver", headers, "content", "application/json",
  7194. [&](const char *data, size_t data_length) {
  7195. received_body.append(data, data_length);
  7196. return true;
  7197. },
  7198. nullptr);
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. EXPECT_EQ("content", received_body);
  7202. }
  7203. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7204. #ifdef CPPHTTPLIB_SSL_ENABLED
  7205. using ClientT = SSLClient;
  7206. #else
  7207. using ClientT = Client;
  7208. #endif
  7209. TestWithHeadersAndContentReceiver<ClientT>(
  7210. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7211. const std::string &body, const std::string &content_type,
  7212. ContentReceiver receiver, DownloadProgress progress) {
  7213. return cli.Post(path, headers, body, content_type, receiver, progress);
  7214. });
  7215. }
  7216. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7217. #ifdef CPPHTTPLIB_SSL_ENABLED
  7218. using ClientT = SSLClient;
  7219. #else
  7220. using ClientT = Client;
  7221. #endif
  7222. TestWithHeadersAndContentReceiver<ClientT>(
  7223. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7224. const std::string &body, const std::string &content_type,
  7225. ContentReceiver receiver, DownloadProgress progress) {
  7226. return cli.Put(path, headers, body, content_type, receiver, progress);
  7227. });
  7228. }
  7229. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7230. #ifdef CPPHTTPLIB_SSL_ENABLED
  7231. using ClientT = SSLClient;
  7232. #else
  7233. using ClientT = Client;
  7234. #endif
  7235. TestWithHeadersAndContentReceiver<ClientT>(
  7236. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7237. const std::string &body, const std::string &content_type,
  7238. ContentReceiver receiver, DownloadProgress progress) {
  7239. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7240. });
  7241. }
  7242. template <typename ClientType>
  7243. void TestWithHeadersAndContentReceiverWithProgress(
  7244. ClientType &cli,
  7245. std::function<Result(ClientType &, const std::string &, const Headers &,
  7246. const std::string &, const std::string &,
  7247. ContentReceiver, DownloadProgress)>
  7248. request_func) {
  7249. Headers headers;
  7250. headers.emplace("X-Test-Header", "progress-test");
  7251. std::string received_body;
  7252. auto progress_called = false;
  7253. auto res = request_func(
  7254. cli, "/content_receiver", headers, "content", "text/plain",
  7255. [&](const char *data, size_t data_length) {
  7256. received_body.append(data, data_length);
  7257. return true;
  7258. },
  7259. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7260. progress_called = true;
  7261. return true;
  7262. });
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. EXPECT_EQ(StatusCode::OK_200, res->status);
  7265. EXPECT_EQ("content", received_body);
  7266. EXPECT_TRUE(progress_called);
  7267. }
  7268. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7269. #ifdef CPPHTTPLIB_SSL_ENABLED
  7270. using ClientT = SSLClient;
  7271. #else
  7272. using ClientT = Client;
  7273. #endif
  7274. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7276. const std::string &body, const std::string &content_type,
  7277. ContentReceiver receiver, DownloadProgress progress) {
  7278. return cli.Post(path, headers, body, content_type, receiver, progress);
  7279. });
  7280. }
  7281. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7282. #ifdef CPPHTTPLIB_SSL_ENABLED
  7283. using ClientT = SSLClient;
  7284. #else
  7285. using ClientT = Client;
  7286. #endif
  7287. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7288. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7289. const std::string &body, const std::string &content_type,
  7290. ContentReceiver receiver, DownloadProgress progress) {
  7291. return cli.Put(path, headers, body, content_type, receiver, progress);
  7292. });
  7293. }
  7294. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7295. #ifdef CPPHTTPLIB_SSL_ENABLED
  7296. using ClientT = SSLClient;
  7297. #else
  7298. using ClientT = Client;
  7299. #endif
  7300. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7301. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7302. const std::string &body, const std::string &content_type,
  7303. ContentReceiver receiver, DownloadProgress progress) {
  7304. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7305. });
  7306. }
  7307. template <typename ClientType>
  7308. void TestWithHeadersAndContentReceiverError(
  7309. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7310. const Headers &, const std::string &,
  7311. const std::string &, ContentReceiver)>
  7312. request_func) {
  7313. Headers headers;
  7314. headers.emplace("X-Error-Test", "true");
  7315. std::string received_body;
  7316. auto receiver_failed = false;
  7317. auto res =
  7318. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7319. [&](const char *data, size_t data_length) {
  7320. received_body.append(data, data_length);
  7321. receiver_failed = true;
  7322. return false;
  7323. });
  7324. ASSERT_FALSE(res);
  7325. EXPECT_TRUE(receiver_failed);
  7326. }
  7327. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7328. #ifdef CPPHTTPLIB_SSL_ENABLED
  7329. using ClientT = SSLClient;
  7330. #else
  7331. using ClientT = Client;
  7332. #endif
  7333. TestWithHeadersAndContentReceiverError<ClientT>(
  7334. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7335. const std::string &body, const std::string &content_type,
  7336. ContentReceiver receiver) {
  7337. return cli.Post(path, headers, body, content_type, receiver);
  7338. });
  7339. }
  7340. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7341. #ifdef CPPHTTPLIB_SSL_ENABLED
  7342. using ClientT = SSLClient;
  7343. #else
  7344. using ClientT = Client;
  7345. #endif
  7346. TestWithHeadersAndContentReceiverError<ClientT>(
  7347. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7348. const std::string &body, const std::string &content_type,
  7349. ContentReceiver receiver) {
  7350. return cli.Put(path, headers, body, content_type, receiver);
  7351. });
  7352. }
  7353. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7354. #ifdef CPPHTTPLIB_SSL_ENABLED
  7355. using ClientT = SSLClient;
  7356. #else
  7357. using ClientT = Client;
  7358. #endif
  7359. TestWithHeadersAndContentReceiverError<ClientT>(
  7360. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7361. const std::string &body, const std::string &content_type,
  7362. ContentReceiver receiver) {
  7363. return cli.Patch(path, headers, body, content_type, receiver);
  7364. });
  7365. }
  7366. TEST_F(ServerTest, PostQueryStringAndBody) {
  7367. auto res =
  7368. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. ASSERT_EQ(StatusCode::OK_200, res->status);
  7371. }
  7372. TEST_F(ServerTest, HTTP2Magic) {
  7373. Request req;
  7374. req.method = "PRI";
  7375. req.path = "*";
  7376. req.body = "SM";
  7377. auto res = std::make_shared<Response>();
  7378. auto error = Error::Success;
  7379. auto ret = cli_.send(req, *res, error);
  7380. ASSERT_TRUE(ret);
  7381. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7382. }
  7383. TEST_F(ServerTest, KeepAlive) {
  7384. auto res = cli_.Get("/hi");
  7385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7386. EXPECT_EQ(StatusCode::OK_200, res->status);
  7387. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7388. EXPECT_EQ("Hello World!", res->body);
  7389. res = cli_.Get("/hi");
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::OK_200, res->status);
  7392. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7393. EXPECT_EQ("Hello World!", res->body);
  7394. res = cli_.Get("/hi");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7398. EXPECT_EQ("Hello World!", res->body);
  7399. res = cli_.Get("/not-exist");
  7400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7401. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7402. res = cli_.Post("/empty", "", "text/plain");
  7403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7404. EXPECT_EQ(StatusCode::OK_200, res->status);
  7405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7406. EXPECT_EQ("empty", res->body);
  7407. EXPECT_EQ("close", res->get_header_value("Connection"));
  7408. res = cli_.Post(
  7409. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7410. "text/plain");
  7411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7412. EXPECT_EQ(StatusCode::OK_200, res->status);
  7413. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7414. EXPECT_EQ("empty", res->body);
  7415. cli_.set_keep_alive(false);
  7416. res = cli_.Get("/last-request");
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::OK_200, res->status);
  7419. EXPECT_EQ("close", res->get_header_value("Connection"));
  7420. }
  7421. TEST_F(ServerTest, TooManyRedirect) {
  7422. cli_.set_follow_location(true);
  7423. auto res = cli_.Get("/redirect/0");
  7424. ASSERT_TRUE(!res);
  7425. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7426. }
  7427. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7428. Request req;
  7429. req.method = "FOOBAR";
  7430. req.path = "/hi";
  7431. cli_.set_keep_alive(true);
  7432. auto res = cli_.send(req);
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7435. EXPECT_EQ("close", res->get_header_value("Connection"));
  7436. EXPECT_FALSE(cli_.is_socket_open());
  7437. }
  7438. TEST_F(ServerTest, CustomRouteReadsBody) {
  7439. const std::string xml =
  7440. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7441. Request req;
  7442. req.method = "PROPFIND";
  7443. req.path = "/dav/dir";
  7444. req.set_header("Depth", "1");
  7445. req.body = xml;
  7446. auto res = cli_.send(req);
  7447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7448. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7449. EXPECT_EQ(xml, res->body);
  7450. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7451. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7452. }
  7453. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7454. Request req;
  7455. req.method = "PROPFIND";
  7456. req.path = "/dav/42";
  7457. auto res = cli_.send(req);
  7458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7459. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7460. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7461. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7462. }
  7463. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7464. Request req;
  7465. req.method = "PROPFIND";
  7466. req.path = "/dav-re/123";
  7467. auto res = cli_.send(req);
  7468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7469. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7470. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7471. }
  7472. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7473. Request req;
  7474. req.method = "MKCOL";
  7475. req.path = "/dav-mkcol";
  7476. auto res = cli_.send(req);
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::Created_201, res->status);
  7479. }
  7480. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7481. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7482. Request req;
  7483. req.method = "REPORT";
  7484. req.path = "/dav-report";
  7485. req.body = xml;
  7486. auto res = cli_.send(req);
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7489. EXPECT_EQ(xml, res->body);
  7490. }
  7491. // A content reader route must fire even when the request carries no body,
  7492. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7493. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7494. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7495. Request req;
  7496. req.method = "REPORT";
  7497. req.path = "/dav-report";
  7498. auto res = cli_.send(req);
  7499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7500. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7501. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7502. }
  7503. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7504. Request req;
  7505. req.method = "PROPFIND";
  7506. req.path = "/not-dav";
  7507. auto res = cli_.send(req);
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7510. }
  7511. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7512. Request req;
  7513. req.method = "UNLOCK";
  7514. req.path = "/dav/dir";
  7515. cli_.set_keep_alive(true);
  7516. auto res = cli_.send(req);
  7517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7519. EXPECT_EQ("close", res->get_header_value("Connection"));
  7520. EXPECT_FALSE(cli_.is_socket_open());
  7521. }
  7522. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7523. // The mount point serves this path, but only for GET and HEAD.
  7524. auto get_res = cli_.Get("/dir/index.html");
  7525. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7526. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7527. Request req;
  7528. req.method = "PROPFIND";
  7529. req.path = "/dir/index.html";
  7530. auto res = cli_.send(req);
  7531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7532. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7533. }
  7534. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7535. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7536. cli_.set_keep_alive(true);
  7537. for (auto i = 0; i < 2; i++) {
  7538. Request req;
  7539. req.method = "PROPFIND";
  7540. req.path = "/dav/dir";
  7541. req.body = xml;
  7542. auto res = cli_.send(req);
  7543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7544. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7545. EXPECT_EQ(xml, res->body);
  7546. EXPECT_TRUE(cli_.is_socket_open());
  7547. }
  7548. // A built-in method must still be served on the same connection.
  7549. cli_.set_keep_alive(false);
  7550. auto res = cli_.Get("/hi");
  7551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7552. EXPECT_EQ(StatusCode::OK_200, res->status);
  7553. EXPECT_EQ("close", res->get_header_value("Connection"));
  7554. }
  7555. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7556. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7557. Request req;
  7558. req.method = "PROPFIND";
  7559. req.path = "/dav/dir";
  7560. req.set_header("Expect", "100-continue");
  7561. req.body = xml;
  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(xml, res->body);
  7566. }
  7567. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7568. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7569. TEST_F(ServerTest, Gzip) {
  7570. Headers headers;
  7571. headers.emplace("Accept-Encoding", "gzip, deflate");
  7572. auto res = cli_.Get("/compress", headers);
  7573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7574. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7576. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7577. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7578. "7890123456789012345678901234567890",
  7579. res->body);
  7580. EXPECT_EQ(StatusCode::OK_200, res->status);
  7581. }
  7582. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7583. Headers headers;
  7584. headers.emplace("Accept-Encoding", "gzip, deflate");
  7585. auto res = cli_.Get("/compress-with-charset", headers);
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7588. EXPECT_EQ("application/json; charset=utf-8",
  7589. res->get_header_value("Content-Type"));
  7590. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7591. "7890123456789012345678901234567890",
  7592. res->body);
  7593. EXPECT_EQ(StatusCode::OK_200, res->status);
  7594. }
  7595. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7596. Headers headers;
  7597. headers.emplace("Accept-Encoding", "");
  7598. auto res = cli_.Get("/compress", headers);
  7599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7600. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7602. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7603. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7604. "7890123456789012345678901234567890",
  7605. res->body);
  7606. EXPECT_EQ(StatusCode::OK_200, res->status);
  7607. }
  7608. TEST_F(ServerTest, GzipWithContentReceiver) {
  7609. Headers headers;
  7610. headers.emplace("Accept-Encoding", "gzip, deflate");
  7611. std::string body;
  7612. auto res = cli_.Get("/compress", headers,
  7613. [&](const char *data, uint64_t data_length) {
  7614. EXPECT_EQ(100U, data_length);
  7615. body.append(data, data_length);
  7616. return true;
  7617. });
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7620. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7621. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7622. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7623. "7890123456789012345678901234567890",
  7624. body);
  7625. EXPECT_EQ(StatusCode::OK_200, res->status);
  7626. }
  7627. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7628. Headers headers;
  7629. headers.emplace("Accept-Encoding", "gzip, deflate");
  7630. cli_.set_decompress(false);
  7631. auto res = cli_.Get("/compress", headers);
  7632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7633. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7634. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7635. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7636. EXPECT_EQ(33U, res->body.size());
  7637. EXPECT_EQ(StatusCode::OK_200, res->status);
  7638. }
  7639. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7640. Headers headers;
  7641. headers.emplace("Accept-Encoding", "");
  7642. std::string body;
  7643. auto res = cli_.Get("/compress", headers,
  7644. [&](const char *data, uint64_t data_length) {
  7645. EXPECT_EQ(100U, data_length);
  7646. body.append(data, data_length);
  7647. return true;
  7648. });
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7652. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7654. "7890123456789012345678901234567890",
  7655. body);
  7656. EXPECT_EQ(StatusCode::OK_200, res->status);
  7657. }
  7658. TEST_F(ServerTest, NoGzip) {
  7659. Headers headers;
  7660. headers.emplace("Accept-Encoding", "gzip, deflate");
  7661. auto res = cli_.Get("/nocompress", headers);
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7664. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7665. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7667. "7890123456789012345678901234567890",
  7668. res->body);
  7669. EXPECT_EQ(StatusCode::OK_200, res->status);
  7670. }
  7671. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7672. Headers headers;
  7673. headers.emplace("Accept-Encoding", "gzip, deflate");
  7674. std::string body;
  7675. auto res = cli_.Get("/nocompress", headers,
  7676. [&](const char *data, uint64_t data_length) {
  7677. EXPECT_EQ(100U, data_length);
  7678. body.append(data, data_length);
  7679. return true;
  7680. });
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7683. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7684. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7686. "7890123456789012345678901234567890",
  7687. body);
  7688. EXPECT_EQ(StatusCode::OK_200, res->status);
  7689. }
  7690. TEST_F(ServerTest, MultipartFormDataGzip) {
  7691. UploadFormDataItems items = {
  7692. {"key1", "test", "", ""},
  7693. {"key2", "--abcdefg123", "", ""},
  7694. };
  7695. cli_.set_compress(true);
  7696. auto res = cli_.Post("/compress-multipart", items);
  7697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7698. EXPECT_EQ(StatusCode::OK_200, res->status);
  7699. }
  7700. #endif
  7701. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7702. // Static file compression is opt-in, so these run their own server rather than
  7703. // flipping it on for the shared ServerTest fixture, which would silently
  7704. // rewrite what every other static file test is asserting.
  7705. class StaticFileCompressionTest : public ::testing::Test {
  7706. protected:
  7707. void TearDown() override {
  7708. if (t_.joinable()) {
  7709. svr_.stop();
  7710. t_.join();
  7711. }
  7712. }
  7713. int start(const std::function<void(Server &)> &configure = nullptr) {
  7714. // Serves the same tree as a directory of build-time compressed assets
  7715. // would be served: the mount point names the coding the files are already
  7716. // stored in. Registered before "/" so it is the one that matches.
  7717. svr_.set_mount_point("/pre-encoded", "./www",
  7718. {{"Content-Encoding", "gzip"}});
  7719. svr_.set_mount_point("/", "./www");
  7720. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7721. res.set_file_content("./www/dir/index.html", "text/html");
  7722. });
  7723. svr_.Get("/pre-encoded-file-content",
  7724. [](const Request & /*req*/, Response &res) {
  7725. res.set_header("Content-Encoding", "gzip");
  7726. res.set_file_content("./www/dir/index.html", "text/html");
  7727. });
  7728. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7729. res.set_content_provider(
  7730. 6, "text/plain",
  7731. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7732. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7733. return true;
  7734. });
  7735. });
  7736. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7737. res.set_content_provider(
  7738. 1000, "text/plain",
  7739. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7740. if (offset < 100) {
  7741. std::string data(100, 'A');
  7742. sink.write(data.data(), data.size());
  7743. return true;
  7744. }
  7745. std::this_thread::sleep_for(std::chrono::seconds(2));
  7746. std::string data(900, 'B');
  7747. sink.write(data.data(), data.size());
  7748. return true;
  7749. });
  7750. });
  7751. if (configure) { configure(svr_); }
  7752. auto port = svr_.bind_to_any_port(HOST);
  7753. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7754. svr_.wait_until_ready();
  7755. return port;
  7756. }
  7757. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7758. // Every file under ./www except 1MB.txt is smaller than the default
  7759. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7760. // it out of the way.
  7761. static void enable_without_floor(Server &svr) {
  7762. svr.set_static_file_compression(true);
  7763. svr.set_static_file_compression_min_length(0);
  7764. }
  7765. Server svr_;
  7766. std::thread t_;
  7767. };
  7768. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7769. auto port = start();
  7770. Client cli(HOST, port);
  7771. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7773. EXPECT_EQ(StatusCode::OK_200, res->status);
  7774. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7775. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7776. EXPECT_EQ(1048576U, res->body.size());
  7777. }
  7778. TEST_F(StaticFileCompressionTest, MountPoint) {
  7779. auto port = start(enable);
  7780. Client cli(HOST, port);
  7781. cli.set_decompress(false);
  7782. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::OK_200, res->status);
  7785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7786. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7787. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7788. // The response stays self-delimiting: a length, not a chunked body.
  7789. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7790. EXPECT_EQ(std::to_string(res->body.size()),
  7791. res->get_header_value("Content-Length"));
  7792. EXPECT_LT(res->body.size(), 1048576U);
  7793. EXPECT_FALSE(res->body.empty());
  7794. }
  7795. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7796. auto port = start(enable);
  7797. Client cli(HOST, port);
  7798. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::OK_200, res->status);
  7801. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7802. EXPECT_EQ(1048576U, res->body.size());
  7803. }
  7804. TEST_F(StaticFileCompressionTest, FileContent) {
  7805. auto port = start(enable_without_floor);
  7806. Client cli(HOST, port);
  7807. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7811. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7812. EXPECT_EQ(104U, res->body.size());
  7813. }
  7814. // A handler that serves an already-encoded file names the coding itself. The
  7815. // file-backed path decided its coding from Accept-Encoding and the content
  7816. // type alone, so it compressed the stored bytes a second time and appended a
  7817. // second Content-Encoding field line.
  7818. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7819. auto port = start(enable_without_floor);
  7820. Client cli(HOST, port);
  7821. cli.set_decompress(false);
  7822. auto res = cli.Get("/pre-encoded-file-content",
  7823. Headers{{"Accept-Encoding", "gzip"}});
  7824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7825. EXPECT_EQ(StatusCode::OK_200, res->status);
  7826. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7827. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7828. // Vary belongs to a coding the server chose, and it chose none here.
  7829. EXPECT_FALSE(res->has_header("Vary"));
  7830. // The file travels exactly as it is stored on disk.
  7831. EXPECT_EQ(104U, res->body.size());
  7832. }
  7833. // The 1MB file clears the default floor, so this one runs the configuration a
  7834. // deployment would actually have.
  7835. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7836. auto port = start(enable);
  7837. Client cli(HOST, port);
  7838. cli.set_decompress(false);
  7839. auto res =
  7840. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7844. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7845. EXPECT_FALSE(res->has_header("Vary"));
  7846. EXPECT_EQ(1048576U, res->body.size());
  7847. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7848. }
  7849. TEST_F(StaticFileCompressionTest, Head) {
  7850. auto port = start(enable);
  7851. Client cli(HOST, port);
  7852. cli.set_decompress(false);
  7853. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7854. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7855. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7859. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7860. // HEAD still reports the size a GET would return.
  7861. EXPECT_EQ(get->get_header_value("Content-Length"),
  7862. res->get_header_value("Content-Length"));
  7863. EXPECT_TRUE(res->body.empty());
  7864. }
  7865. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7866. auto port = start(enable);
  7867. Client cli(HOST, port);
  7868. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7869. {"Accept-Encoding", "gzip"}});
  7870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7871. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7872. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7873. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7874. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7875. EXPECT_EQ("cd", res->body);
  7876. }
  7877. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7878. auto port = start(enable);
  7879. Client cli(HOST, port);
  7880. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7884. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7885. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7886. }
  7887. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7888. auto port = start(enable);
  7889. Client cli(HOST, port);
  7890. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7892. EXPECT_EQ(StatusCode::OK_200, res->status);
  7893. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7894. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7895. EXPECT_TRUE(res->body.empty());
  7896. }
  7897. TEST_F(StaticFileCompressionTest, MinLength) {
  7898. auto port = start(enable);
  7899. Client cli(HOST, port);
  7900. // 104 bytes, well under the default floor. Compressing it would add the
  7901. // gzip header and trailer to a body that already fits in one packet.
  7902. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::OK_200, res->status);
  7905. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7906. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7907. }
  7908. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7909. auto port = start([](Server &svr) {
  7910. svr.set_static_file_compression(true);
  7911. svr.set_static_file_compression_min_length(1);
  7912. });
  7913. Client cli(HOST, port);
  7914. cli.set_decompress(false);
  7915. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7918. // A 9-byte file comes back larger than it went in, because gzip's header and
  7919. // trailer outweigh anything deflate can save. That is the end of the range
  7920. // the floor exists to keep out.
  7921. EXPECT_GT(res->body.size(), 9U);
  7922. }
  7923. TEST_F(StaticFileCompressionTest, MaxLength) {
  7924. auto port = start([](Server &svr) {
  7925. svr.set_static_file_compression(true);
  7926. svr.set_static_file_compression_min_length(0);
  7927. svr.set_static_file_compression_max_length(1024);
  7928. });
  7929. Client cli(HOST, port);
  7930. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7931. // defines `small` as a macro on Windows.
  7932. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7933. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7934. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7935. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7936. // Under it: compressed.
  7937. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7938. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7939. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7940. }
  7941. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7942. auto port = start(enable_without_floor);
  7943. Client cli(HOST, port);
  7944. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7945. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7946. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7947. auto identity_etag = identity->get_header_value("ETag");
  7948. ASSERT_FALSE(identity_etag.empty());
  7949. auto gzipped =
  7950. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7951. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7952. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7953. auto gzip_etag = gzipped->get_header_value("ETag");
  7954. ASSERT_FALSE(gzip_etag.empty());
  7955. // Two representations, two validators.
  7956. EXPECT_NE(identity_etag, gzip_etag);
  7957. // Each one revalidates against the request that would produce it...
  7958. auto fresh =
  7959. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7960. {"If-None-Match", gzip_etag}});
  7961. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7962. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7963. auto fresh_identity =
  7964. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7965. {"If-None-Match", identity_etag}});
  7966. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7967. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7968. // ...and not against the other representation.
  7969. auto crossed =
  7970. cli.Get("/dir/index.html",
  7971. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7972. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7973. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7974. }
  7975. // The opt-in covers responses the server reads off disk itself. A caller's own
  7976. // known-length provider keeps its Content-Length and, more importantly, keeps
  7977. // delivering incrementally: routing it through a compressor would hold every
  7978. // write back until zlib's window filled.
  7979. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7980. auto port = start(enable);
  7981. Client cli(HOST, port);
  7982. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7987. EXPECT_EQ("aaabbb", res->body);
  7988. }
  7989. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7990. auto port = start(enable);
  7991. Client cli(HOST, port);
  7992. cli.set_read_timeout(1, 0);
  7993. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7994. Headers{{"Accept-Encoding", "gzip"}});
  7995. ASSERT_TRUE(handle.is_valid());
  7996. // The provider writes 100 bytes and then stalls for longer than the read
  7997. // timeout. Those first bytes have to arrive anyway: run the response through
  7998. // a compressor and zlib holds them until its window fills, so the read would
  7999. // come back empty instead.
  8000. char buf[256];
  8001. auto n = handle.read(buf, sizeof(buf));
  8002. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8003. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8004. }
  8005. #endif
  8006. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8007. TEST_F(ServerTest, Brotli) {
  8008. Headers headers;
  8009. headers.emplace("Accept-Encoding", "br");
  8010. auto res = cli_.Get("/compress", headers);
  8011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8012. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8013. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8014. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8015. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8016. "7890123456789012345678901234567890",
  8017. res->body);
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. }
  8020. #endif
  8021. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8022. TEST_F(ServerTest, Zstd) {
  8023. Headers headers;
  8024. headers.emplace("Accept-Encoding", "zstd");
  8025. auto res = cli_.Get("/compress", headers);
  8026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8027. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8028. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8029. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8030. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8031. "7890123456789012345678901234567890",
  8032. res->body);
  8033. EXPECT_EQ(StatusCode::OK_200, res->status);
  8034. }
  8035. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8036. Headers headers;
  8037. headers.emplace("Accept-Encoding", "");
  8038. auto res = cli_.Get("/compress", headers);
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8041. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8042. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8043. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8044. "7890123456789012345678901234567890",
  8045. res->body);
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. }
  8048. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8049. Headers headers;
  8050. headers.emplace("Accept-Encoding", "zstd");
  8051. std::string body;
  8052. auto res = cli_.Get("/compress", headers,
  8053. [&](const char *data, uint64_t data_length) {
  8054. EXPECT_EQ(100U, data_length);
  8055. body.append(data, data_length);
  8056. return true;
  8057. });
  8058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8059. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8061. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8062. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8063. "7890123456789012345678901234567890",
  8064. body);
  8065. EXPECT_EQ(StatusCode::OK_200, res->status);
  8066. }
  8067. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8068. Headers headers;
  8069. headers.emplace("Accept-Encoding", "zstd");
  8070. cli_.set_decompress(false);
  8071. auto res = cli_.Get("/compress", headers);
  8072. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8073. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8074. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8075. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8078. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8079. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8080. EXPECT_EQ(StatusCode::OK_200, res->status);
  8081. ASSERT_EQ(26U, res->body.size());
  8082. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8083. 0);
  8084. }
  8085. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8086. Headers headers;
  8087. headers.emplace("Accept-Encoding", "");
  8088. std::string body;
  8089. auto res = cli_.Get("/compress", headers,
  8090. [&](const char *data, uint64_t data_length) {
  8091. EXPECT_EQ(100U, data_length);
  8092. body.append(data, data_length);
  8093. return true;
  8094. });
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8097. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8098. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8099. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8100. "7890123456789012345678901234567890",
  8101. body);
  8102. EXPECT_EQ(StatusCode::OK_200, res->status);
  8103. }
  8104. TEST_F(ServerTest, NoZstd) {
  8105. Headers headers;
  8106. headers.emplace("Accept-Encoding", "zstd");
  8107. auto res = cli_.Get("/nocompress", headers);
  8108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8109. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8110. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8111. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8112. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8113. "7890123456789012345678901234567890",
  8114. res->body);
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. }
  8117. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8118. Headers headers;
  8119. headers.emplace("Accept-Encoding", "zstd");
  8120. std::string body;
  8121. auto res = cli_.Get("/nocompress", headers,
  8122. [&](const char *data, uint64_t data_length) {
  8123. EXPECT_EQ(100U, data_length);
  8124. body.append(data, data_length);
  8125. return true;
  8126. });
  8127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8128. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8129. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8130. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8131. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8132. "7890123456789012345678901234567890",
  8133. body);
  8134. EXPECT_EQ(StatusCode::OK_200, res->status);
  8135. }
  8136. // TODO: How to enable zstd ??
  8137. TEST_F(ServerTest, MultipartFormDataZstd) {
  8138. UploadFormDataItems items = {
  8139. {"key1", "test", "", ""},
  8140. {"key2", "--abcdefg123", "", ""},
  8141. };
  8142. Headers headers;
  8143. headers.emplace("Accept-Encoding", "zstd");
  8144. cli_.set_compress(true);
  8145. auto res = cli_.Post("/compress-multipart", headers, items);
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::OK_200, res->status);
  8148. }
  8149. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8150. Headers headers;
  8151. headers.emplace("Accept-Encoding", "zstd");
  8152. cli_.set_compress(true);
  8153. auto res = cli_.Put(
  8154. "/put", headers, 3,
  8155. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8156. sink.os << "PUT";
  8157. return true;
  8158. },
  8159. "text/plain");
  8160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8161. EXPECT_EQ(StatusCode::OK_200, res->status);
  8162. EXPECT_EQ("PUT", res->body);
  8163. }
  8164. // Pre-compression logging tests
  8165. TEST_F(ServerTest, PreCompressionLogging) {
  8166. // Test data for compression (matches the actual /compress endpoint content)
  8167. const std::string test_content =
  8168. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8169. "3456789012345678901234567890";
  8170. // Variables to capture logging data
  8171. std::string pre_compression_body;
  8172. std::string pre_compression_content_type;
  8173. std::string pre_compression_content_encoding;
  8174. std::string post_compression_body;
  8175. std::string post_compression_content_type;
  8176. std::string post_compression_content_encoding;
  8177. // Set up pre-compression logger
  8178. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8179. const Response &res) {
  8180. pre_compression_body = res.body;
  8181. pre_compression_content_type = res.get_header_value("Content-Type");
  8182. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8183. });
  8184. // Set up post-compression logger
  8185. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8186. post_compression_body = res.body;
  8187. post_compression_content_type = res.get_header_value("Content-Type");
  8188. post_compression_content_encoding =
  8189. res.get_header_value("Content-Encoding");
  8190. });
  8191. // Test with gzip compression
  8192. Headers headers;
  8193. headers.emplace("Accept-Encoding", "gzip");
  8194. auto res = cli_.Get("/compress", headers);
  8195. // Verify response was compressed
  8196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8197. EXPECT_EQ(StatusCode::OK_200, res->status);
  8198. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8199. // Verify pre-compression logger captured uncompressed content
  8200. EXPECT_EQ(test_content, pre_compression_body);
  8201. EXPECT_EQ("text/plain", pre_compression_content_type);
  8202. EXPECT_TRUE(pre_compression_content_encoding
  8203. .empty()); // No encoding header before compression
  8204. // Verify post-compression logger captured compressed content
  8205. EXPECT_NE(test_content,
  8206. post_compression_body); // Should be different after compression
  8207. EXPECT_EQ("text/plain", post_compression_content_type);
  8208. EXPECT_EQ("gzip", post_compression_content_encoding);
  8209. // Verify compressed content is smaller
  8210. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8211. }
  8212. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8213. const std::string test_content =
  8214. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8215. "3456789012345678901234567890";
  8216. std::string pre_compression_body;
  8217. std::string post_compression_body;
  8218. svr_.set_pre_compression_logger(
  8219. [&](const Request & /*req*/, const Response &res) {
  8220. pre_compression_body = res.body;
  8221. });
  8222. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8223. post_compression_body = res.body;
  8224. });
  8225. Headers headers;
  8226. headers.emplace("Accept-Encoding", "br");
  8227. auto res = cli_.Get("/compress", headers);
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8231. // Verify pre-compression content is uncompressed
  8232. EXPECT_EQ(test_content, pre_compression_body);
  8233. // Verify post-compression content is compressed
  8234. EXPECT_NE(test_content, post_compression_body);
  8235. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8236. }
  8237. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8238. const std::string test_content =
  8239. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8240. "3456789012345678901234567890";
  8241. std::string pre_compression_body;
  8242. std::string post_compression_body;
  8243. svr_.set_pre_compression_logger(
  8244. [&](const Request & /*req*/, const Response &res) {
  8245. pre_compression_body = res.body;
  8246. });
  8247. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8248. post_compression_body = res.body;
  8249. });
  8250. // Request without compression (use /nocompress endpoint)
  8251. Headers headers;
  8252. auto res = cli_.Get("/nocompress", headers);
  8253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8254. EXPECT_EQ(StatusCode::OK_200, res->status);
  8255. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8256. // Pre-compression logger should not be called when no compression is applied
  8257. EXPECT_TRUE(
  8258. pre_compression_body.empty()); // Pre-compression logger not called
  8259. EXPECT_EQ(
  8260. test_content,
  8261. post_compression_body); // Post-compression logger captures final content
  8262. }
  8263. TEST_F(ServerTest, LoggerSeesContentLength) {
  8264. size_t logged_content_length = 0;
  8265. std::string logged_content_length_header;
  8266. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8267. logged_content_length = res.content_length_;
  8268. logged_content_length_header = res.get_header_value("Content-Length");
  8269. });
  8270. auto res = cli_.Get("/nocompress");
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::OK_200, res->status);
  8273. EXPECT_EQ(res->body.size(), logged_content_length);
  8274. EXPECT_EQ(std::to_string(logged_content_length),
  8275. logged_content_length_header);
  8276. }
  8277. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8278. const std::string test_content =
  8279. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8280. "3456789012345678901234567890";
  8281. std::string pre_compression_body;
  8282. bool pre_logger_called = false;
  8283. // Set only pre-compression logger
  8284. svr_.set_pre_compression_logger(
  8285. [&](const Request & /*req*/, const Response &res) {
  8286. pre_compression_body = res.body;
  8287. pre_logger_called = true;
  8288. });
  8289. Headers headers;
  8290. headers.emplace("Accept-Encoding", "gzip");
  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("gzip", res->get_header_value("Content-Encoding"));
  8295. // Verify pre-compression logger was called
  8296. EXPECT_TRUE(pre_logger_called);
  8297. EXPECT_EQ(test_content, pre_compression_body);
  8298. }
  8299. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8300. {
  8301. // Test with Expect: 100-continue header - success case
  8302. // Server returns 100 Continue, client sends body, server returns 200 OK
  8303. Request req;
  8304. req.method = "POST";
  8305. req.path = "/post-large";
  8306. req.set_header("Expect", "100-continue");
  8307. req.body = LARGE_DATA;
  8308. Response res;
  8309. auto error = Error::Success;
  8310. cli_.set_keep_alive(true);
  8311. auto ret = cli_.send(req, res, error);
  8312. EXPECT_TRUE(ret);
  8313. EXPECT_EQ(StatusCode::OK_200, res.status);
  8314. EXPECT_EQ(LARGE_DATA, res.body);
  8315. }
  8316. {
  8317. // Test with Expect: 100-continue header - error case
  8318. // Client should not send the body when server returns an error
  8319. Request req;
  8320. req.method = "POST";
  8321. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8322. req.set_header("Expect", "100-continue");
  8323. req.body = LARGE_DATA;
  8324. Response res;
  8325. auto error = Error::Success;
  8326. auto start = std::chrono::high_resolution_clock::now();
  8327. cli_.set_keep_alive(true);
  8328. auto ret = cli_.send(req, res, error);
  8329. auto end = std::chrono::high_resolution_clock::now();
  8330. auto elapsed =
  8331. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8332. .count();
  8333. // With Expect: 100-continue, request completes successfully but with error
  8334. EXPECT_TRUE(ret);
  8335. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8336. EXPECT_EQ("close", res.get_header_value("Connection"));
  8337. EXPECT_FALSE(cli_.is_socket_open());
  8338. EXPECT_LE(elapsed, 2000);
  8339. }
  8340. {
  8341. // Send an extra GET request to ensure error recovery without hanging
  8342. Request req;
  8343. req.method = "GET";
  8344. req.path = "/hi";
  8345. auto start = std::chrono::high_resolution_clock::now();
  8346. auto res = cli_.send(req);
  8347. auto end = std::chrono::high_resolution_clock::now();
  8348. auto elapsed =
  8349. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8350. .count();
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. EXPECT_EQ("Hello World!", res->body);
  8354. EXPECT_LE(elapsed, 500);
  8355. }
  8356. }
  8357. TEST(ZstdDecompressor, ChunkedDecompression) {
  8358. std::string data;
  8359. for (size_t i = 0; i < 32 * 1024; ++i) {
  8360. data.push_back(static_cast<char>('a' + i % 26));
  8361. }
  8362. std::string compressed_data;
  8363. {
  8364. httplib::detail::zstd_compressor compressor;
  8365. bool result = compressor.compress(
  8366. data.data(), data.size(),
  8367. /*last=*/true,
  8368. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8369. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8370. compressed_data_size);
  8371. return true;
  8372. });
  8373. ASSERT_TRUE(result);
  8374. }
  8375. std::string decompressed_data;
  8376. {
  8377. httplib::detail::zstd_decompressor decompressor;
  8378. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8379. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8380. size_t chunk_size = 130;
  8381. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8382. chunk_begin += chunk_size) {
  8383. size_t current_chunk_size =
  8384. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8385. bool result = decompressor.decompress(
  8386. compressed_data.data() + chunk_begin, current_chunk_size,
  8387. [&](const char *decompressed_data_chunk,
  8388. size_t decompressed_data_chunk_size) {
  8389. decompressed_data.insert(decompressed_data.size(),
  8390. decompressed_data_chunk,
  8391. decompressed_data_chunk_size);
  8392. return true;
  8393. });
  8394. ASSERT_TRUE(result);
  8395. }
  8396. }
  8397. ASSERT_EQ(data, decompressed_data);
  8398. }
  8399. TEST(ZstdDecompressor, Decompress) {
  8400. std::string original_text = "Compressed with ZSTD";
  8401. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8402. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8403. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8404. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8405. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8406. std::string decompressed_data;
  8407. {
  8408. httplib::detail::zstd_decompressor decompressor;
  8409. bool result = decompressor.decompress(
  8410. compressed_data.data(), compressed_data.size(),
  8411. [&](const char *decompressed_data_chunk,
  8412. size_t decompressed_data_chunk_size) {
  8413. decompressed_data.insert(decompressed_data.size(),
  8414. decompressed_data_chunk,
  8415. decompressed_data_chunk_size);
  8416. return true;
  8417. });
  8418. ASSERT_TRUE(result);
  8419. }
  8420. ASSERT_EQ(original_text, decompressed_data);
  8421. }
  8422. #endif
  8423. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8424. // separate chunks so that the server sees each part in its own read(). Used to
  8425. // place a read boundary at a specific offset of a request body.
  8426. static bool send_request_in_parts(time_t read_timeout_sec,
  8427. const std::vector<std::string> &parts,
  8428. std::string *resp = nullptr,
  8429. int port = PORT) {
  8430. auto error = Error::Success;
  8431. auto client_sock = detail::create_client_socket(
  8432. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8433. /*connection_timeout_sec=*/5, 0,
  8434. /*read_timeout_sec=*/5, 0,
  8435. /*write_timeout_sec=*/5, 0, std::string(), error);
  8436. if (client_sock == INVALID_SOCKET) { return false; }
  8437. auto ret = detail::process_client_socket(
  8438. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8439. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8440. for (size_t i = 0; i < parts.size(); i++) {
  8441. const auto &part = parts[i];
  8442. if (part.size() !=
  8443. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8444. return false;
  8445. }
  8446. if (i + 1 < parts.size()) {
  8447. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8448. }
  8449. }
  8450. char buf[512];
  8451. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8452. while (line_reader.getline()) {
  8453. if (resp) { *resp += line_reader.ptr(); }
  8454. }
  8455. return true;
  8456. });
  8457. detail::close_socket(client_sock);
  8458. return ret;
  8459. }
  8460. // Sends a raw request to a server listening at HOST:PORT.
  8461. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8462. std::string *resp = nullptr, int port = PORT) {
  8463. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8464. }
  8465. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8466. Server svr;
  8467. std::string header_value;
  8468. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8469. header_value = req.get_header_value("foo");
  8470. res.set_content("ok", "text/plain");
  8471. });
  8472. thread t = thread([&] { svr.listen(HOST, PORT); });
  8473. auto se = detail::scope_exit([&] {
  8474. svr.stop();
  8475. t.join();
  8476. ASSERT_FALSE(svr.is_running());
  8477. });
  8478. svr.wait_until_ready();
  8479. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8480. // like characters are not treated the same - use vertical tab and escape.
  8481. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8482. "foo: \t \v bar \x1B\t \r\n"
  8483. "Connection: close\r\n"
  8484. "\r\n";
  8485. std::string res;
  8486. ASSERT_TRUE(send_request(5, req, &res));
  8487. EXPECT_EQ(header_value, "");
  8488. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8489. }
  8490. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8491. Server svr;
  8492. std::string received;
  8493. svr.Get("/order", [&](const Request &req, Response &res) {
  8494. received = entries_to_string(req.headers);
  8495. res.set_content("ok", "text/plain");
  8496. });
  8497. auto port = svr.bind_to_any_port(HOST);
  8498. thread t = thread([&] { svr.listen_after_bind(); });
  8499. auto se = detail::scope_exit([&] {
  8500. svr.stop();
  8501. t.join();
  8502. ASSERT_FALSE(svr.is_running());
  8503. });
  8504. svr.wait_until_ready();
  8505. const std::string req = "GET /order HTTP/1.1\r\n"
  8506. "X-First: 1\r\n"
  8507. "X-Dup: a\r\n"
  8508. "X-Second: 2\r\n"
  8509. "X-Dup: b\r\n"
  8510. "Connection: close\r\n"
  8511. "\r\n";
  8512. std::string res;
  8513. ASSERT_TRUE(send_request(5, req, &res, port));
  8514. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8515. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8516. }
  8517. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8518. Server svr;
  8519. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8520. res.set_header("Set-Cookie", "first=1");
  8521. res.set_header("X-Between", "y");
  8522. res.set_header("Set-Cookie", "second=2");
  8523. res.set_content("ok", "text/plain");
  8524. });
  8525. auto port = svr.bind_to_any_port(HOST);
  8526. thread t = thread([&] { svr.listen_after_bind(); });
  8527. auto se = detail::scope_exit([&] {
  8528. svr.stop();
  8529. t.join();
  8530. ASSERT_FALSE(svr.is_running());
  8531. });
  8532. svr.wait_until_ready();
  8533. Client cli(HOST, port);
  8534. auto res = cli.Get("/cookies");
  8535. ASSERT_TRUE(res);
  8536. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8537. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8538. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8539. }
  8540. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8541. Server svr;
  8542. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8543. auto i = new int(0);
  8544. res.set_header("Trailer", "X-Safe, X-Reflected");
  8545. res.set_chunked_content_provider(
  8546. "text/plain",
  8547. [i](size_t /*offset*/, DataSink &sink) {
  8548. if (*i == 0) {
  8549. sink.os << "body";
  8550. } else {
  8551. Headers trailer;
  8552. // A valid trailer that must survive.
  8553. trailer.emplace("X-Safe", "safe");
  8554. // Attacker-controlled value carrying CR/LF (response splitting).
  8555. trailer.emplace("X-Reflected",
  8556. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8557. // Attacker-controlled name carrying CR/LF.
  8558. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8559. sink.done_with_trailer(trailer);
  8560. }
  8561. (*i)++;
  8562. return true;
  8563. },
  8564. [i](bool /*success*/) { delete i; });
  8565. });
  8566. thread t = thread([&] { svr.listen(HOST, PORT); });
  8567. auto se = detail::scope_exit([&] {
  8568. svr.stop();
  8569. t.join();
  8570. ASSERT_FALSE(svr.is_running());
  8571. });
  8572. svr.wait_until_ready();
  8573. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8574. "Host: " + HOST +
  8575. "\r\n"
  8576. "Connection: close\r\n"
  8577. "\r\n";
  8578. std::string res;
  8579. ASSERT_TRUE(send_request(5, req, &res));
  8580. // The injected fields must not appear anywhere in the raw response.
  8581. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8582. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8583. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8584. // Invalid trailers are dropped entirely, matching set_header().
  8585. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8586. // The valid trailer still passes through.
  8587. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8588. }
  8589. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8590. Server svr;
  8591. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8592. // res.headers is a public field an application can populate directly,
  8593. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8594. // A valid header that must survive.
  8595. res.headers.emplace("X-Safe", "safe");
  8596. // Attacker-controlled value carrying CR/LF (response splitting).
  8597. res.headers.emplace("X-Reflected",
  8598. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8599. // Attacker-controlled name carrying CR/LF.
  8600. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8601. res.set_content("body", "text/plain");
  8602. });
  8603. thread t = thread([&] { svr.listen(HOST, PORT); });
  8604. auto se = detail::scope_exit([&] {
  8605. svr.stop();
  8606. t.join();
  8607. ASSERT_FALSE(svr.is_running());
  8608. });
  8609. svr.wait_until_ready();
  8610. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8611. "Host: " + HOST +
  8612. "\r\n"
  8613. "Connection: close\r\n"
  8614. "\r\n";
  8615. std::string res;
  8616. ASSERT_TRUE(send_request(5, req, &res));
  8617. // The injected fields must not appear anywhere in the raw response.
  8618. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8619. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8620. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8621. // Invalid headers are dropped entirely, matching set_header().
  8622. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8623. // The valid header still passes through.
  8624. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8625. }
  8626. // Forward declaration: in split builds split.py strips `inline` and moves the
  8627. // definition into httplib.cc, so detail::write_request_line is not visible from
  8628. // the public httplib.h. Re-declaring it here lets the tests link against the
  8629. // symbol in both header-only and split builds.
  8630. namespace httplib {
  8631. namespace detail {
  8632. ssize_t write_request_line(Stream &strm, const std::string &method,
  8633. const std::string &path);
  8634. } // namespace detail
  8635. } // namespace httplib
  8636. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8637. // A well-formed target is written verbatim.
  8638. {
  8639. detail::BufferStream strm;
  8640. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8641. EXPECT_GT(n, 0);
  8642. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8643. }
  8644. // A target carrying CR/LF, SP or other control octets must be rejected
  8645. // before anything reaches the wire, otherwise it splits the request line and
  8646. // injects a header or a whole request.
  8647. const std::string evil_targets[] = {
  8648. "/a\r\nInjected: pwned",
  8649. "/a\rInjected",
  8650. "/a\nInjected",
  8651. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8652. "/a b",
  8653. "/a\tb",
  8654. "/a\x7f",
  8655. };
  8656. for (const auto &evil : evil_targets) {
  8657. detail::BufferStream strm;
  8658. auto n = detail::write_request_line(strm, "GET", evil);
  8659. EXPECT_LT(n, 0);
  8660. EXPECT_TRUE(strm.get_buffer().empty());
  8661. }
  8662. }
  8663. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8664. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8665. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8666. // target reaches write_request. The client must fail cleanly with
  8667. // Error::Write instead of putting a request-line-less, header-injecting
  8668. // request on the wire.
  8669. Server svr;
  8670. svr.Get("/a", [](const Request &, Response &res) {
  8671. res.set_content("ok", "text/plain");
  8672. });
  8673. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8674. auto se = detail::scope_exit([&] {
  8675. svr.stop();
  8676. thread.join();
  8677. ASSERT_FALSE(svr.is_running());
  8678. });
  8679. svr.wait_until_ready();
  8680. {
  8681. Client cli(HOST, PORT);
  8682. cli.set_path_encode(false);
  8683. // The request is rejected before anything is written, so the connection
  8684. // stays silent and the subsequent response read would otherwise block for
  8685. // the full default read timeout. Shorten it -- the assertion is on the
  8686. // error, not the timeout.
  8687. cli.set_read_timeout(1, 0);
  8688. auto res = cli.Get("/a\r\nInjected: pwned");
  8689. EXPECT_FALSE(res);
  8690. EXPECT_EQ(Error::Write, res.error());
  8691. }
  8692. }
  8693. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8694. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8695. // including extension methods.
  8696. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8697. for (const auto &method : good_methods) {
  8698. detail::BufferStream strm;
  8699. auto n = detail::write_request_line(strm, method, "/");
  8700. EXPECT_GT(n, 0);
  8701. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8702. }
  8703. // A method carrying CR/LF would split the request line and smuggle a whole
  8704. // request ahead of the real one. A space or an empty method corrupts the
  8705. // request line. All must be rejected before anything reaches the wire.
  8706. const std::string evil_methods[] = {
  8707. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8708. "GET\r\nInjected: pwned",
  8709. "GET\r",
  8710. "GET\n",
  8711. "GE T",
  8712. "",
  8713. };
  8714. for (const auto &evil : evil_methods) {
  8715. detail::BufferStream strm;
  8716. auto n = detail::write_request_line(strm, evil, "/");
  8717. EXPECT_LT(n, 0);
  8718. EXPECT_TRUE(strm.get_buffer().empty());
  8719. }
  8720. }
  8721. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8722. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8723. // through Client::send must fail with Error::Write and no request, neither
  8724. // the smuggled one nor the real one, may reach the server.
  8725. Server svr;
  8726. std::atomic<int> request_count(0);
  8727. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8728. request_count++;
  8729. res.status = StatusCode::OK_200;
  8730. return Server::HandlerResponse::Handled;
  8731. });
  8732. auto port = svr.bind_to_any_port(HOST);
  8733. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8734. auto se = detail::scope_exit([&] {
  8735. svr.stop();
  8736. thread.join();
  8737. ASSERT_FALSE(svr.is_running());
  8738. });
  8739. svr.wait_until_ready();
  8740. {
  8741. Client cli(HOST, port);
  8742. const std::string evil_methods[] = {
  8743. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8744. "GE T",
  8745. "",
  8746. };
  8747. for (const auto &evil : evil_methods) {
  8748. Request req;
  8749. req.method = evil;
  8750. req.path = "/";
  8751. auto res = cli.send(req);
  8752. EXPECT_FALSE(res);
  8753. EXPECT_EQ(Error::Write, res.error());
  8754. }
  8755. auto handle =
  8756. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8757. EXPECT_FALSE(handle.is_valid());
  8758. EXPECT_EQ(Error::Write, handle.error);
  8759. // A valid request on the same client still goes through.
  8760. auto res = cli.Get("/");
  8761. ASSERT_TRUE(res);
  8762. EXPECT_EQ(StatusCode::OK_200, res->status);
  8763. }
  8764. EXPECT_EQ(1, request_count.load());
  8765. }
  8766. // Sends a raw request and verifies that there isn't a crash or exception.
  8767. static void test_raw_request(const std::string &req,
  8768. std::string *out = nullptr) {
  8769. Server svr;
  8770. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8771. res.set_content("ok", "text/plain");
  8772. });
  8773. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8774. res.set_content("ok", "text/plain");
  8775. });
  8776. svr.Get("/header_field_value_check",
  8777. [&](const Request & /*req*/, Response &res) {
  8778. res.set_content("ok", "text/plain");
  8779. });
  8780. svr.CustomRoute("PROPFIND", "/dav",
  8781. [&](const Request & /*req*/, Response &res) {
  8782. res.status = StatusCode::MultiStatus_207;
  8783. });
  8784. // Server read timeout must be longer than the client read timeout for the
  8785. // bug to reproduce, probably to force the server to process a request
  8786. // without a trailing blank line.
  8787. const time_t client_read_timeout_sec = 1;
  8788. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8789. bool listen_thread_ok = false;
  8790. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8791. auto se = detail::scope_exit([&] {
  8792. svr.stop();
  8793. t.join();
  8794. ASSERT_FALSE(svr.is_running());
  8795. EXPECT_TRUE(listen_thread_ok);
  8796. });
  8797. svr.wait_until_ready();
  8798. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8799. }
  8800. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8801. // A certain header line causes an exception if the header property is parsed
  8802. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8803. test_raw_request(
  8804. "GET /hi HTTP/1.1\r\n"
  8805. " : "
  8806. " "
  8807. " ");
  8808. }
  8809. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8810. // A certain header line causes an exception if the header property *name* is
  8811. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8812. // greedy matcher and requires backtracking when there are a lot of ":"
  8813. // characters.
  8814. // This occurs with libc++ but not libstdc++.
  8815. test_raw_request(
  8816. "GET /hi HTTP/1.1\r\n"
  8817. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8818. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8819. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8820. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8821. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8822. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8823. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8824. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8825. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8826. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8827. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8828. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8829. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8830. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8831. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8832. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8833. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8834. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8835. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8836. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8837. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8838. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8839. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8840. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8841. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8842. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8843. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8844. "&&&%%%");
  8845. }
  8846. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8847. // Make sure this doesn't crash the server.
  8848. // In a previous version of the header line regex, the "\r" rendered the line
  8849. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8850. // a new position where the leading white space ended and the field value
  8851. // began.
  8852. // The crash occurs with libc++ but not libstdc++.
  8853. test_raw_request("GET /hi HTTP/1.1\r\n"
  8854. "a:" +
  8855. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8856. "\r\n"
  8857. "\r\n");
  8858. }
  8859. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8860. std::string out;
  8861. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8862. "Content-Type: text/plain\r\n"
  8863. "Transfer-Encoding: chunked\r\n"
  8864. "\r\n"
  8865. "nothex\r\n",
  8866. &out);
  8867. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8868. }
  8869. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8870. std::string out;
  8871. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8872. "Content-Type: text/plain\r\n"
  8873. "Transfer-Encoding: chunked\r\n"
  8874. "\r\n"
  8875. "3\r\n"
  8876. "xyz\r\n"
  8877. "NaN\r\n",
  8878. &out);
  8879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8880. }
  8881. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8882. std::string out;
  8883. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8884. "Content-Type: text/plain\r\n"
  8885. "Transfer-Encoding: chunked\r\n"
  8886. "\r\n"
  8887. // Length is too large for 64 bits.
  8888. "1ffffffffffffffff\r\n"
  8889. "xyz\r\n",
  8890. &out);
  8891. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8892. }
  8893. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8894. test_raw_request("GET /hi HTTP/1.1\r\n"
  8895. "Content-Type: text/plain\r\n\r");
  8896. }
  8897. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8898. std::string out;
  8899. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8900. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8901. }
  8902. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8903. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8904. std::string out;
  8905. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8906. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8907. }
  8908. }
  8909. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8910. std::string out;
  8911. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8912. "Connection: close\r\n\r\n",
  8913. &out);
  8914. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8915. }
  8916. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8917. Server svr;
  8918. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8919. EXPECT_TRUE(!req.remote_addr.empty());
  8920. });
  8921. thread t = thread([&] { svr.listen(HOST, PORT); });
  8922. auto se = detail::scope_exit([&] {
  8923. svr.stop();
  8924. t.join();
  8925. ASSERT_FALSE(svr.is_running());
  8926. });
  8927. svr.wait_until_ready();
  8928. // Send an invalid request line to trigger Bad Request
  8929. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8930. std::string out;
  8931. ASSERT_TRUE(send_request(5, bad_req, &out));
  8932. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8933. }
  8934. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8935. // answered right away rather than blocking on a read that waits for EOF.
  8936. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8937. std::string out;
  8938. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8939. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8940. }
  8941. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8942. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8943. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8944. for (const auto *method : methods) {
  8945. Server svr;
  8946. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8947. EXPECT_FALSE(svr.is_valid()) << method;
  8948. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8949. }
  8950. }
  8951. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8952. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8953. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8954. for (const auto *method : methods) {
  8955. Server svr;
  8956. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8957. EXPECT_FALSE(svr.is_valid()) << method;
  8958. }
  8959. }
  8960. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8961. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8962. "COPY", "MOVE", "LOCK",
  8963. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8964. Server svr;
  8965. for (const auto *method : methods) {
  8966. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8967. }
  8968. EXPECT_TRUE(svr.is_valid());
  8969. }
  8970. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8971. Server svr;
  8972. svr.CustomRoute("POST", "/x",
  8973. [](const Request &, Response &, const ContentReader &) {});
  8974. EXPECT_FALSE(svr.is_valid());
  8975. }
  8976. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8977. Server svr;
  8978. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8979. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8980. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8981. EXPECT_FALSE(svr.is_valid());
  8982. }
  8983. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8984. Server svr;
  8985. auto captured = Error::Success;
  8986. svr.set_error_logger(
  8987. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8988. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8989. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8990. }
  8991. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8992. std::string out;
  8993. std::string request(
  8994. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8995. test_raw_request(request, &out);
  8996. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8997. }
  8998. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8999. std::string out;
  9000. std::string request(
  9001. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9002. test_raw_request(request, &out);
  9003. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9004. }
  9005. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9006. std::string out;
  9007. std::string request(
  9008. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9009. test_raw_request(request, &out);
  9010. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9011. }
  9012. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9013. std::string out;
  9014. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9015. "Test: \r\n\r\n",
  9016. &out);
  9017. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9018. }
  9019. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9020. Server svr;
  9021. std::string x_custom;
  9022. std::string cookie;
  9023. std::string xff;
  9024. std::string x_unicode;
  9025. std::string x_iis;
  9026. svr.Get("/check", [&](const Request &req, Response &res) {
  9027. x_custom = req.get_header_value("X-Custom");
  9028. cookie = req.get_header_value("Cookie");
  9029. xff = req.get_header_value("X-Forwarded-For");
  9030. x_unicode = req.get_header_value("X-Unicode");
  9031. x_iis = req.get_header_value("X-IIS");
  9032. res.set_content("ok", "text/plain");
  9033. });
  9034. thread t = thread([&] { svr.listen(HOST, PORT); });
  9035. auto se = detail::scope_exit([&] {
  9036. svr.stop();
  9037. t.join();
  9038. ASSERT_FALSE(svr.is_running());
  9039. });
  9040. svr.wait_until_ready();
  9041. const std::string req = "GET /check HTTP/1.1\r\n"
  9042. "Host: localhost\r\n"
  9043. "X-Custom: a%0D%0AInjected: b\r\n"
  9044. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9045. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9046. "X-Unicode: %E3%81%82\r\n"
  9047. "X-IIS: %u00E9\r\n"
  9048. "Connection: close\r\n"
  9049. "\r\n";
  9050. std::string res;
  9051. ASSERT_TRUE(send_request(5, req, &res));
  9052. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9053. // Every value must be returned verbatim (wire form), with no decoding.
  9054. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9055. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9056. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9057. EXPECT_EQ("%E3%81%82", x_unicode);
  9058. EXPECT_EQ("%u00E9", x_iis);
  9059. }
  9060. // Applications that previously relied on automatic percent-decoding can
  9061. // reproduce the old behavior by explicitly calling decode_path_component()
  9062. // or, for RFC 3986 conformance, decode_uri_component().
  9063. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9064. Server svr;
  9065. std::string decoded;
  9066. svr.Get("/check", [&](const Request &req, Response &res) {
  9067. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9068. res.set_content("ok", "text/plain");
  9069. });
  9070. thread t = thread([&] { svr.listen(HOST, PORT); });
  9071. auto se = detail::scope_exit([&] {
  9072. svr.stop();
  9073. t.join();
  9074. ASSERT_FALSE(svr.is_running());
  9075. });
  9076. svr.wait_until_ready();
  9077. const std::string req = "GET /check HTTP/1.1\r\n"
  9078. "Host: localhost\r\n"
  9079. "X-Custom: hello%20world\r\n"
  9080. "Connection: close\r\n"
  9081. "\r\n";
  9082. std::string res;
  9083. ASSERT_TRUE(send_request(5, req, &res));
  9084. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9085. EXPECT_EQ("hello world", decoded);
  9086. }
  9087. // Regression test for #2033. Browsers send Referer values that include
  9088. // percent-encoded characters such as %0A inside the URL. Decoding the
  9089. // header value would either trip the post-decode CR/LF/NUL guard (the
  9090. // original bug, returning 400) or, after that guard was relaxed, silently
  9091. // store a literal LF — both unacceptable. The wire form must round-trip.
  9092. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9093. Server svr;
  9094. std::string referer;
  9095. svr.Get("/check", [&](const Request &req, Response &res) {
  9096. referer = req.get_header_value("Referer");
  9097. res.set_content("ok", "text/plain");
  9098. });
  9099. thread t = thread([&] { svr.listen(HOST, PORT); });
  9100. auto se = detail::scope_exit([&] {
  9101. svr.stop();
  9102. t.join();
  9103. ASSERT_FALSE(svr.is_running());
  9104. });
  9105. svr.wait_until_ready();
  9106. const std::string req = "GET /check HTTP/1.1\r\n"
  9107. "Host: localhost\r\n"
  9108. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9109. "Connection: close\r\n"
  9110. "\r\n";
  9111. std::string res;
  9112. ASSERT_TRUE(send_request(5, req, &res));
  9113. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9114. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9115. }
  9116. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9117. Server svr;
  9118. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9119. res.set_header("Cache-Control", "no-cache");
  9120. res.set_chunked_content_provider(
  9121. "text/event-stream", [](size_t offset, DataSink &sink) {
  9122. std::string s = "data:";
  9123. s += std::to_string(offset);
  9124. s += "\n\n";
  9125. auto ret = sink.write(s.data(), s.size());
  9126. EXPECT_TRUE(ret);
  9127. std::this_thread::sleep_for(std::chrono::seconds(1));
  9128. return true;
  9129. });
  9130. });
  9131. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9132. svr.wait_until_ready();
  9133. Client client(HOST, PORT);
  9134. const Headers headers = {{"Accept", "text/event-stream"}};
  9135. auto get_thread = std::thread([&client, &headers]() {
  9136. auto res = client.Get(
  9137. "/events", headers,
  9138. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9139. });
  9140. auto se = detail::scope_exit([&] {
  9141. svr.stop();
  9142. get_thread.join();
  9143. listen_thread.join();
  9144. ASSERT_FALSE(svr.is_running());
  9145. });
  9146. // Give GET time to get a few messages.
  9147. std::this_thread::sleep_for(std::chrono::seconds(2));
  9148. }
  9149. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9150. httplib::Server svr;
  9151. svr.Post("/hi",
  9152. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9153. res.status = StatusCode::OK_200;
  9154. });
  9155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9156. svr.wait_until_ready();
  9157. Client cli(HOST, PORT);
  9158. auto res = cli.Post("/hi", "data", "text/plain");
  9159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9160. EXPECT_EQ(StatusCode::OK_200, res->status);
  9161. svr.stop();
  9162. thread.join();
  9163. ASSERT_FALSE(svr.is_running());
  9164. res = cli.Post("/hi", "data", "text/plain");
  9165. ASSERT_FALSE(res);
  9166. }
  9167. TEST(ServerStopTest, ListenFailure) {
  9168. Server svr;
  9169. auto t = thread([&]() {
  9170. auto ret = svr.listen("????", PORT);
  9171. EXPECT_FALSE(ret);
  9172. });
  9173. svr.wait_until_ready();
  9174. svr.stop();
  9175. t.join();
  9176. }
  9177. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9178. TEST(ServerStopTest, Decommision) {
  9179. Server svr;
  9180. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9181. for (int i = 0; i < 4; i++) {
  9182. auto is_even = !(i % 2);
  9183. std::thread t{[&] {
  9184. try {
  9185. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9186. if (is_even) {
  9187. throw std::runtime_error("Some thing that happens to go wrong.");
  9188. }
  9189. svr.listen(HOST, PORT);
  9190. } catch (...) { svr.decommission(); }
  9191. }};
  9192. svr.wait_until_ready();
  9193. // Server is up
  9194. {
  9195. Client cli(HOST, PORT);
  9196. auto res = cli.Get("/hi");
  9197. if (is_even) {
  9198. EXPECT_FALSE(res);
  9199. } else {
  9200. EXPECT_TRUE(res);
  9201. EXPECT_EQ("hi...", res->body);
  9202. }
  9203. }
  9204. svr.stop();
  9205. t.join();
  9206. // Server is down...
  9207. {
  9208. Client cli(HOST, PORT);
  9209. auto res = cli.Get("/hi");
  9210. EXPECT_FALSE(res);
  9211. }
  9212. }
  9213. }
  9214. #endif
  9215. // Helper function for string body upload progress tests
  9216. template <typename SetupHandler, typename ClientCall>
  9217. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9218. ClientCall &&client_call,
  9219. const string &body) {
  9220. Server svr;
  9221. setup_handler(svr);
  9222. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9223. auto se = detail::scope_exit([&] {
  9224. svr.stop();
  9225. t.join();
  9226. });
  9227. svr.wait_until_ready();
  9228. Client cli(HOST, PORT);
  9229. vector<uint64_t> progress_values;
  9230. bool progress_called = false;
  9231. auto res =
  9232. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9233. progress_values.push_back(current);
  9234. progress_called = true;
  9235. return true;
  9236. });
  9237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9238. EXPECT_EQ(200, res->status);
  9239. EXPECT_TRUE(progress_called);
  9240. }
  9241. TEST(UploadProgressTest, PostStringBodyBasic) {
  9242. TestStringBodyUploadProgress(
  9243. [](Server &svr) {
  9244. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9245. res.set_content("received", "text/plain");
  9246. });
  9247. },
  9248. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9249. return cli.Post("/test", body, "text/plain", progress_callback);
  9250. },
  9251. "test data for upload progress");
  9252. }
  9253. TEST(UploadProgressTest, PutStringBodyBasic) {
  9254. TestStringBodyUploadProgress(
  9255. [](Server &svr) {
  9256. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9257. res.set_content("put received", "text/plain");
  9258. });
  9259. },
  9260. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9261. return cli.Put("/test", body, "text/plain", progress_callback);
  9262. },
  9263. "put test data for upload progress");
  9264. }
  9265. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9266. TestStringBodyUploadProgress(
  9267. [](Server &svr) {
  9268. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9269. res.set_content("patch received", "text/plain");
  9270. });
  9271. },
  9272. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9273. return cli.Patch("/test", body, "text/plain", progress_callback);
  9274. },
  9275. "patch test data for upload progress");
  9276. }
  9277. // Helper function for content provider upload progress tests
  9278. template <typename SetupHandler, typename ClientCall>
  9279. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9280. ClientCall &&client_call) {
  9281. Server svr;
  9282. setup_handler(svr);
  9283. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9284. auto se = detail::scope_exit([&] {
  9285. svr.stop();
  9286. t.join();
  9287. });
  9288. svr.wait_until_ready();
  9289. Client cli(HOST, PORT);
  9290. vector<uint64_t> progress_values;
  9291. auto res =
  9292. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9293. progress_values.push_back(current);
  9294. return true;
  9295. });
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ(200, res->status);
  9298. EXPECT_FALSE(progress_values.empty());
  9299. }
  9300. TEST(UploadProgressTest, PostContentProviderProgress) {
  9301. TestContentProviderUploadProgress(
  9302. [](Server &svr) {
  9303. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9304. res.set_content("provider received", "text/plain");
  9305. });
  9306. },
  9307. [](Client &cli, UploadProgress progress_callback) {
  9308. return cli.Post(
  9309. "/test", 10,
  9310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9311. sink.os << "test data";
  9312. return true;
  9313. },
  9314. "text/plain", progress_callback);
  9315. });
  9316. }
  9317. // Helper function for multipart upload progress tests
  9318. template <typename SetupHandler, typename ClientCall>
  9319. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9320. ClientCall &&client_call,
  9321. const string &endpoint) {
  9322. Server svr;
  9323. setup_handler(svr);
  9324. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9325. auto se = detail::scope_exit([&] {
  9326. svr.stop();
  9327. t.join();
  9328. });
  9329. svr.wait_until_ready();
  9330. Client cli(HOST, PORT);
  9331. vector<uint64_t> progress_values;
  9332. UploadFormDataItems items = {
  9333. {"field1", "value1", "", ""},
  9334. {"field2", "longer value for progress tracking test", "", ""},
  9335. {"file1", "file content data for upload progress", "test.txt",
  9336. "text/plain"}};
  9337. auto res = client_call(cli, endpoint, items,
  9338. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9339. progress_values.push_back(current);
  9340. return true;
  9341. });
  9342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9343. EXPECT_EQ(200, res->status);
  9344. EXPECT_FALSE(progress_values.empty());
  9345. }
  9346. TEST(UploadProgressTest, PostMultipartProgress) {
  9347. TestMultipartUploadProgress(
  9348. [](Server &svr) {
  9349. svr.Post("/multipart", [](const Request &req, Response &res) {
  9350. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9351. res.set_content("multipart received", "text/plain");
  9352. });
  9353. },
  9354. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9355. UploadProgress progress_callback) {
  9356. return cli.Post(endpoint, items, progress_callback);
  9357. },
  9358. "/multipart");
  9359. }
  9360. // Helper function for basic download progress tests
  9361. template <typename SetupHandler, typename ClientCall>
  9362. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9363. ClientCall &&client_call, const string &endpoint,
  9364. size_t expected_content_size) {
  9365. Server svr;
  9366. setup_handler(svr);
  9367. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9368. auto se = detail::scope_exit([&] {
  9369. svr.stop();
  9370. t.join();
  9371. });
  9372. svr.wait_until_ready();
  9373. Client cli(HOST, PORT);
  9374. vector<uint64_t> progress_values;
  9375. auto res = client_call(cli, endpoint,
  9376. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9377. progress_values.push_back(current);
  9378. return true;
  9379. });
  9380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9381. EXPECT_EQ(200, res->status);
  9382. EXPECT_FALSE(progress_values.empty());
  9383. EXPECT_EQ(expected_content_size, res->body.size());
  9384. }
  9385. TEST(DownloadProgressTest, GetBasic) {
  9386. TestBasicDownloadProgress(
  9387. [](Server &svr) {
  9388. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9389. string content(1000, 'D');
  9390. res.set_content(content, "text/plain");
  9391. });
  9392. },
  9393. [](Client &cli, const string &endpoint,
  9394. DownloadProgress progress_callback) {
  9395. return cli.Get(endpoint, progress_callback);
  9396. },
  9397. "/download", 1000u);
  9398. }
  9399. // Helper function for content receiver download progress tests
  9400. template <typename SetupHandler, typename ClientCall>
  9401. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9402. ClientCall &&client_call,
  9403. const string &endpoint,
  9404. size_t expected_content_size) {
  9405. Server svr;
  9406. setup_handler(svr);
  9407. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9408. auto se = detail::scope_exit([&] {
  9409. svr.stop();
  9410. t.join();
  9411. });
  9412. svr.wait_until_ready();
  9413. Client cli(HOST, PORT);
  9414. vector<uint64_t> progress_values;
  9415. string received_body;
  9416. auto res = client_call(
  9417. cli, endpoint,
  9418. [&](const char *data, size_t data_length) -> bool {
  9419. received_body.append(data, data_length);
  9420. return true;
  9421. },
  9422. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9423. progress_values.push_back(current);
  9424. return true;
  9425. });
  9426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9427. EXPECT_EQ(200, res->status);
  9428. EXPECT_FALSE(progress_values.empty());
  9429. EXPECT_EQ(expected_content_size, received_body.size());
  9430. EXPECT_TRUE(res->body.empty());
  9431. }
  9432. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9433. TestContentReceiverDownloadProgress(
  9434. [](Server &svr) {
  9435. svr.Get("/download-receiver",
  9436. [](const Request & /*req*/, Response &res) {
  9437. string content(2000, 'R');
  9438. res.set_content(content, "text/plain");
  9439. });
  9440. },
  9441. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9442. DownloadProgress progress_callback) {
  9443. return cli.Get(endpoint, content_receiver, progress_callback);
  9444. },
  9445. "/download-receiver", 2000u);
  9446. }
  9447. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9448. // A provider reaching a pass with nothing to hand over - an empty buffer
  9449. // popped off a queue, say - must not be taken to mean the body is finished.
  9450. // It used to end the loop with the terminating chunk unwritten while the
  9451. // server still considered the response complete, so the peer waited for an
  9452. // end that never arrived.
  9453. Server svr;
  9454. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9455. auto step = std::make_shared<int>(0);
  9456. res.set_chunked_content_provider("text/plain",
  9457. [step](size_t /*offset*/, DataSink &sink) {
  9458. switch ((*step)++) {
  9459. case 0: sink.write("", 0); break;
  9460. case 1: sink.write("hello", 5); break;
  9461. default: sink.done(); break;
  9462. }
  9463. return true;
  9464. });
  9465. });
  9466. auto port = svr.bind_to_any_port(HOST);
  9467. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9468. auto listen_se = detail::scope_exit([&] {
  9469. svr.stop();
  9470. listen_thread.join();
  9471. ASSERT_FALSE(svr.is_running());
  9472. });
  9473. svr.wait_until_ready();
  9474. Client cli(HOST, port);
  9475. // Without the fix the body is never terminated, so bound the wait rather
  9476. // than letting the test hang on the default read timeout.
  9477. cli.set_read_timeout(5, 0);
  9478. auto res = cli.Get("/stream");
  9479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9480. EXPECT_EQ(StatusCode::OK_200, res->status);
  9481. EXPECT_EQ("hello", res->body);
  9482. }
  9483. TEST(StreamingTest, NoContentLengthStreaming) {
  9484. Server svr;
  9485. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9486. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9487. if (offset < 6) {
  9488. sink.os << (offset < 3 ? "a" : "b");
  9489. } else {
  9490. sink.done();
  9491. }
  9492. return true;
  9493. });
  9494. });
  9495. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9496. auto listen_se = detail::scope_exit([&] {
  9497. svr.stop();
  9498. listen_thread.join();
  9499. ASSERT_FALSE(svr.is_running());
  9500. });
  9501. svr.wait_until_ready();
  9502. Client client(HOST, PORT);
  9503. auto get_thread = std::thread([&client]() {
  9504. std::string s;
  9505. auto res =
  9506. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9507. s += std::string(data, len);
  9508. return true;
  9509. });
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ(StatusCode::OK_200, res->status);
  9512. EXPECT_EQ("aaabbb", s);
  9513. });
  9514. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9515. // Give GET time to get a few messages.
  9516. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9517. }
  9518. TEST(MountTest, Unmount) {
  9519. Server svr;
  9520. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9521. auto se = detail::scope_exit([&] {
  9522. svr.stop();
  9523. listen_thread.join();
  9524. ASSERT_FALSE(svr.is_running());
  9525. });
  9526. svr.wait_until_ready();
  9527. Client cli("localhost", PORT);
  9528. svr.set_mount_point("/mount2", "./www2");
  9529. auto res = cli.Get("/");
  9530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9532. res = cli.Get("/mount2/dir/test.html");
  9533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9534. EXPECT_EQ(StatusCode::OK_200, res->status);
  9535. svr.set_mount_point("/", "./www");
  9536. res = cli.Get("/dir/");
  9537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9538. EXPECT_EQ(StatusCode::OK_200, res->status);
  9539. svr.remove_mount_point("/");
  9540. res = cli.Get("/dir/");
  9541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9542. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9543. svr.remove_mount_point("/mount2");
  9544. res = cli.Get("/mount2/dir/test.html");
  9545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9547. }
  9548. TEST(MountTest, PathSegmentBoundary) {
  9549. Server svr;
  9550. svr.set_mount_point("/mount2", "./www2");
  9551. svr.set_mount_point("/", "./www");
  9552. auto port = svr.bind_to_any_port(HOST);
  9553. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9554. auto se = detail::scope_exit([&] {
  9555. svr.stop();
  9556. listen_thread.join();
  9557. ASSERT_FALSE(svr.is_running());
  9558. });
  9559. svr.wait_until_ready();
  9560. Client cli(HOST, port);
  9561. auto res = cli.Get("/mount2/dir/test.html");
  9562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9563. EXPECT_EQ(StatusCode::OK_200, res->status);
  9564. // "/mount2" must not match part-way through a path segment.
  9565. res = cli.Get("/mount2dir/test.html");
  9566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9568. // A mount point ending in '/' keeps matching every path below it.
  9569. res = cli.Get("/dir/test.html");
  9570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9571. EXPECT_EQ(StatusCode::OK_200, res->status);
  9572. }
  9573. TEST(MountTest, Redicect) {
  9574. Server svr;
  9575. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9576. auto se = detail::scope_exit([&] {
  9577. svr.stop();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. svr.set_mount_point("/", "./www");
  9582. svr.wait_until_ready();
  9583. Client cli("localhost", PORT);
  9584. auto res = cli.Get("/dir/");
  9585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9586. EXPECT_EQ(StatusCode::OK_200, res->status);
  9587. res = cli.Get("/dir");
  9588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9589. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9590. res = cli.Get("/file");
  9591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9592. EXPECT_EQ(StatusCode::OK_200, res->status);
  9593. res = cli.Get("/file/");
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9596. cli.set_follow_location(true);
  9597. res = cli.Get("/dir");
  9598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9599. EXPECT_EQ(StatusCode::OK_200, res->status);
  9600. }
  9601. TEST(MountTest, MultibytesPathName) {
  9602. Server svr;
  9603. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9604. auto se = detail::scope_exit([&] {
  9605. svr.stop();
  9606. listen_thread.join();
  9607. ASSERT_FALSE(svr.is_running());
  9608. });
  9609. svr.set_mount_point("/", "./www");
  9610. svr.wait_until_ready();
  9611. Client cli("localhost", PORT);
  9612. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9614. EXPECT_EQ(StatusCode::OK_200, res->status);
  9615. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9616. }
  9617. #ifdef _WIN32
  9618. // Issue #2435: mmap::open() must succeed even when another handle holds
  9619. // the file open for writing (e.g. an active log file).
  9620. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9621. const char *path = "mmap_concurrent_writer_test.txt";
  9622. const char *content = "hello";
  9623. {
  9624. std::ofstream f(path, std::ios::binary);
  9625. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9626. }
  9627. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9628. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9629. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9630. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9631. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9632. detail::mmap m(path);
  9633. ASSERT_TRUE(m.is_open());
  9634. EXPECT_EQ(strlen(content), m.size());
  9635. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9636. }
  9637. #endif
  9638. #ifndef _WIN32
  9639. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9640. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9641. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9642. TEST(MmapTest, FailedMappingIsNotOpen) {
  9643. const char *path = "./mmap_failed_mapping_test_dir";
  9644. ASSERT_EQ(0, ::mkdir(path, 0755));
  9645. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9646. detail::mmap m(path);
  9647. EXPECT_FALSE(m.is_open());
  9648. EXPECT_EQ(0U, m.size());
  9649. EXPECT_NE(static_cast<const void *>(m.data()),
  9650. static_cast<const void *>(MAP_FAILED));
  9651. }
  9652. #endif
  9653. TEST(KeepAliveTest, ReadTimeout) {
  9654. Server svr;
  9655. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9656. std::this_thread::sleep_for(std::chrono::seconds(2));
  9657. res.set_content("a", "text/plain");
  9658. });
  9659. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9660. res.set_content("b", "text/plain");
  9661. });
  9662. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9663. auto se = detail::scope_exit([&] {
  9664. svr.stop();
  9665. listen_thread.join();
  9666. ASSERT_FALSE(svr.is_running());
  9667. });
  9668. svr.wait_until_ready();
  9669. Client cli("localhost", PORT);
  9670. cli.set_keep_alive(true);
  9671. cli.set_read_timeout(std::chrono::seconds(1));
  9672. auto resa = cli.Get("/a");
  9673. ASSERT_FALSE(resa);
  9674. EXPECT_EQ(Error::Read, resa.error());
  9675. auto resb = cli.Get("/b");
  9676. ASSERT_TRUE(resb);
  9677. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9678. EXPECT_EQ("b", resb->body);
  9679. }
  9680. TEST(KeepAliveTest, MaxCount) {
  9681. size_t keep_alive_max_count = 3;
  9682. Server svr;
  9683. svr.set_keep_alive_max_count(keep_alive_max_count);
  9684. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9685. res.set_content("Hello World!", "text/plain");
  9686. });
  9687. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9688. auto se = detail::scope_exit([&] {
  9689. svr.stop();
  9690. listen_thread.join();
  9691. ASSERT_FALSE(svr.is_running());
  9692. });
  9693. svr.wait_until_ready();
  9694. Client cli(HOST, PORT);
  9695. cli.set_keep_alive(true);
  9696. for (size_t i = 0; i < 5; i++) {
  9697. auto result = cli.Get("/hi");
  9698. ASSERT_TRUE(result);
  9699. EXPECT_EQ(StatusCode::OK_200, result->status);
  9700. if (i == keep_alive_max_count - 1) {
  9701. EXPECT_EQ("close", result->get_header_value("Connection"));
  9702. } else {
  9703. EXPECT_FALSE(result->has_header("Connection"));
  9704. }
  9705. }
  9706. }
  9707. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  9708. // can pull the next one into the server's buffer. The server must serve it
  9709. // without waiting for the socket to become readable again. The keep-alive
  9710. // timeout outlasts the client's read timeout, so a request left waiting for it
  9711. // shows up as a missing response.
  9712. static void serve_pipelining_routes(Server &svr,
  9713. const std::function<void(int)> &client) {
  9714. svr.set_keep_alive_timeout(5);
  9715. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  9716. res.set_content("hi " + req.matches[1].str(), "text/plain");
  9717. });
  9718. svr.Post("/echo", [](const Request &req, Response &res) {
  9719. res.set_content("echo " + req.body, "text/plain");
  9720. });
  9721. auto port = svr.bind_to_any_port(HOST);
  9722. thread t = thread([&] { svr.listen_after_bind(); });
  9723. auto se = detail::scope_exit([&] {
  9724. svr.stop();
  9725. t.join();
  9726. });
  9727. svr.wait_until_ready();
  9728. client(port);
  9729. }
  9730. static std::string
  9731. send_pipelined_requests(const std::vector<std::string> &parts) {
  9732. Server svr;
  9733. std::string res;
  9734. serve_pipelining_routes(svr, [&](int port) {
  9735. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  9736. });
  9737. return res;
  9738. }
  9739. static void expect_in_order(const std::string &res,
  9740. const std::vector<std::string> &bodies) {
  9741. size_t pos = 0;
  9742. for (const auto &body : bodies) {
  9743. pos = res.find(body, pos);
  9744. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  9745. pos += body.size();
  9746. }
  9747. }
  9748. TEST(KeepAliveTest, PipelinedRequests) {
  9749. auto res = send_pipelined_requests(
  9750. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9751. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9752. "Content-Length: 4\r\n\r\nbody"
  9753. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9754. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  9755. }
  9756. // The second request starts in the server's buffer and ends on the socket.
  9757. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  9758. auto res =
  9759. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9760. "GET /hi/2 HTTP/1.1\r\nHo",
  9761. "st: localhost\r\nConnection: close\r\n\r\n"});
  9762. expect_in_order(res, {"hi 1", "hi 2"});
  9763. }
  9764. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  9765. // CRLF after a body does not turn into a 400 for the next request.
  9766. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  9767. auto res = send_pipelined_requests(
  9768. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  9769. "Content-Length: 4\r\n\r\nbody\r\n"
  9770. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  9771. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  9772. expect_in_order(res, {"echo body", "hi 2"});
  9773. }
  9774. // Where an unparsable request ends is unknown, so what follows it in the buffer
  9775. // must not be served as the next request.
  9776. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  9777. auto res = send_pipelined_requests(
  9778. {"INVALID REQUEST LINE\r\n\r\n"
  9779. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  9780. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9781. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  9782. }
  9783. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9784. // Over TLS, the next request is held by the TLS library as already decrypted
  9785. // data rather than on the socket.
  9786. TEST(KeepAliveTest, SSLPipelinedRequests) {
  9787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9788. std::string res;
  9789. serve_pipelining_routes(svr, [&](int port) {
  9790. auto error = Error::Success;
  9791. auto sock = detail::create_client_socket(
  9792. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9793. /*connection_timeout_sec=*/5, 0,
  9794. /*read_timeout_sec=*/2, 0,
  9795. /*write_timeout_sec=*/5, 0, std::string(), error);
  9796. ASSERT_NE(INVALID_SOCKET, sock);
  9797. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9798. auto ctx = SSL_CTX_new(TLS_client_method());
  9799. auto ssl = SSL_new(ctx);
  9800. auto ssl_se = detail::scope_exit([&] {
  9801. SSL_free(ssl);
  9802. SSL_CTX_free(ctx);
  9803. });
  9804. SSL_set_fd(ssl, static_cast<int>(sock));
  9805. ASSERT_EQ(1, SSL_connect(ssl));
  9806. // One write, so all three requests arrive in one TLS record
  9807. const std::string req =
  9808. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9809. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  9810. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  9811. ASSERT_EQ(static_cast<int>(req.size()),
  9812. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  9813. char buf[512];
  9814. int n;
  9815. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9816. res.append(buf, static_cast<size_t>(n));
  9817. }
  9818. });
  9819. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  9820. }
  9821. #endif
  9822. TEST(KeepAliveTest, Issue1041) {
  9823. Server svr;
  9824. svr.set_keep_alive_timeout(3);
  9825. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9826. res.set_content("Hello World!", "text/plain");
  9827. });
  9828. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9829. auto se = detail::scope_exit([&] {
  9830. svr.stop();
  9831. listen_thread.join();
  9832. ASSERT_FALSE(svr.is_running());
  9833. });
  9834. svr.wait_until_ready();
  9835. Client cli(HOST, PORT);
  9836. cli.set_keep_alive(true);
  9837. auto result = cli.Get("/hi");
  9838. ASSERT_TRUE(result);
  9839. EXPECT_EQ(StatusCode::OK_200, result->status);
  9840. std::this_thread::sleep_for(std::chrono::seconds(5));
  9841. result = cli.Get("/hi");
  9842. ASSERT_TRUE(result);
  9843. EXPECT_EQ(StatusCode::OK_200, result->status);
  9844. }
  9845. TEST(KeepAliveTest, Issue1959) {
  9846. Server svr;
  9847. svr.set_keep_alive_timeout(5);
  9848. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9849. res.set_content("a", "text/plain");
  9850. });
  9851. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9852. auto se = detail::scope_exit([&] {
  9853. if (!svr.is_running()) return;
  9854. svr.stop();
  9855. listen_thread.join();
  9856. ASSERT_FALSE(svr.is_running());
  9857. });
  9858. svr.wait_until_ready();
  9859. Client cli("localhost", PORT);
  9860. cli.set_keep_alive(true);
  9861. using namespace std::chrono;
  9862. auto start = steady_clock::now();
  9863. cli.Get("/a");
  9864. svr.stop();
  9865. listen_thread.join();
  9866. auto end = steady_clock::now();
  9867. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9868. EXPECT_LT(elapsed, 5000);
  9869. }
  9870. #ifdef CPPHTTPLIB_SSL_ENABLED
  9871. TEST(KeepAliveTest, SSLClientReconnection) {
  9872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9873. ASSERT_TRUE(svr.is_valid());
  9874. svr.set_keep_alive_timeout(1);
  9875. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9876. res.set_content("Hello World!", "text/plain");
  9877. });
  9878. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. listen_thread.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. SSLClient cli(HOST, PORT);
  9886. cli.enable_server_certificate_verification(false);
  9887. cli.set_keep_alive(true);
  9888. auto result = cli.Get("/hi");
  9889. ASSERT_TRUE(result);
  9890. EXPECT_EQ(StatusCode::OK_200, result->status);
  9891. result = cli.Get("/hi");
  9892. ASSERT_TRUE(result);
  9893. EXPECT_EQ(StatusCode::OK_200, result->status);
  9894. std::this_thread::sleep_for(std::chrono::seconds(2));
  9895. // Recoonect
  9896. result = cli.Get("/hi");
  9897. ASSERT_TRUE(result);
  9898. EXPECT_EQ(StatusCode::OK_200, result->status);
  9899. result = cli.Get("/hi");
  9900. ASSERT_TRUE(result);
  9901. EXPECT_EQ(StatusCode::OK_200, result->status);
  9902. }
  9903. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9905. ASSERT_TRUE(svr.is_valid());
  9906. svr.set_keep_alive_timeout(1);
  9907. std::string content = "reconnect";
  9908. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9909. res.set_content("Hello World!", "text/plain");
  9910. });
  9911. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9912. auto se = detail::scope_exit([&] {
  9913. svr.stop();
  9914. listen_thread.join();
  9915. ASSERT_FALSE(svr.is_running());
  9916. });
  9917. svr.wait_until_ready();
  9918. SSLClient cli(HOST, PORT);
  9919. cli.enable_server_certificate_verification(false);
  9920. cli.set_keep_alive(true);
  9921. auto result = cli.Post(
  9922. "/hi", content.size(),
  9923. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9924. sink.write(content.c_str(), content.size());
  9925. return true;
  9926. },
  9927. "text/plain");
  9928. ASSERT_TRUE(result);
  9929. EXPECT_EQ(200, result->status);
  9930. std::this_thread::sleep_for(std::chrono::seconds(2));
  9931. // Recoonect
  9932. result = cli.Post(
  9933. "/hi", content.size(),
  9934. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9935. sink.write(content.c_str(), content.size());
  9936. return true;
  9937. },
  9938. "text/plain");
  9939. ASSERT_TRUE(result);
  9940. EXPECT_EQ(200, result->status);
  9941. result = cli.Post(
  9942. "/hi", content.size(),
  9943. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9944. sink.write(content.c_str(), content.size());
  9945. return true;
  9946. },
  9947. "text/plain");
  9948. ASSERT_TRUE(result);
  9949. EXPECT_EQ(200, result->status);
  9950. }
  9951. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9952. using namespace httplib::tls;
  9953. {
  9954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9955. ASSERT_TRUE(svr.is_valid());
  9956. svr.Get("/sni", [&](const Request &req, Response &res) {
  9957. std::string expected = req.sni();
  9958. EXPECT_EQ(expected, req.get_param_value("expected"));
  9959. res.set_content("ok", "text/plain");
  9960. });
  9961. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9962. auto se = detail::scope_exit([&] {
  9963. svr.stop();
  9964. listen_thread.join();
  9965. ASSERT_FALSE(svr.is_running());
  9966. });
  9967. svr.wait_until_ready();
  9968. {
  9969. SSLClient cli("localhost", PORT);
  9970. cli.enable_server_certificate_verification(false);
  9971. auto res = cli.Get("/sni?expected=localhost");
  9972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9973. }
  9974. {
  9975. SSLClient cli("::1", PORT);
  9976. cli.enable_server_certificate_verification(false);
  9977. auto res = cli.Get("/sni?expected=");
  9978. // NOTE: This may fail if the server is listening on IPv4 only
  9979. // (e.g., when localhost resolves to 127.0.0.1 only)
  9980. if (res) {
  9981. EXPECT_EQ(StatusCode::OK_200, res->status);
  9982. } else {
  9983. EXPECT_EQ(Error::Connection, res.error());
  9984. }
  9985. }
  9986. }
  9987. }
  9988. #endif
  9989. TEST(ClientProblemDetectionTest, ContentProvider) {
  9990. Server svr;
  9991. size_t content_length = 1024 * 1024;
  9992. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9993. res.set_content_provider(
  9994. content_length, "text/plain",
  9995. [&](size_t offset, size_t length, DataSink &sink) {
  9996. auto out_len = std::min(length, static_cast<size_t>(1024));
  9997. std::string out(out_len, '@');
  9998. sink.write(out.data(), out_len);
  9999. return offset < 4096;
  10000. },
  10001. [](bool success) { ASSERT_FALSE(success); });
  10002. });
  10003. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10004. res.set_content_provider(
  10005. 0, "text/plain",
  10006. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10007. EXPECT_TRUE(false);
  10008. return true;
  10009. },
  10010. [](bool success) { ASSERT_FALSE(success); });
  10011. });
  10012. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10013. auto se = detail::scope_exit([&] {
  10014. svr.stop();
  10015. listen_thread.join();
  10016. ASSERT_FALSE(svr.is_running());
  10017. });
  10018. svr.wait_until_ready();
  10019. Client cli("localhost", PORT);
  10020. {
  10021. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10022. size_t /*data_length*/) { return false; });
  10023. ASSERT_FALSE(res);
  10024. }
  10025. {
  10026. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10027. size_t /*data_length*/) { return false; });
  10028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10029. }
  10030. }
  10031. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10032. // A provider that reports success without writing anything and without
  10033. // calling done() used to be handed the same offset and length again on every
  10034. // pass, so it spun for as long as the peer stayed connected.
  10035. Server svr;
  10036. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10037. res.set_content("ok", "text/plain");
  10038. });
  10039. auto port = svr.bind_to_any_port(HOST);
  10040. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. listen_thread.join();
  10044. ASSERT_FALSE(svr.is_running());
  10045. });
  10046. svr.wait_until_ready();
  10047. std::atomic<int> call_count{0};
  10048. Client cli(HOST, port);
  10049. auto res = cli.Post(
  10050. "/", 1024,
  10051. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10052. // Give up after enough passes to show the spin, so that losing the
  10053. // check below fails this test instead of hanging it.
  10054. return ++call_count < 100;
  10055. },
  10056. "text/plain");
  10057. ASSERT_FALSE(res);
  10058. EXPECT_EQ(Error::Write, res.error());
  10059. EXPECT_EQ(1, call_count.load());
  10060. }
  10061. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10062. // A writer only has to assign `write`. The other three used to be left as
  10063. // empty std::functions, so a provider calling one threw
  10064. // std::bad_function_call out of the thread running it and took the whole
  10065. // process down.
  10066. DataSink sink;
  10067. std::string written;
  10068. sink.write = [&](const char *data, size_t data_len) {
  10069. written.append(data, data_len);
  10070. return true;
  10071. };
  10072. EXPECT_TRUE(sink.is_writable());
  10073. sink.done();
  10074. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10075. EXPECT_TRUE(written.empty());
  10076. }
  10077. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10078. // A sink that cannot carry trailers still has to finish.
  10079. DataSink sink;
  10080. auto done_count = 0;
  10081. sink.done = [&]() { done_count++; };
  10082. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10083. EXPECT_EQ(1, done_count);
  10084. }
  10085. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10086. Server svr;
  10087. const std::string body(4096, 'x');
  10088. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10089. res.set_content_provider(body.size(), "text/plain",
  10090. [&](size_t offset, size_t length, DataSink &sink) {
  10091. sink.write(body.data() + offset, length);
  10092. sink.done();
  10093. return true;
  10094. });
  10095. });
  10096. auto port = svr.bind_to_any_port(HOST);
  10097. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10098. auto se = detail::scope_exit([&] {
  10099. svr.stop();
  10100. listen_thread.join();
  10101. ASSERT_FALSE(svr.is_running());
  10102. });
  10103. svr.wait_until_ready();
  10104. Client cli(HOST, port);
  10105. auto res = cli.Get("/");
  10106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10107. EXPECT_EQ(StatusCode::OK_200, res->status);
  10108. EXPECT_EQ(body, res->body);
  10109. }
  10110. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10111. Server svr;
  10112. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10113. res.set_content_provider(
  10114. 1024, "text/plain",
  10115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10116. sink.write("hello", 5);
  10117. sink.done(); // short of the 1024 bytes the response promised
  10118. return true;
  10119. });
  10120. });
  10121. auto port = svr.bind_to_any_port(HOST);
  10122. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. listen_thread.join();
  10126. ASSERT_FALSE(svr.is_running());
  10127. });
  10128. svr.wait_until_ready();
  10129. Client cli(HOST, port);
  10130. cli.set_read_timeout(5, 0);
  10131. // The response is short of its Content-Length, so the client cannot read a
  10132. // complete body. What matters is that this returns at all: a no-op done()
  10133. // would leave the writer looping over a provider that never makes progress.
  10134. auto res = cli.Get("/");
  10135. EXPECT_FALSE(res);
  10136. }
  10137. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10138. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10139. // The compressed path builds the whole body before connecting, so this
  10140. // fails client-side and never reaches a server.
  10141. Client cli(HOST, PORT);
  10142. cli.set_compress(true);
  10143. auto res = cli.Post(
  10144. "/", 1024,
  10145. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10146. sink.write("hello", 5);
  10147. sink.done(); // short of the 1024 bytes the request announced
  10148. return true;
  10149. },
  10150. "text/plain");
  10151. ASSERT_FALSE(res);
  10152. EXPECT_EQ(Error::Write, res.error());
  10153. }
  10154. #endif
  10155. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10156. Server svr;
  10157. svr.set_error_handler([](Request const &, Response &res) -> void {
  10158. res.set_chunked_content_provider(
  10159. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10160. sink.os << "hello";
  10161. sink.os << "world";
  10162. sink.done();
  10163. return true;
  10164. });
  10165. });
  10166. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10167. auto se = detail::scope_exit([&] {
  10168. svr.stop();
  10169. listen_thread.join();
  10170. ASSERT_FALSE(svr.is_running());
  10171. });
  10172. svr.wait_until_ready();
  10173. Client cli("localhost", PORT);
  10174. auto res = cli.Get("/");
  10175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10176. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10177. EXPECT_EQ("helloworld", res->body);
  10178. }
  10179. TEST(LongPollingTest, ClientCloseDetection) {
  10180. Server svr;
  10181. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10182. res.set_chunked_content_provider(
  10183. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10184. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10185. sink.os << "hello";
  10186. auto count = 10;
  10187. while (count > 0 && sink.is_writable()) {
  10188. this_thread::sleep_for(chrono::milliseconds(10));
  10189. count--;
  10190. }
  10191. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10192. return true;
  10193. });
  10194. });
  10195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. listen_thread.join();
  10199. ASSERT_FALSE(svr.is_running());
  10200. });
  10201. svr.wait_until_ready();
  10202. Client cli("localhost", PORT);
  10203. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10204. EXPECT_EQ("hello", string(data, data_length));
  10205. return false; // close the socket immediately.
  10206. });
  10207. ASSERT_FALSE(res);
  10208. }
  10209. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10210. Server svr;
  10211. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10212. res.set_chunked_content_provider(
  10213. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10214. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10215. sink.os << "hello";
  10216. EXPECT_TRUE(sink.os.good());
  10217. // Wait for the client to close the connection
  10218. auto count = 10;
  10219. while (count > 0 && sink.is_writable()) {
  10220. this_thread::sleep_for(chrono::milliseconds(10));
  10221. count--;
  10222. }
  10223. // After client disconnect, write repeatedly until the socket
  10224. // write actually fails (small writes may be absorbed by the
  10225. // kernel buffer)
  10226. std::string chunk(1024, 'x');
  10227. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10228. sink.os << chunk;
  10229. }
  10230. EXPECT_TRUE(sink.os.fail());
  10231. return true;
  10232. });
  10233. });
  10234. auto port = svr.bind_to_any_port("localhost");
  10235. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10236. auto se = detail::scope_exit([&] {
  10237. svr.stop();
  10238. listen_thread.join();
  10239. ASSERT_FALSE(svr.is_running());
  10240. });
  10241. svr.wait_until_ready();
  10242. Client cli("localhost", port);
  10243. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10244. EXPECT_EQ("hello", string(data, data_length));
  10245. return false; // close the socket immediately.
  10246. });
  10247. ASSERT_FALSE(res);
  10248. }
  10249. TEST(GetWithParametersTest, GetWithParameters) {
  10250. Server svr;
  10251. svr.Get("/", [&](const Request &req, Response &) {
  10252. EXPECT_EQ("world", req.get_param_value("hello"));
  10253. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10254. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10255. });
  10256. svr.Get("/params", [&](const Request &req, Response &) {
  10257. EXPECT_EQ("world", req.get_param_value("hello"));
  10258. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10259. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10260. });
  10261. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10262. EXPECT_EQ("resource-id", req.matches[1]);
  10263. EXPECT_EQ("foo", req.get_param_value("param1"));
  10264. EXPECT_EQ("bar", req.get_param_value("param2"));
  10265. });
  10266. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10267. EXPECT_EQ("user-id", req.path_params.at("id"));
  10268. EXPECT_EQ("foo", req.get_param_value("param1"));
  10269. EXPECT_EQ("bar", req.get_param_value("param2"));
  10270. });
  10271. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10272. auto se = detail::scope_exit([&] {
  10273. svr.stop();
  10274. listen_thread.join();
  10275. ASSERT_FALSE(svr.is_running());
  10276. });
  10277. svr.wait_until_ready();
  10278. {
  10279. Client cli(HOST, PORT);
  10280. Params params;
  10281. params.emplace("hello", "world");
  10282. params.emplace("hello2", "world2");
  10283. params.emplace("hello3", "world3");
  10284. auto res = cli.Get("/", params, Headers{});
  10285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10286. EXPECT_EQ(StatusCode::OK_200, res->status);
  10287. }
  10288. {
  10289. Client cli(HOST, PORT);
  10290. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10292. EXPECT_EQ(StatusCode::OK_200, res->status);
  10293. }
  10294. {
  10295. Client cli(HOST, PORT);
  10296. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10298. EXPECT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. {
  10301. Client cli(HOST, PORT);
  10302. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10304. EXPECT_EQ(StatusCode::OK_200, res->status);
  10305. }
  10306. }
  10307. TEST(GetWithParametersTest, GetWithParameters2) {
  10308. Server svr;
  10309. svr.Get("/", [&](const Request &req, Response &res) {
  10310. auto text = req.get_param_value("hello");
  10311. res.set_content(text, "text/plain");
  10312. });
  10313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10314. auto se = detail::scope_exit([&] {
  10315. svr.stop();
  10316. listen_thread.join();
  10317. ASSERT_FALSE(svr.is_running());
  10318. });
  10319. svr.wait_until_ready();
  10320. Client cli("localhost", PORT);
  10321. Params params;
  10322. params.emplace("hello", "world");
  10323. std::string body;
  10324. auto res = cli.Get("/", params, Headers{},
  10325. [&](const char *data, size_t data_length) {
  10326. body.append(data, data_length);
  10327. return true;
  10328. });
  10329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10330. EXPECT_EQ(StatusCode::OK_200, res->status);
  10331. EXPECT_EQ("world", body);
  10332. }
  10333. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10334. Server svr;
  10335. svr.Get("/search", [&](const Request &req, Response &res) {
  10336. auto q = req.get_param_value("q");
  10337. res.set_content(q, "text/plain");
  10338. });
  10339. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10340. auto se = detail::scope_exit([&] {
  10341. svr.stop();
  10342. listen_thread.join();
  10343. ASSERT_FALSE(svr.is_running());
  10344. });
  10345. svr.wait_until_ready();
  10346. Client cli("localhost", PORT);
  10347. // Verify that Get(path, params) works without requiring Headers argument
  10348. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(StatusCode::OK_200, res->status);
  10351. EXPECT_EQ("cpp-httplib", res->body);
  10352. }
  10353. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10354. auto host = "httpbingo.org";
  10355. auto path = std::string{"/range/32"};
  10356. #ifdef CPPHTTPLIB_SSL_ENABLED
  10357. SSLClient cli(host);
  10358. #else
  10359. Client cli(host);
  10360. #endif
  10361. cli.set_default_headers({make_range_header({{1, 10}})});
  10362. cli.set_connection_timeout(5);
  10363. {
  10364. auto res = cli.Get(path);
  10365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10366. EXPECT_EQ("bcdefghijk", res->body);
  10367. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10368. }
  10369. {
  10370. auto res = cli.Get(path);
  10371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10372. EXPECT_EQ("bcdefghijk", res->body);
  10373. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10374. }
  10375. }
  10376. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10377. Server svr;
  10378. svr.set_default_headers({{"Hello", "World"}});
  10379. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10380. res.set_content("ok", "text/plain");
  10381. });
  10382. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10383. auto se = detail::scope_exit([&] {
  10384. svr.stop();
  10385. listen_thread.join();
  10386. ASSERT_FALSE(svr.is_running());
  10387. });
  10388. svr.wait_until_ready();
  10389. Client cli("localhost", PORT);
  10390. auto res = cli.Get("/");
  10391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10392. EXPECT_EQ(StatusCode::OK_200, res->status);
  10393. EXPECT_EQ("ok", res->body);
  10394. EXPECT_EQ("World", res->get_header_value("Hello"));
  10395. }
  10396. #ifdef CPPHTTPLIB_SSL_ENABLED
  10397. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10399. ASSERT_TRUE(svr.is_valid());
  10400. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10401. std::this_thread::sleep_for(std::chrono::seconds(2));
  10402. res.set_content("a", "text/plain");
  10403. });
  10404. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10405. res.set_content("b", "text/plain");
  10406. });
  10407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10408. auto se = detail::scope_exit([&] {
  10409. svr.stop();
  10410. listen_thread.join();
  10411. ASSERT_FALSE(svr.is_running());
  10412. });
  10413. svr.wait_until_ready();
  10414. SSLClient cli("localhost", PORT);
  10415. cli.enable_server_certificate_verification(false);
  10416. cli.set_keep_alive(true);
  10417. cli.set_read_timeout(std::chrono::seconds(1));
  10418. auto resa = cli.Get("/a");
  10419. ASSERT_TRUE(!resa);
  10420. EXPECT_EQ(Error::Read, resa.error());
  10421. auto resb = cli.Get("/b");
  10422. ASSERT_TRUE(resb);
  10423. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10424. EXPECT_EQ("b", resb->body);
  10425. }
  10426. // Closing an idle keep-alive connection sends close_notify and returns. The
  10427. // server must not wait for the client's close_notify: an idle client never
  10428. // sends one, so the worker would be held until the read timeout expires, and
  10429. // stop() would wait for it.
  10430. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10431. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10432. ASSERT_TRUE(svr.is_valid());
  10433. svr.set_keep_alive_timeout(1);
  10434. svr.set_read_timeout(10, 0);
  10435. svr.Get("/", [](const Request &, Response &res) {
  10436. res.set_content("ok", "text/plain");
  10437. });
  10438. auto port = svr.bind_to_any_port(HOST);
  10439. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10440. auto se = detail::scope_exit([&] {
  10441. if (listen_thread.joinable()) {
  10442. svr.stop();
  10443. listen_thread.join();
  10444. }
  10445. });
  10446. svr.wait_until_ready();
  10447. SSLClient cli(HOST, port);
  10448. cli.enable_server_certificate_verification(false);
  10449. cli.set_keep_alive(true);
  10450. auto res = cli.Get("/");
  10451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10452. EXPECT_EQ(StatusCode::OK_200, res->status);
  10453. // Stay idle past the keep-alive timeout so the server closes the connection.
  10454. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10455. auto start = std::chrono::steady_clock::now();
  10456. svr.stop();
  10457. listen_thread.join();
  10458. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10459. std::chrono::steady_clock::now() - start)
  10460. .count();
  10461. EXPECT_LT(elapsed, 3000);
  10462. }
  10463. #endif
  10464. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10465. protected:
  10466. ServerTestWithAI_PASSIVE()
  10467. : cli_(HOST, PORT)
  10468. #ifdef CPPHTTPLIB_SSL_ENABLED
  10469. ,
  10470. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10471. #endif
  10472. {
  10473. #ifdef CPPHTTPLIB_SSL_ENABLED
  10474. cli_.enable_server_certificate_verification(false);
  10475. #endif
  10476. }
  10477. virtual void SetUp() {
  10478. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10479. res.set_content("Hello World!", "text/plain");
  10480. });
  10481. t_ = thread(
  10482. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10483. svr_.wait_until_ready();
  10484. }
  10485. virtual void TearDown() {
  10486. svr_.stop();
  10487. t_.join();
  10488. }
  10489. #ifdef CPPHTTPLIB_SSL_ENABLED
  10490. SSLClient cli_;
  10491. SSLServer svr_;
  10492. #else
  10493. Client cli_;
  10494. Server svr_;
  10495. #endif
  10496. thread t_;
  10497. };
  10498. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10499. auto res = cli_.Get("/hi");
  10500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10501. EXPECT_EQ(StatusCode::OK_200, res->status);
  10502. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10503. EXPECT_EQ("Hello World!", res->body);
  10504. }
  10505. class ServerUpDownTest : public ::testing::Test {
  10506. protected:
  10507. ServerUpDownTest() : cli_(HOST, PORT) {}
  10508. virtual void SetUp() {
  10509. t_ = thread([&]() {
  10510. svr_.bind_to_any_port(HOST);
  10511. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10512. ASSERT_TRUE(svr_.listen_after_bind());
  10513. });
  10514. svr_.wait_until_ready();
  10515. }
  10516. virtual void TearDown() {
  10517. svr_.stop();
  10518. t_.join();
  10519. }
  10520. Client cli_;
  10521. Server svr_;
  10522. thread t_;
  10523. };
  10524. TEST_F(ServerUpDownTest, QuickStartStop) {
  10525. // Should not crash, especially when run with
  10526. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10527. }
  10528. class PayloadMaxLengthTest : public ::testing::Test {
  10529. protected:
  10530. PayloadMaxLengthTest()
  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_.set_payload_max_length(8);
  10543. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10544. res.set_content("test", "text/plain");
  10545. });
  10546. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  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(PayloadMaxLengthTest, ExceedLimit) {
  10563. auto res = cli_.Post("/test", "123456789", "text/plain");
  10564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10565. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10566. res = cli_.Post("/test", "12345678", "text/plain");
  10567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10568. EXPECT_EQ(StatusCode::OK_200, res->status);
  10569. }
  10570. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10571. // Test chunked encoding with payload exceeding the 8-byte limit
  10572. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10573. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10575. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10576. }
  10577. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10578. // Test chunked encoding with payload within the 8-byte limit
  10579. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10580. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10582. EXPECT_EQ(StatusCode::OK_200, res->status);
  10583. }
  10584. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10585. // Test using send_request to send chunked data exceeding payload limit
  10586. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10587. "Host: " +
  10588. std::string(HOST) + ":" + std::to_string(PORT) +
  10589. "\r\n"
  10590. "Transfer-Encoding: chunked\r\n"
  10591. "Connection: close\r\n"
  10592. "\r\n"
  10593. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10594. "0123456789\r\n"
  10595. "0\r\n" // End chunk
  10596. "\r\n";
  10597. std::string response;
  10598. bool result = send_request(1, chunked_request, &response);
  10599. if (!result) {
  10600. // If send_request fails, it might be because the server closed the
  10601. // connection due to payload limit enforcement, which is acceptable
  10602. SUCCEED()
  10603. << "Server rejected oversized chunked request (connection closed)";
  10604. } else {
  10605. // If we got a response, check if it's an error response or connection was
  10606. // closed early Short response length indicates connection was closed due to
  10607. // payload limit
  10608. if (response.length() <= 10) {
  10609. SUCCEED() << "Server closed connection for oversized chunked request";
  10610. } else {
  10611. // Check for error status codes
  10612. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10613. response.find("Payload Too Large") != std::string::npos ||
  10614. response.find("400") != std::string::npos);
  10615. }
  10616. }
  10617. }
  10618. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10619. // Test request without Content-Length header exceeding payload limit
  10620. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10621. "Host: " +
  10622. std::string(HOST) + ":" +
  10623. std::to_string(PORT) +
  10624. "\r\n"
  10625. "Connection: close\r\n"
  10626. "\r\n";
  10627. // Add payload exceeding the 8-byte limit
  10628. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10629. request_without_content_length += large_payload;
  10630. std::string response;
  10631. bool result = send_request(1, request_without_content_length, &response);
  10632. if (!result) {
  10633. // If send_request fails, server likely closed connection due to payload
  10634. // limit
  10635. SUCCEED() << "Server rejected oversized request without Content-Length "
  10636. "(connection closed)";
  10637. } else {
  10638. // Check if server responded with error or closed connection early
  10639. if (response.length() <= 10) {
  10640. SUCCEED() << "Server closed connection for oversized request without "
  10641. "Content-Length";
  10642. } else {
  10643. // Check for error status codes
  10644. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10645. response.find("Payload Too Large") != std::string::npos ||
  10646. response.find("400") != std::string::npos);
  10647. }
  10648. }
  10649. }
  10650. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10651. // Test request without Content-Length header within payload limit
  10652. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10653. "Host: " +
  10654. std::string(HOST) + ":" +
  10655. std::to_string(PORT) +
  10656. "\r\n"
  10657. "Connection: close\r\n"
  10658. "\r\n";
  10659. // Add payload within the 8-byte limit
  10660. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10661. request_without_content_length += small_payload;
  10662. std::string response;
  10663. bool result = send_request(1, request_without_content_length, &response);
  10664. // For requests without Content-Length, the server may have different behavior
  10665. // The key is that it should not reject due to payload limit for small
  10666. // payloads
  10667. if (result) {
  10668. // Check for any HTTP response (success or error, but not connection closed)
  10669. if (response.length() > 10) {
  10670. SUCCEED()
  10671. << "Server processed request without Content-Length within limit";
  10672. } else {
  10673. // Short response might indicate connection closed, which is acceptable
  10674. SUCCEED() << "Server closed connection for request without "
  10675. "Content-Length (acceptable behavior)";
  10676. }
  10677. } else {
  10678. // Connection failure might be due to protocol requirements
  10679. SUCCEED() << "Connection issue with request without Content-Length "
  10680. "(environment-specific)";
  10681. }
  10682. }
  10683. class LargePayloadMaxLengthTest : public ::testing::Test {
  10684. protected:
  10685. LargePayloadMaxLengthTest()
  10686. : cli_(HOST, PORT)
  10687. #ifdef CPPHTTPLIB_SSL_ENABLED
  10688. ,
  10689. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10690. #endif
  10691. {
  10692. #ifdef CPPHTTPLIB_SSL_ENABLED
  10693. cli_.enable_server_certificate_verification(false);
  10694. #endif
  10695. }
  10696. virtual void SetUp() {
  10697. // Set 10MB payload limit
  10698. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10699. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10700. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10701. res.set_content("Large payload test", "text/plain");
  10702. });
  10703. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10704. svr_.wait_until_ready();
  10705. }
  10706. virtual void TearDown() {
  10707. svr_.stop();
  10708. t_.join();
  10709. }
  10710. #ifdef CPPHTTPLIB_SSL_ENABLED
  10711. SSLClient cli_;
  10712. SSLServer svr_;
  10713. #else
  10714. Client cli_;
  10715. Server svr_;
  10716. #endif
  10717. thread t_;
  10718. };
  10719. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10720. // Test chunked encoding with payload within 10MB limit
  10721. std::string medium_payload(5 * 1024 * 1024,
  10722. 'A'); // 5MB payload, within 10MB limit
  10723. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. EXPECT_EQ(StatusCode::OK_200, res->status);
  10726. }
  10727. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10728. // Test chunked encoding with payload exceeding 10MB limit
  10729. std::string large_payload(12 * 1024 * 1024,
  10730. 'B'); // 12MB payload, exceeds 10MB limit
  10731. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10732. // Server may either return 413 or close the connection
  10733. if (res) {
  10734. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10735. } else {
  10736. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10737. }
  10738. }
  10739. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10740. // Test request without Content-Length header within 10MB limit
  10741. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10742. "Host: " +
  10743. std::string(HOST) + ":" +
  10744. std::to_string(PORT) +
  10745. "\r\n"
  10746. "Connection: close\r\n"
  10747. "\r\n";
  10748. // Add 1MB payload (within 10MB limit)
  10749. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10750. request_without_content_length += medium_payload;
  10751. std::string response;
  10752. bool result = send_request(5, request_without_content_length, &response);
  10753. if (result) {
  10754. // Should get a proper HTTP response for payloads within limit
  10755. if (response.length() > 10) {
  10756. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10757. "10MB limit";
  10758. } else {
  10759. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10760. "Content-Length)";
  10761. }
  10762. } else {
  10763. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10764. }
  10765. }
  10766. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10767. // Test request without Content-Length header exceeding 10MB limit
  10768. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10769. "Host: " +
  10770. std::string(HOST) + ":" +
  10771. std::to_string(PORT) +
  10772. "\r\n"
  10773. "Connection: close\r\n"
  10774. "\r\n";
  10775. // Add 12MB payload (exceeds 10MB limit)
  10776. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10777. request_without_content_length += large_payload;
  10778. std::string response;
  10779. bool result = send_request(10, request_without_content_length, &response);
  10780. if (!result) {
  10781. // Server should close connection due to payload limit
  10782. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10783. "(connection closed)";
  10784. } else {
  10785. // Check for error response
  10786. if (response.length() <= 10) {
  10787. SUCCEED()
  10788. << "Server closed connection for 12MB request exceeding 10MB limit";
  10789. } else {
  10790. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10791. response.find("Payload Too Large") != std::string::npos ||
  10792. response.find("400") != std::string::npos);
  10793. }
  10794. }
  10795. }
  10796. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10797. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10798. // path.
  10799. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10800. Server svr;
  10801. const size_t LIMIT = 64 * 1024; // 64KB
  10802. svr.set_payload_max_length(LIMIT);
  10803. size_t total = 0;
  10804. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10805. const ContentReader &content_reader) {
  10806. content_reader([&](const char * /*data*/, size_t len) {
  10807. total += len;
  10808. return true;
  10809. });
  10810. res.status = 200;
  10811. res.set_content("stream_ok", "text/plain");
  10812. });
  10813. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10814. auto se = detail::scope_exit([&] {
  10815. svr.stop();
  10816. thread.join();
  10817. ASSERT_FALSE(svr.is_running());
  10818. });
  10819. svr.wait_until_ready();
  10820. // Prepare 256KB raw data and gzip-compress it
  10821. std::string raw(256 * 1024, 'A');
  10822. std::string gz;
  10823. {
  10824. z_stream zs{};
  10825. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10826. Z_DEFAULT_STRATEGY);
  10827. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10828. zs.avail_in = static_cast<uInt>(raw.size());
  10829. char outbuf[4096];
  10830. int ret;
  10831. do {
  10832. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10833. zs.avail_out = sizeof(outbuf);
  10834. ret = deflate(&zs, Z_FINISH);
  10835. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10836. } while (ret != Z_STREAM_END);
  10837. deflateEnd(&zs);
  10838. }
  10839. Client cli(HOST, PORT);
  10840. cli.set_connection_timeout(std::chrono::seconds(5));
  10841. Headers headers = {{"Content-Encoding", "gzip"}};
  10842. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10843. "application/octet-stream");
  10844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10845. // Server must reject oversized decompressed payloads with 413.
  10846. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10847. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10848. EXPECT_LE(total, LIMIT);
  10849. }
  10850. #ifndef CPPHTTPLIB_SSL_ENABLED
  10851. // For a request with neither Content-Length nor Transfer-Encoding, the
  10852. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10853. // compressed wire bytes straight to the ContentReader without ever routing
  10854. // them through the decompressor, so payload_max_length_ only bounded the
  10855. // compressed size on the wire, not the decompressed size.
  10856. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10857. Server svr;
  10858. const size_t LIMIT = 64 * 1024; // 64KB
  10859. svr.set_payload_max_length(LIMIT);
  10860. size_t total = 0;
  10861. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10862. const ContentReader &content_reader) {
  10863. content_reader([&](const char * /*data*/, size_t len) {
  10864. total += len;
  10865. return true;
  10866. });
  10867. res.status = 200;
  10868. res.set_content("stream_ok", "text/plain");
  10869. });
  10870. auto port = svr.bind_to_any_port(HOST);
  10871. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10872. auto se = detail::scope_exit([&] {
  10873. svr.stop();
  10874. thread.join();
  10875. ASSERT_FALSE(svr.is_running());
  10876. });
  10877. svr.wait_until_ready();
  10878. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10879. // StreamingGzipDecompression test above.
  10880. std::string raw(256 * 1024, 'A');
  10881. std::string gz;
  10882. {
  10883. httplib::detail::gzip_compressor compressor;
  10884. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10885. [&](const char *chunk, size_t len) {
  10886. gz.append(chunk, len);
  10887. return true;
  10888. });
  10889. ASSERT_TRUE(result);
  10890. }
  10891. // Send the gzip body over raw TCP with neither Content-Length nor
  10892. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10893. // kicks in.
  10894. std::string req = "POST /stream HTTP/1.1\r\n"
  10895. "Host: " +
  10896. std::string(HOST) + ":" + std::to_string(port) +
  10897. "\r\n"
  10898. "Content-Encoding: gzip\r\n"
  10899. "Connection: close\r\n"
  10900. "\r\n" +
  10901. gz;
  10902. std::string response;
  10903. ASSERT_TRUE(send_request(5, req, &response, port));
  10904. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10905. EXPECT_LE(total, LIMIT);
  10906. }
  10907. #endif
  10908. #endif
  10909. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10910. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10911. // the payload must be passed through untouched instead of being rejected.
  10912. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10913. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10914. Server svr;
  10915. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10916. res.set_content(body, "image/jpeg");
  10917. res.set_header("Content-Encoding", "UTF-8");
  10918. });
  10919. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10920. res.set_content(body, "image/jpeg");
  10921. res.set_header("Content-Encoding", "identity");
  10922. });
  10923. svr.Post("/echo", [](const Request &req, Response &res) {
  10924. res.set_content(req.body, "image/jpeg");
  10925. });
  10926. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10927. auto se = detail::scope_exit([&] {
  10928. svr.stop();
  10929. t.join();
  10930. ASSERT_FALSE(svr.is_running());
  10931. });
  10932. svr.wait_until_ready();
  10933. Client cli(HOST, PORT);
  10934. {
  10935. auto res = cli.Get("/image");
  10936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10937. EXPECT_EQ(StatusCode::OK_200, res->status);
  10938. EXPECT_EQ(body, res->body);
  10939. }
  10940. {
  10941. auto res = cli.Get("/identity");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. EXPECT_EQ(body, res->body);
  10945. }
  10946. {
  10947. // The same applies to a request body reaching the server.
  10948. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10949. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10951. EXPECT_EQ(StatusCode::OK_200, res->status);
  10952. EXPECT_EQ(body, res->body);
  10953. }
  10954. }
  10955. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10956. // gzip-encoded response even when the build has no zlib support.
  10957. static const char GZIPPED_HELLO_WORLD[] = {
  10958. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10959. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10960. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10961. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10962. // A content coding is a whole token, not something the field value merely
  10963. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10964. // as "fibre" look like Brotli, and turned a multi-coding value like
  10965. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10966. // it was never meant to see.
  10967. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10968. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10969. Server svr;
  10970. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10971. res.set_content(body, "image/jpeg");
  10972. res.set_header("Content-Encoding", "fibre");
  10973. });
  10974. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10975. res.set_content(body, "image/jpeg");
  10976. res.set_header("Content-Encoding", "gzip, br");
  10977. });
  10978. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10979. res.set_content(body, "image/jpeg");
  10980. res.set_header("Content-Encoding", "x-zstd-ish");
  10981. });
  10982. auto port = svr.bind_to_any_port(HOST);
  10983. thread t = thread([&]() { svr.listen_after_bind(); });
  10984. auto se = detail::scope_exit([&] {
  10985. svr.stop();
  10986. t.join();
  10987. ASSERT_FALSE(svr.is_running());
  10988. });
  10989. svr.wait_until_ready();
  10990. Client cli(HOST, port);
  10991. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10992. auto res = cli.Get(path);
  10993. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10994. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10995. // Not a coding we recognize, so the payload comes back untouched
  10996. EXPECT_EQ(body, res->body) << path;
  10997. }
  10998. }
  10999. // A content coding cpp-httplib recognizes but was not built with must be
  11000. // reported as such. Handing the still-compressed payload back to the caller
  11001. // would silently corrupt it.
  11002. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11003. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11004. Server svr;
  11005. // "image/jpeg" keeps the server from applying a content coding of its own,
  11006. // so the hand-crafted Content-Encoding below survives.
  11007. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11008. res.set_content(gzipped, "image/jpeg");
  11009. res.set_header("Content-Encoding", "gzip");
  11010. });
  11011. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11012. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11013. res.set_content(gzipped, "image/jpeg");
  11014. res.set_header("Content-Encoding", "GZIP");
  11015. });
  11016. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. t.join();
  11020. ASSERT_FALSE(svr.is_running());
  11021. });
  11022. svr.wait_until_ready();
  11023. Client cli(HOST, PORT);
  11024. {
  11025. auto res = cli.Get("/gzipped");
  11026. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11028. EXPECT_EQ("Hello World!", res->body);
  11029. #else
  11030. ASSERT_FALSE(res);
  11031. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11032. #endif
  11033. }
  11034. {
  11035. // open_stream() must behave the same way.
  11036. auto handle = cli.open_stream("GET", "/gzipped");
  11037. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11038. ASSERT_TRUE(handle.is_valid());
  11039. std::string received;
  11040. char buf[256];
  11041. ssize_t n;
  11042. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11043. received.append(buf, static_cast<size_t>(n));
  11044. }
  11045. EXPECT_EQ("Hello World!", received);
  11046. #else
  11047. EXPECT_FALSE(handle.is_valid());
  11048. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11049. #endif
  11050. }
  11051. {
  11052. // A differently-cased coding must not be mistaken for an unknown one, or
  11053. // the body would be handed back still compressed.
  11054. auto res = cli.Get("/gzipped-uppercase");
  11055. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11057. EXPECT_EQ("Hello World!", res->body);
  11058. #else
  11059. ASSERT_FALSE(res);
  11060. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11061. #endif
  11062. }
  11063. }
  11064. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11065. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11066. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11067. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11068. // body a second time and appending a second Content-Encoding field line, so
  11069. // clients that decode one coding per listed value handed back raw gzip bytes.
  11070. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11071. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11072. Server svr;
  11073. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11074. // keeps the server from applying a coding of its own.
  11075. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11076. res.set_content(gzipped, "text/plain");
  11077. res.set_header("Content-Encoding", "gzip");
  11078. });
  11079. auto port = svr.bind_to_any_port(HOST);
  11080. thread t = thread([&]() { svr.listen_after_bind(); });
  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. Headers headers = {{"Accept-Encoding", "gzip"}};
  11089. auto res = cli.Get("/pre-gzipped", headers);
  11090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11091. EXPECT_EQ(StatusCode::OK_200, res->status);
  11092. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11093. EXPECT_EQ("Hello World!", res->body);
  11094. }
  11095. // A chunked provider settles its coding where the headers are written and
  11096. // reuses it at write time. Both ends of that have to hold: a handler's own
  11097. // Content-Encoding suppresses the coding, and a response without one is still
  11098. // compressed as it always was.
  11099. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11100. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11101. const std::string plain = "Hello World! Hello World! Hello World!";
  11102. Server svr;
  11103. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11104. res.set_header("Content-Encoding", "gzip");
  11105. res.set_chunked_content_provider(
  11106. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11107. sink.write(gzipped.data(), gzipped.size());
  11108. sink.done();
  11109. return true;
  11110. });
  11111. });
  11112. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11113. res.set_chunked_content_provider(
  11114. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11115. sink.write(plain.data(), plain.size());
  11116. sink.done();
  11117. return true;
  11118. });
  11119. });
  11120. auto port = svr.bind_to_any_port(HOST);
  11121. thread t = thread([&]() { svr.listen_after_bind(); });
  11122. auto se = detail::scope_exit([&] {
  11123. svr.stop();
  11124. t.join();
  11125. ASSERT_FALSE(svr.is_running());
  11126. });
  11127. svr.wait_until_ready();
  11128. Client cli(HOST, port);
  11129. Headers headers = {{"Accept-Encoding", "gzip"}};
  11130. {
  11131. auto res = cli.Get("/pre-gzipped", headers);
  11132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11133. EXPECT_EQ(StatusCode::OK_200, res->status);
  11134. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11135. EXPECT_EQ("Hello World!", res->body);
  11136. }
  11137. {
  11138. auto res = cli.Get("/negotiated", headers);
  11139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11140. EXPECT_EQ(StatusCode::OK_200, res->status);
  11141. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11142. EXPECT_EQ(plain, res->body);
  11143. }
  11144. }
  11145. #endif
  11146. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11147. // the same message as the comma-joined one, so both have to be read the same
  11148. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11149. // single gzip coding, and a body the sender says was encoded twice was handed
  11150. // back after one pass, still compressed but presented as decoded.
  11151. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11152. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11153. Server svr;
  11154. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11155. res.set_content(body, "image/jpeg");
  11156. res.headers.emplace("Content-Encoding", "gzip");
  11157. res.headers.emplace("Content-Encoding", "gzip");
  11158. });
  11159. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11160. res.set_content(body, "image/jpeg");
  11161. res.set_header("Content-Encoding", "gzip, gzip");
  11162. });
  11163. auto port = svr.bind_to_any_port(HOST);
  11164. thread t = thread([&]() { svr.listen_after_bind(); });
  11165. auto se = detail::scope_exit([&] {
  11166. svr.stop();
  11167. t.join();
  11168. ASSERT_FALSE(svr.is_running());
  11169. });
  11170. svr.wait_until_ready();
  11171. Client cli(HOST, port);
  11172. // Two codings is not something cpp-httplib decodes, so both representations
  11173. // take the pass-through path rather than one of them being gunzipped once.
  11174. for (const char *path : {"/split", "/joined"}) {
  11175. auto res = cli.Get(path);
  11176. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11177. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11178. EXPECT_EQ(body, res->body) << path;
  11179. }
  11180. }
  11181. // Regression test for DoS vulnerability: a malicious server sending a response
  11182. // without Content-Length header must not cause unbounded memory consumption on
  11183. // the client side. The client should stop reading after a reasonable limit,
  11184. // similar to the server-side set_payload_max_length protection.
  11185. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11186. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11187. #ifndef _WIN32
  11188. signal(SIGPIPE, SIG_IGN);
  11189. #endif
  11190. auto server_thread = std::thread([] {
  11191. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11192. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11193. default_socket_options(srv);
  11194. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11195. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11196. sockaddr_in addr{};
  11197. addr.sin_family = AF_INET;
  11198. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11199. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11200. int opt = 1;
  11201. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11202. #ifdef _WIN32
  11203. reinterpret_cast<const char *>(&opt),
  11204. #else
  11205. &opt,
  11206. #endif
  11207. sizeof(opt));
  11208. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11209. ::listen(srv, 1);
  11210. sockaddr_in cli_addr{};
  11211. socklen_t cli_len = sizeof(cli_addr);
  11212. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11213. if (cli != INVALID_SOCKET) {
  11214. char buf[4096];
  11215. ::recv(cli, buf, sizeof(buf), 0);
  11216. // Malicious response: no Content-Length, no chunked encoding
  11217. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11218. "Connection: close\r\n"
  11219. "\r\n";
  11220. ::send(cli,
  11221. #ifdef _WIN32
  11222. static_cast<const char *>(response_header.c_str()),
  11223. static_cast<int>(response_header.size()),
  11224. #else
  11225. response_header.c_str(), response_header.size(),
  11226. #endif
  11227. 0);
  11228. // Send 10MB of data
  11229. std::string chunk(64 * 1024, 'A');
  11230. size_t total_sent = 0;
  11231. while (total_sent < MALICIOUS_DATA_SIZE) {
  11232. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11233. auto sent = ::send(cli,
  11234. #ifdef _WIN32
  11235. static_cast<const char *>(chunk.c_str()),
  11236. static_cast<int>(to_send),
  11237. #else
  11238. chunk.c_str(), to_send,
  11239. #endif
  11240. 0);
  11241. if (sent <= 0) break;
  11242. total_sent += static_cast<size_t>(sent);
  11243. }
  11244. detail::close_socket(cli);
  11245. }
  11246. detail::close_socket(srv);
  11247. });
  11248. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11249. size_t total_read = 0;
  11250. {
  11251. Client cli("127.0.0.1", PORT + 2);
  11252. cli.set_read_timeout(5, 0);
  11253. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11254. auto stream = cli.open_stream("GET", "/malicious");
  11255. ASSERT_TRUE(stream.is_valid());
  11256. char buffer[64 * 1024];
  11257. ssize_t n;
  11258. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11259. total_read += static_cast<size_t>(n);
  11260. }
  11261. } // StreamHandle and Client destroyed here, closing the socket
  11262. server_thread.join();
  11263. // With set_payload_max_length, the client must stop reading before consuming
  11264. // all 10MB. The read loop should be cut off at or near the configured limit.
  11265. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11266. << "Client read " << total_read << " bytes, exceeding the configured "
  11267. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11268. }
  11269. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11270. // the entire response body without truncation.
  11271. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11272. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11273. #ifndef _WIN32
  11274. signal(SIGPIPE, SIG_IGN);
  11275. #endif
  11276. auto server_thread = std::thread([] {
  11277. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11278. default_socket_options(srv);
  11279. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11281. sockaddr_in addr{};
  11282. addr.sin_family = AF_INET;
  11283. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11285. int opt = 1;
  11286. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11287. #ifdef _WIN32
  11288. reinterpret_cast<const char *>(&opt),
  11289. #else
  11290. &opt,
  11291. #endif
  11292. sizeof(opt));
  11293. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11294. ::listen(srv, 1);
  11295. sockaddr_in cli_addr{};
  11296. socklen_t cli_len = sizeof(cli_addr);
  11297. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11298. if (cli != INVALID_SOCKET) {
  11299. char buf[4096];
  11300. ::recv(cli, buf, sizeof(buf), 0);
  11301. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11302. "Connection: close\r\n"
  11303. "\r\n";
  11304. ::send(cli,
  11305. #ifdef _WIN32
  11306. static_cast<const char *>(response_header.c_str()),
  11307. static_cast<int>(response_header.size()),
  11308. #else
  11309. response_header.c_str(), response_header.size(),
  11310. #endif
  11311. 0);
  11312. std::string chunk(64 * 1024, 'A');
  11313. size_t total_sent = 0;
  11314. while (total_sent < DATA_SIZE) {
  11315. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11316. auto sent = ::send(cli,
  11317. #ifdef _WIN32
  11318. static_cast<const char *>(chunk.c_str()),
  11319. static_cast<int>(to_send),
  11320. #else
  11321. chunk.c_str(), to_send,
  11322. #endif
  11323. 0);
  11324. if (sent <= 0) break;
  11325. total_sent += static_cast<size_t>(sent);
  11326. }
  11327. #ifdef _WIN32
  11328. ::shutdown(cli, SD_SEND);
  11329. #else
  11330. ::shutdown(cli, SHUT_WR);
  11331. #endif
  11332. // Drain until the client closes its end, ensuring all data is delivered
  11333. char drain[1024];
  11334. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11335. detail::close_socket(cli);
  11336. }
  11337. detail::close_socket(srv);
  11338. });
  11339. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11340. size_t total_read = 0;
  11341. {
  11342. Client cli("127.0.0.1", PORT + 2);
  11343. cli.set_read_timeout(5, 0);
  11344. cli.set_payload_max_length(0); // 0 means no limit
  11345. auto stream = cli.open_stream("GET", "/data");
  11346. ASSERT_TRUE(stream.is_valid());
  11347. char buffer[64 * 1024];
  11348. ssize_t n;
  11349. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11350. total_read += static_cast<size_t>(n);
  11351. }
  11352. }
  11353. server_thread.join();
  11354. EXPECT_EQ(total_read, DATA_SIZE)
  11355. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11356. << " bytes without truncation, but only read " << total_read << " bytes.";
  11357. }
  11358. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11359. // enormous Content-Length must not cause the client to pre-allocate a huge
  11360. // response body buffer. The reservation is capped at payload_max_length_, and
  11361. // the read itself fails when the body exceeds the limit.
  11362. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11363. #ifndef _WIN32
  11364. signal(SIGPIPE, SIG_IGN);
  11365. #endif
  11366. auto server_thread = std::thread([] {
  11367. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11368. default_socket_options(srv);
  11369. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11370. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11371. sockaddr_in addr{};
  11372. addr.sin_family = AF_INET;
  11373. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11374. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11375. int opt = 1;
  11376. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11377. #ifdef _WIN32
  11378. reinterpret_cast<const char *>(&opt),
  11379. #else
  11380. &opt,
  11381. #endif
  11382. sizeof(opt));
  11383. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11384. ::listen(srv, 1);
  11385. sockaddr_in cli_addr{};
  11386. socklen_t cli_len = sizeof(cli_addr);
  11387. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11388. if (cli != INVALID_SOCKET) {
  11389. char buf[4096];
  11390. ::recv(cli, buf, sizeof(buf), 0);
  11391. // Malicious response: claim a 20GB body but send only a tiny payload.
  11392. std::string response = "HTTP/1.1 200 OK\r\n"
  11393. "Content-Length: 20000000000\r\n"
  11394. "\r\n"
  11395. "abc";
  11396. ::send(cli,
  11397. #ifdef _WIN32
  11398. static_cast<const char *>(response.c_str()),
  11399. static_cast<int>(response.size()),
  11400. #else
  11401. response.c_str(), response.size(),
  11402. #endif
  11403. 0);
  11404. detail::close_socket(cli);
  11405. }
  11406. detail::close_socket(srv);
  11407. });
  11408. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11409. {
  11410. Client cli("127.0.0.1", PORT + 2);
  11411. cli.set_read_timeout(5, 0);
  11412. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11413. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11414. // (server claims more bytes than payload_max_length permits), but it must
  11415. // not exhaust memory before getting there.
  11416. auto res = cli.Get("/malicious");
  11417. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11418. }
  11419. server_thread.join();
  11420. }
  11421. // Verify that content_receiver bypasses the default payload_max_length,
  11422. // allowing streaming downloads larger than 100MB without requiring an explicit
  11423. // set_payload_max_length call.
  11424. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11425. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11426. #ifndef _WIN32
  11427. signal(SIGPIPE, SIG_IGN);
  11428. #endif
  11429. auto server_thread = std::thread([] {
  11430. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11431. default_socket_options(srv);
  11432. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11433. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11434. sockaddr_in addr{};
  11435. addr.sin_family = AF_INET;
  11436. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11437. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11438. int opt = 1;
  11439. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11440. #ifdef _WIN32
  11441. reinterpret_cast<const char *>(&opt),
  11442. #else
  11443. &opt,
  11444. #endif
  11445. sizeof(opt));
  11446. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11447. ::listen(srv, 1);
  11448. sockaddr_in cli_addr{};
  11449. socklen_t cli_len = sizeof(cli_addr);
  11450. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11451. if (cli != INVALID_SOCKET) {
  11452. char buf[4096];
  11453. ::recv(cli, buf, sizeof(buf), 0);
  11454. // Response with Content-Length larger than default 100MB limit
  11455. auto content_length = std::to_string(DATA_SIZE);
  11456. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11457. "Content-Length: " +
  11458. content_length +
  11459. "\r\n"
  11460. "Connection: close\r\n"
  11461. "\r\n";
  11462. ::send(cli,
  11463. #ifdef _WIN32
  11464. static_cast<const char *>(response_header.c_str()),
  11465. static_cast<int>(response_header.size()),
  11466. #else
  11467. response_header.c_str(), response_header.size(),
  11468. #endif
  11469. 0);
  11470. std::string chunk(64 * 1024, 'A');
  11471. size_t total_sent = 0;
  11472. while (total_sent < DATA_SIZE) {
  11473. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11474. auto sent = ::send(cli,
  11475. #ifdef _WIN32
  11476. static_cast<const char *>(chunk.c_str()),
  11477. static_cast<int>(to_send),
  11478. #else
  11479. chunk.c_str(), to_send,
  11480. #endif
  11481. 0);
  11482. if (sent <= 0) break;
  11483. total_sent += static_cast<size_t>(sent);
  11484. }
  11485. detail::close_socket(cli);
  11486. }
  11487. detail::close_socket(srv);
  11488. });
  11489. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11490. size_t total_received = 0;
  11491. {
  11492. Client cli("127.0.0.1", PORT + 2);
  11493. cli.set_read_timeout(10, 0);
  11494. // Do NOT call set_payload_max_length — use the default 100MB limit
  11495. auto res =
  11496. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11497. total_received += data_length;
  11498. return true;
  11499. });
  11500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11501. EXPECT_EQ(StatusCode::OK_200, res->status);
  11502. }
  11503. server_thread.join();
  11504. EXPECT_EQ(total_received, DATA_SIZE)
  11505. << "With content_receiver, the client should read all " << DATA_SIZE
  11506. << " bytes despite the default 100MB payload_max_length, but only read "
  11507. << total_received << " bytes.";
  11508. }
  11509. // Verify that an explicit set_payload_max_length smaller than the response is
  11510. // enforced even when a content_receiver is used.
  11511. TEST(ClientVulnerabilityTest,
  11512. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11513. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11514. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11515. #ifndef _WIN32
  11516. signal(SIGPIPE, SIG_IGN);
  11517. #endif
  11518. auto server_thread = std::thread([] {
  11519. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11520. default_socket_options(srv);
  11521. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11522. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11523. sockaddr_in addr{};
  11524. addr.sin_family = AF_INET;
  11525. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11526. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11527. int opt = 1;
  11528. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11529. #ifdef _WIN32
  11530. reinterpret_cast<const char *>(&opt),
  11531. #else
  11532. &opt,
  11533. #endif
  11534. sizeof(opt));
  11535. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11536. ::listen(srv, 1);
  11537. sockaddr_in cli_addr{};
  11538. socklen_t cli_len = sizeof(cli_addr);
  11539. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11540. if (cli != INVALID_SOCKET) {
  11541. char buf[4096];
  11542. ::recv(cli, buf, sizeof(buf), 0);
  11543. auto content_length = std::to_string(DATA_SIZE);
  11544. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11545. "Content-Length: " +
  11546. content_length +
  11547. "\r\n"
  11548. "Connection: close\r\n"
  11549. "\r\n";
  11550. ::send(cli,
  11551. #ifdef _WIN32
  11552. static_cast<const char *>(response_header.c_str()),
  11553. static_cast<int>(response_header.size()),
  11554. #else
  11555. response_header.c_str(), response_header.size(),
  11556. #endif
  11557. 0);
  11558. std::string chunk(64 * 1024, 'A');
  11559. size_t total_sent = 0;
  11560. while (total_sent < DATA_SIZE) {
  11561. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11562. auto sent = ::send(cli,
  11563. #ifdef _WIN32
  11564. static_cast<const char *>(chunk.c_str()),
  11565. static_cast<int>(to_send),
  11566. #else
  11567. chunk.c_str(), to_send,
  11568. #endif
  11569. 0);
  11570. if (sent <= 0) break;
  11571. total_sent += static_cast<size_t>(sent);
  11572. }
  11573. detail::close_socket(cli);
  11574. }
  11575. detail::close_socket(srv);
  11576. });
  11577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11578. size_t total_received = 0;
  11579. {
  11580. Client cli("127.0.0.1", PORT + 2);
  11581. cli.set_read_timeout(10, 0);
  11582. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11583. auto res =
  11584. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11585. total_received += data_length;
  11586. return true;
  11587. });
  11588. // Should fail because 200MB exceeds the explicit 150MB limit
  11589. EXPECT_FALSE(res);
  11590. }
  11591. server_thread.join();
  11592. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11593. << "Client with content_receiver should respect the explicit "
  11594. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11595. << total_received << " bytes.";
  11596. }
  11597. // Verify that an explicit set_payload_max_length larger than the response
  11598. // allows the content_receiver to read all data successfully.
  11599. TEST(ClientVulnerabilityTest,
  11600. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11601. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11602. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11603. #ifndef _WIN32
  11604. signal(SIGPIPE, SIG_IGN);
  11605. #endif
  11606. auto server_thread = std::thread([] {
  11607. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11608. default_socket_options(srv);
  11609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11610. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11611. sockaddr_in addr{};
  11612. addr.sin_family = AF_INET;
  11613. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11614. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11615. int opt = 1;
  11616. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11617. #ifdef _WIN32
  11618. reinterpret_cast<const char *>(&opt),
  11619. #else
  11620. &opt,
  11621. #endif
  11622. sizeof(opt));
  11623. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11624. ::listen(srv, 1);
  11625. sockaddr_in cli_addr{};
  11626. socklen_t cli_len = sizeof(cli_addr);
  11627. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11628. if (cli != INVALID_SOCKET) {
  11629. char buf[4096];
  11630. ::recv(cli, buf, sizeof(buf), 0);
  11631. auto content_length = std::to_string(DATA_SIZE);
  11632. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11633. "Content-Length: " +
  11634. content_length +
  11635. "\r\n"
  11636. "Connection: close\r\n"
  11637. "\r\n";
  11638. ::send(cli,
  11639. #ifdef _WIN32
  11640. static_cast<const char *>(response_header.c_str()),
  11641. static_cast<int>(response_header.size()),
  11642. #else
  11643. response_header.c_str(), response_header.size(),
  11644. #endif
  11645. 0);
  11646. std::string chunk(64 * 1024, 'A');
  11647. size_t total_sent = 0;
  11648. while (total_sent < DATA_SIZE) {
  11649. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11650. auto sent = ::send(cli,
  11651. #ifdef _WIN32
  11652. static_cast<const char *>(chunk.c_str()),
  11653. static_cast<int>(to_send),
  11654. #else
  11655. chunk.c_str(), to_send,
  11656. #endif
  11657. 0);
  11658. if (sent <= 0) break;
  11659. total_sent += static_cast<size_t>(sent);
  11660. }
  11661. #ifdef _WIN32
  11662. ::shutdown(cli, SD_SEND);
  11663. #else
  11664. ::shutdown(cli, SHUT_WR);
  11665. #endif
  11666. char drain[1024];
  11667. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11668. detail::close_socket(cli);
  11669. }
  11670. detail::close_socket(srv);
  11671. });
  11672. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11673. size_t total_received = 0;
  11674. {
  11675. Client cli("127.0.0.1", PORT + 2);
  11676. cli.set_read_timeout(10, 0);
  11677. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11678. auto res =
  11679. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11680. total_received += data_length;
  11681. return true;
  11682. });
  11683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11684. EXPECT_EQ(StatusCode::OK_200, res->status);
  11685. }
  11686. server_thread.join();
  11687. EXPECT_EQ(total_received, DATA_SIZE)
  11688. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11689. << " bytes (larger than " << DATA_SIZE
  11690. << " bytes response), content_receiver should read all data, but only "
  11691. "read "
  11692. << total_received << " bytes.";
  11693. }
  11694. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11695. // Regression test for "zip bomb" attack on the client side: a malicious server
  11696. // sends a small gzip-compressed response that decompresses to a huge payload.
  11697. // The client must enforce payload_max_length on the decompressed size.
  11698. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11699. constexpr size_t DECOMPRESSED_SIZE =
  11700. 10 * 1024 * 1024; // 10MB after decompression
  11701. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11702. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11703. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11704. std::string compressed;
  11705. {
  11706. httplib::detail::gzip_compressor compressor;
  11707. bool ok =
  11708. compressor.compress(uncompressed.data(), uncompressed.size(),
  11709. /*last=*/true, [&](const char *buf, size_t len) {
  11710. compressed.append(buf, len);
  11711. return true;
  11712. });
  11713. ASSERT_TRUE(ok);
  11714. }
  11715. // Sanity: compressed data should be much smaller than the decompressed size
  11716. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11717. #ifndef _WIN32
  11718. signal(SIGPIPE, SIG_IGN);
  11719. #endif
  11720. // Set up the listening socket in the main thread so the server is guaranteed
  11721. // to be ready before the client connects (eliminates race condition).
  11722. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11723. default_socket_options(srv);
  11724. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11725. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11726. sockaddr_in addr{};
  11727. addr.sin_family = AF_INET;
  11728. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11729. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11730. int opt = 1;
  11731. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11732. #ifdef _WIN32
  11733. reinterpret_cast<const char *>(&opt),
  11734. #else
  11735. &opt,
  11736. #endif
  11737. sizeof(opt));
  11738. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11739. ASSERT_EQ(0, ::listen(srv, 1));
  11740. auto server_thread = std::thread([&compressed, srv] {
  11741. sockaddr_in cli_addr{};
  11742. socklen_t cli_len = sizeof(cli_addr);
  11743. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11744. if (cli != INVALID_SOCKET) {
  11745. // Read the full HTTP request (until \r\n\r\n)
  11746. char buf[4096];
  11747. size_t total = 0;
  11748. while (total < sizeof(buf)) {
  11749. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11750. if (n <= 0) break;
  11751. total += static_cast<size_t>(n);
  11752. // Check for end of headers
  11753. if (total >= 4) {
  11754. std::string req(buf, total);
  11755. if (req.find("\r\n\r\n") != std::string::npos) break;
  11756. }
  11757. }
  11758. // Malicious response: gzip-compressed body, no Content-Length
  11759. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11760. "Content-Encoding: gzip\r\n"
  11761. "Connection: close\r\n"
  11762. "\r\n";
  11763. ::send(cli,
  11764. #ifdef _WIN32
  11765. static_cast<const char *>(response_header.c_str()),
  11766. static_cast<int>(response_header.size()),
  11767. #else
  11768. response_header.c_str(), response_header.size(),
  11769. #endif
  11770. 0);
  11771. // Send the compressed payload (small on the wire, huge when decompressed)
  11772. size_t total_sent = 0;
  11773. while (total_sent < compressed.size()) {
  11774. auto to_send = std::min(compressed.size() - total_sent,
  11775. static_cast<size_t>(64 * 1024));
  11776. auto sent =
  11777. ::send(cli,
  11778. #ifdef _WIN32
  11779. static_cast<const char *>(compressed.c_str() + total_sent),
  11780. static_cast<int>(to_send),
  11781. #else
  11782. compressed.c_str() + total_sent, to_send,
  11783. #endif
  11784. 0);
  11785. if (sent <= 0) break;
  11786. total_sent += static_cast<size_t>(sent);
  11787. }
  11788. detail::close_socket(cli);
  11789. }
  11790. });
  11791. auto se = detail::scope_exit([&] {
  11792. detail::close_socket(srv);
  11793. server_thread.join();
  11794. });
  11795. size_t total_decompressed = 0;
  11796. {
  11797. Client cli("127.0.0.1", PORT + 3);
  11798. cli.set_read_timeout(5, 0);
  11799. cli.set_decompress(true);
  11800. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11801. auto stream = cli.open_stream("GET", "/zipbomb");
  11802. ASSERT_TRUE(stream.is_valid());
  11803. char buffer[64 * 1024];
  11804. ssize_t n;
  11805. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11806. total_decompressed += static_cast<size_t>(n);
  11807. }
  11808. }
  11809. // The decompressed size must be capped by payload_max_length. Without
  11810. // protection, the client would decompress the full 10MB from a tiny
  11811. // compressed payload, enabling a zip bomb DoS attack.
  11812. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11813. << "Client decompressed " << total_decompressed
  11814. << " bytes from a gzip response. The decompressed size should be "
  11815. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11816. }
  11817. #endif
  11818. TEST(HostAndPortPropertiesTest, NoSSL) {
  11819. httplib::Client cli("www.google.com", 1234);
  11820. ASSERT_EQ("www.google.com", cli.host());
  11821. ASSERT_EQ(1234, cli.port());
  11822. }
  11823. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11824. httplib::Client cli("www.google.com:1234");
  11825. ASSERT_EQ("www.google.com", cli.host());
  11826. ASSERT_EQ(1234, cli.port());
  11827. }
  11828. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11829. // Port number that overflows int — should not crash, client becomes invalid
  11830. httplib::Client cli("http://www.google.com:99999999999999999999");
  11831. ASSERT_FALSE(cli.is_valid());
  11832. }
  11833. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11834. // Port 99999 exceeds valid range (1-65535) — should not crash
  11835. httplib::Client cli("http://www.google.com:99999");
  11836. ASSERT_FALSE(cli.is_valid());
  11837. }
  11838. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  11839. httplib::Client cli("http://www.google.com:80abc");
  11840. ASSERT_FALSE(cli.is_valid());
  11841. }
  11842. #ifdef CPPHTTPLIB_SSL_ENABLED
  11843. TEST(HostAndPortPropertiesTest, SSL) {
  11844. httplib::SSLClient cli("www.google.com");
  11845. ASSERT_EQ("www.google.com", cli.host());
  11846. ASSERT_EQ(443, cli.port());
  11847. }
  11848. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11849. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11850. std::string cert;
  11851. read_file(CA_CERT_FILE, cert);
  11852. httplib::SSLClient httplib_client("www.google.com");
  11853. // Load CA store first time
  11854. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11855. // Load CA store second time (update)
  11856. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11857. // Verify client is still valid and can make connections
  11858. httplib_client.enable_server_certificate_verification(true);
  11859. auto res = httplib_client.Get("/");
  11860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11861. // Google may return 200 or 301 depending on various factors
  11862. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11863. res->status == StatusCode::MovedPermanently_301);
  11864. }
  11865. TEST(SSLClientTest, ServerNameIndication_Online) {
  11866. auto host = "httpbingo.org";
  11867. auto path = std::string{"/get"};
  11868. SSLClient cli(host, 443);
  11869. auto res = cli.Get(path);
  11870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11871. ASSERT_EQ(StatusCode::OK_200, res->status);
  11872. }
  11873. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11874. // Use a site that will cause SSL verification failure due to self-signed cert
  11875. SSLClient cli("self-signed.badssl.com", 443);
  11876. cli.enable_server_certificate_verification(true);
  11877. auto res = cli.Get("/");
  11878. ASSERT_TRUE(!res);
  11879. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11880. // Verify backend error is captured for SSLServerVerification
  11881. // This occurs when certificate verification fails
  11882. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11883. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11884. EXPECT_NE(0UL, res.ssl_backend_error());
  11885. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11886. // For OpenSSL, ssl_error is 0 for verification errors
  11887. EXPECT_EQ(0, res.ssl_error());
  11888. #if !defined(_WIN32) || \
  11889. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11890. // On non-Windows or when Windows Schannel is disabled, the error comes
  11891. // from OpenSSL's verification
  11892. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11893. res.ssl_backend_error());
  11894. #endif
  11895. #endif
  11896. }
  11897. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11898. // Use a site where hostname doesn't match the certificate
  11899. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11900. SSLClient cli("wrong.host.badssl.com", 443);
  11901. cli.enable_server_certificate_verification(true);
  11902. cli.enable_server_hostname_verification(true);
  11903. auto res = cli.Get("/");
  11904. ASSERT_TRUE(!res);
  11905. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11906. // Verify backend error is captured for hostname verification failure
  11907. EXPECT_NE(0UL, res.ssl_backend_error());
  11908. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11909. // For OpenSSL, ssl_error is 0 for verification errors
  11910. EXPECT_EQ(0, res.ssl_error());
  11911. #if !defined(_WIN32) || \
  11912. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11913. // On non-Windows or when Windows Schannel is disabled, the error comes
  11914. // from OpenSSL's hostname verification
  11915. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11916. res.ssl_backend_error());
  11917. #endif
  11918. #endif
  11919. }
  11920. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11921. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11922. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11923. SSLClient cli("www.google.com", 443);
  11924. cli.enable_server_certificate_verification(true);
  11925. auto res = cli.Get("/");
  11926. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11927. }
  11928. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11929. SSLClient cli("www.google.com", 443);
  11930. cli.enable_server_certificate_verification(true);
  11931. cli.enable_windows_certificate_verification(false);
  11932. auto res = cli.Get("/");
  11933. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11934. }
  11935. // The server sends an intermediate cross-signed by a root Windows trusts,
  11936. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  11937. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  11938. SSLClient cli("accounts.spotify.com", 443);
  11939. auto res = cli.Get("/");
  11940. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  11941. << " ssl_backend_error=" << res.ssl_backend_error();
  11942. }
  11943. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  11944. // policy status, which no backend reports for a self-signed certificate.
  11945. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  11946. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11947. ASSERT_TRUE(svr.is_valid());
  11948. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11949. auto se = detail::scope_exit([&] {
  11950. svr.stop();
  11951. t.join();
  11952. ASSERT_FALSE(svr.is_running());
  11953. });
  11954. svr.wait_until_ready();
  11955. SSLClient cli("127.0.0.1", PORT);
  11956. cli.set_connection_timeout(30);
  11957. auto res = cli.Get("/");
  11958. ASSERT_FALSE(res);
  11959. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11960. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  11961. }
  11962. #endif
  11963. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11964. Client cli("https://google.com");
  11965. auto res = cli.Get("/");
  11966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11967. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11968. }
  11969. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11970. SSLClient cli("google.com");
  11971. cli.set_ca_cert_path(CA_CERT_FILE);
  11972. auto res = cli.Get("/");
  11973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11974. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11975. }
  11976. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11977. SSLClient cli("google.com");
  11978. cli.enable_server_certificate_verification(true);
  11979. cli.set_ca_cert_path("hello");
  11980. auto res = cli.Get("/");
  11981. ASSERT_TRUE(!res);
  11982. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11983. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11984. // should be set
  11985. EXPECT_EQ(0, res.ssl_error());
  11986. // Verify backend error is captured for SSLLoadingCerts
  11987. // This error occurs when loading CA certificates fails
  11988. EXPECT_NE(0UL, res.ssl_backend_error());
  11989. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11990. // OpenSSL specific error codes:
  11991. // > openssl errstr 0x80000002
  11992. // error:80000002:system library::No such file or directory
  11993. // > openssl errstr 0xA000126
  11994. // error:0A000126:SSL routines::unexpected eof while reading
  11995. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11996. res.ssl_backend_error() == 0xA000126);
  11997. #endif
  11998. }
  11999. TEST(SSLClientTest, ServerCertificateVerification4) {
  12000. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12001. ASSERT_TRUE(svr.is_valid());
  12002. svr.Get("/test", [&](const Request &, Response &res) {
  12003. res.set_content("test", "text/plain");
  12004. svr.stop();
  12005. ASSERT_TRUE(true);
  12006. });
  12007. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12008. auto se = detail::scope_exit([&] {
  12009. t.join();
  12010. ASSERT_FALSE(svr.is_running());
  12011. });
  12012. svr.wait_until_ready();
  12013. SSLClient cli("127.0.0.1", PORT);
  12014. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12015. cli.enable_server_certificate_verification(true);
  12016. cli.set_connection_timeout(30);
  12017. auto res = cli.Get("/test");
  12018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12019. ASSERT_EQ(StatusCode::OK_200, res->status);
  12020. }
  12021. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12022. std::string cert;
  12023. read_file(CA_CERT_FILE, cert);
  12024. SSLClient cli("google.com");
  12025. cli.load_ca_cert_store(cert.data(), cert.size());
  12026. const auto res = cli.Get("/");
  12027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12028. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12029. }
  12030. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12031. // clang-format off
  12032. static constexpr char cert[] =
  12033. "GlobalSign Root CA\n"
  12034. "==================\n"
  12035. "-----BEGIN CERTIFICATE-----\n"
  12036. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12037. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12038. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12039. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12040. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12041. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12042. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12043. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12044. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12045. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12046. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12047. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12048. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12049. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12050. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12051. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12052. "-----END CERTIFICATE-----\n";
  12053. // clang-format on
  12054. SSLClient cli("google.com");
  12055. cli.load_ca_cert_store(cert, sizeof(cert));
  12056. const auto res = cli.Get("/");
  12057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12058. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12059. }
  12060. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12061. SSLClient cli("www.youtube.com");
  12062. cli.set_ca_cert_path(CA_CERT_FILE);
  12063. cli.enable_server_certificate_verification(true);
  12064. cli.set_follow_location(true);
  12065. auto res = cli.Get("/");
  12066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12067. ASSERT_EQ(StatusCode::OK_200, res->status);
  12068. }
  12069. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12070. SSLClient cli("wWw.YouTube.Com");
  12071. cli.set_ca_cert_path(CA_CERT_FILE);
  12072. cli.enable_server_certificate_verification(true);
  12073. cli.enable_server_hostname_verification(true);
  12074. cli.set_follow_location(true);
  12075. auto res = cli.Get("/");
  12076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12077. ASSERT_EQ(StatusCode::OK_200, res->status);
  12078. }
  12079. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12080. SSLClient cli("gOoGlE.COm");
  12081. cli.enable_server_certificate_verification(true);
  12082. cli.enable_server_hostname_verification(true);
  12083. cli.set_follow_location(true);
  12084. auto res = cli.Get("/");
  12085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12086. ASSERT_EQ(StatusCode::OK_200, res->status);
  12087. }
  12088. TEST(SSLClientTest, Issue2004_Online) {
  12089. Client client("https://google.com");
  12090. client.set_follow_location(true);
  12091. auto res = client.Get("/");
  12092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12093. ASSERT_EQ(StatusCode::OK_200, res->status);
  12094. auto body = res->body;
  12095. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12096. }
  12097. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12098. // Create SSLClient with invalid cert/key to make is_valid() return false
  12099. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12100. "nonexistent_key.pem");
  12101. // is_valid() should be false due to cert loading failure
  12102. ASSERT_FALSE(cli.is_valid());
  12103. auto res = cli.Get("/");
  12104. ASSERT_FALSE(res);
  12105. EXPECT_EQ(Error::SSLConnection, res.error());
  12106. }
  12107. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12108. // Test for Issue #2251: SSL error not properly reported when client cert
  12109. // and key paths are swapped or mismatched
  12110. // This simulates the scenario where user accidentally swaps the cert and key
  12111. // files
  12112. // Using client cert file as private key and vice versa (completely wrong)
  12113. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12114. // Should fail validation due to cert/key mismatch
  12115. ASSERT_FALSE(cli.is_valid());
  12116. // Attempt to make a request should fail with proper error
  12117. auto res = cli.Get("/");
  12118. ASSERT_FALSE(res);
  12119. EXPECT_EQ(Error::SSLConnection, res.error());
  12120. // SSL error should be recorded in the Result object (this is the key fix for
  12121. // Issue #2251)
  12122. auto backend_error = res.ssl_backend_error();
  12123. EXPECT_NE(0u, backend_error);
  12124. }
  12125. // Tests cert/key mismatch detection at the TLS context level
  12126. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12127. // Test that using mismatched cert/key causes connection failure.
  12128. // We verify this at the SSLClient level rather than through internal
  12129. // TLS API functions.
  12130. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12131. cli.enable_server_certificate_verification(false);
  12132. cli.set_connection_timeout(2);
  12133. // The mismatch should cause a connection or handshake error
  12134. auto res = cli.Get("/test");
  12135. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12136. // Either way, the request should fail
  12137. EXPECT_FALSE(res);
  12138. }
  12139. #endif
  12140. #if 0
  12141. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12142. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12143. ASSERT_TRUE(cli != nullptr);
  12144. cli->set_address_family(AF_INET6);
  12145. cli->set_interface("en0");
  12146. auto res = cli->Get("/get");
  12147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12148. ASSERT_EQ(StatusCode::OK_200, res->status);
  12149. }
  12150. #endif
  12151. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12152. #ifdef CPPHTTPLIB_SSL_ENABLED
  12153. void ClientCertPresent(
  12154. const std::string &client_cert_file,
  12155. const std::string &client_private_key_file,
  12156. const std::string &client_encrypted_private_key_pass = std::string()) {
  12157. using namespace httplib::tls;
  12158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12159. CLIENT_CA_CERT_DIR);
  12160. ASSERT_TRUE(svr.is_valid());
  12161. svr.Get("/test", [&](const Request &req, Response &res) {
  12162. res.set_content("test", "text/plain");
  12163. auto cert = req.peer_cert();
  12164. ASSERT_TRUE(static_cast<bool>(cert));
  12165. std::string common_name = cert.subject_cn();
  12166. EXPECT_EQ("Common Name", common_name);
  12167. });
  12168. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12169. auto se = detail::scope_exit([&] {
  12170. svr.stop();
  12171. t.join();
  12172. ASSERT_FALSE(svr.is_running());
  12173. });
  12174. svr.wait_until_ready();
  12175. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12176. client_encrypted_private_key_pass);
  12177. cli.enable_server_certificate_verification(false);
  12178. cli.set_connection_timeout(30);
  12179. auto res = cli.Get("/test");
  12180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12181. ASSERT_EQ(StatusCode::OK_200, res->status);
  12182. }
  12183. TEST(SSLClientServerTest, ClientCertPresent) {
  12184. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12185. }
  12186. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12187. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12188. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12189. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12190. }
  12191. // PEM memory-based constructor tests (works with all TLS backends)
  12192. void PemMemoryClientCertPresent(
  12193. const std::string &client_cert_file,
  12194. const std::string &client_private_key_file,
  12195. const std::string &client_encrypted_private_key_pass = std::string()) {
  12196. // Read PEM files into memory
  12197. std::string server_cert_pem, server_key_pem;
  12198. std::string client_ca_pem;
  12199. std::string client_cert_pem, client_key_pem;
  12200. read_file(SERVER_CERT_FILE, server_cert_pem);
  12201. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12202. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12203. read_file(client_cert_file, client_cert_pem);
  12204. read_file(client_private_key_file, client_key_pem);
  12205. // Create server with PEM memory
  12206. SSLServer::PemMemory server_pem = {
  12207. server_cert_pem.c_str(),
  12208. server_cert_pem.size(),
  12209. server_key_pem.c_str(),
  12210. server_key_pem.size(),
  12211. client_ca_pem.c_str(),
  12212. client_ca_pem.size(),
  12213. nullptr // no password for server key
  12214. };
  12215. SSLServer svr(server_pem);
  12216. ASSERT_TRUE(svr.is_valid());
  12217. svr.Get("/test", [&](const Request &, Response &res) {
  12218. res.set_content("test", "text/plain");
  12219. });
  12220. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12221. auto se = detail::scope_exit([&] {
  12222. svr.stop();
  12223. t.join();
  12224. ASSERT_FALSE(svr.is_running());
  12225. });
  12226. svr.wait_until_ready();
  12227. // Create client with PEM memory
  12228. const char *password = client_encrypted_private_key_pass.empty()
  12229. ? nullptr
  12230. : client_encrypted_private_key_pass.c_str();
  12231. SSLClient::PemMemory client_pem = {
  12232. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12233. client_key_pem.size(), password};
  12234. SSLClient cli(HOST, PORT, client_pem);
  12235. cli.enable_server_certificate_verification(false);
  12236. cli.set_connection_timeout(30);
  12237. auto res = cli.Get("/test");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. ASSERT_EQ(StatusCode::OK_200, res->status);
  12240. }
  12241. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12242. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12243. }
  12244. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12245. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12246. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12247. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12248. }
  12249. TEST(SSLClientServerTest, ClientCertMissing) {
  12250. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12251. CLIENT_CA_CERT_DIR);
  12252. ASSERT_TRUE(svr.is_valid());
  12253. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12255. auto se = detail::scope_exit([&] {
  12256. svr.stop();
  12257. t.join();
  12258. ASSERT_FALSE(svr.is_running());
  12259. });
  12260. svr.wait_until_ready();
  12261. SSLClient cli(HOST, PORT);
  12262. cli.set_connection_timeout(30);
  12263. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12264. // the chain check on Windows, so the result does not depend on the order.
  12265. cli.enable_server_hostname_verification(false);
  12266. auto res = cli.Get("/test");
  12267. ASSERT_TRUE(!res);
  12268. // When client cert is missing and server requires it, connection fails
  12269. // Error type depends on backend implementation
  12270. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12271. res.error() == Error::SSLConnection);
  12272. // Verify backend error is captured
  12273. // Note: This test may have different error codes depending on the exact
  12274. // verification failure
  12275. EXPECT_NE(0UL, res.ssl_backend_error());
  12276. }
  12277. TEST(SSLClientServerTest, TrustDirOptional) {
  12278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12279. ASSERT_TRUE(svr.is_valid());
  12280. svr.Get("/test", [&](const Request &, Response &res) {
  12281. res.set_content("test", "text/plain");
  12282. });
  12283. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12284. auto se = detail::scope_exit([&] {
  12285. svr.stop();
  12286. t.join();
  12287. ASSERT_FALSE(svr.is_running());
  12288. });
  12289. svr.wait_until_ready();
  12290. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12291. cli.enable_server_certificate_verification(false);
  12292. cli.set_connection_timeout(30);
  12293. auto res = cli.Get("/test");
  12294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12295. ASSERT_EQ(StatusCode::OK_200, res->status);
  12296. }
  12297. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12298. class NoListenSSLServer : public SSLServer {
  12299. public:
  12300. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12301. const char *client_ca_cert_file_path,
  12302. const char *client_ca_cert_dir_path = nullptr)
  12303. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12304. client_ca_cert_dir_path),
  12305. stop_(false) {}
  12306. std::atomic_bool stop_;
  12307. private:
  12308. bool process_and_close_socket(socket_t /*sock*/) override {
  12309. // Don't create SSL context
  12310. while (!stop_.load()) {
  12311. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12312. }
  12313. return true;
  12314. }
  12315. };
  12316. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12317. CLIENT_CA_CERT_FILE);
  12318. ASSERT_TRUE(svr.is_valid());
  12319. svr.Get("/test", [&](const Request &, Response &res) {
  12320. res.set_content("test", "text/plain");
  12321. });
  12322. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12323. auto se = detail::scope_exit([&] {
  12324. svr.stop_ = true;
  12325. svr.stop();
  12326. t.join();
  12327. ASSERT_FALSE(svr.is_running());
  12328. });
  12329. svr.wait_until_ready();
  12330. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12331. cli.enable_server_certificate_verification(false);
  12332. cli.set_connection_timeout(1);
  12333. auto res = cli.Get("/test");
  12334. ASSERT_TRUE(!res);
  12335. EXPECT_EQ(Error::SSLConnection, res.error());
  12336. // Timeout results in WantRead error code (maps to backend-specific value)
  12337. EXPECT_NE(0, res.ssl_error());
  12338. }
  12339. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12340. // Test SSLServer with client certificate verification using the standard
  12341. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12342. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12343. CLIENT_CA_CERT_DIR);
  12344. ASSERT_TRUE(svr.is_valid());
  12345. svr.Get("/test", [&](const Request &req, Response &res) {
  12346. res.set_content("test", "text/plain");
  12347. auto cert = req.peer_cert();
  12348. ASSERT_TRUE(static_cast<bool>(cert));
  12349. auto common_name = cert.subject_cn();
  12350. EXPECT_EQ("Common Name", common_name);
  12351. });
  12352. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12353. auto se = detail::scope_exit([&] {
  12354. svr.stop();
  12355. t.join();
  12356. ASSERT_FALSE(svr.is_running());
  12357. });
  12358. svr.wait_until_ready();
  12359. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12360. cli.enable_server_certificate_verification(false);
  12361. cli.set_connection_timeout(30);
  12362. auto res = cli.Get("/test");
  12363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12364. ASSERT_EQ(StatusCode::OK_200, res->status);
  12365. }
  12366. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12367. // Verifies that wildcard matching and exact matching work consistently
  12368. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12369. using namespace httplib::tls;
  12370. // We need a running server to test against
  12371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12372. ASSERT_TRUE(svr.is_valid());
  12373. svr.Get("/test", [](const Request &, Response &res) {
  12374. res.set_content("ok", "text/plain");
  12375. });
  12376. thread t([&]() { svr.listen(HOST, PORT); });
  12377. auto se = detail::scope_exit([&] {
  12378. svr.stop();
  12379. t.join();
  12380. });
  12381. svr.wait_until_ready();
  12382. bool verify_callback_called = false;
  12383. bool verify_result_wrong = false;
  12384. SSLClient cli(HOST, PORT);
  12385. cli.enable_server_certificate_verification(true);
  12386. cli.set_ca_cert_path(CA_CERT_FILE);
  12387. cli.set_connection_timeout(5);
  12388. // Note: Test certificate has CN="Common Name", not "localhost"
  12389. bool verify_result_cn = false;
  12390. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12391. verify_callback_called = true;
  12392. if (!ctx.cert) return false;
  12393. // Test 1: "Common Name" should match (our test server cert CN)
  12394. verify_result_cn = ctx.check_hostname("Common Name");
  12395. // Test 2: wrong hostname should not match
  12396. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12397. return true; // Accept for the purpose of this test
  12398. });
  12399. auto res = cli.Get("/test");
  12400. // The request may succeed or fail depending on cert configuration
  12401. // but the callback should have been called
  12402. ASSERT_TRUE(verify_callback_called)
  12403. << "Verify callback should have been called";
  12404. // CN="Common Name" should match our test certificate
  12405. //
  12406. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12407. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12408. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12409. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12410. // <openssl/base.h>, which is included transitively when
  12411. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12412. #if defined(OPENSSL_IS_BORINGSSL)
  12413. EXPECT_FALSE(verify_result_cn)
  12414. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12415. #else
  12416. EXPECT_TRUE(verify_result_cn)
  12417. << "verify_hostname should match 'Common Name' (certificate CN)";
  12418. #endif
  12419. // Wrong hostname should not match
  12420. EXPECT_FALSE(verify_result_wrong)
  12421. << "verify_hostname should not match 'wronghost.example.com'";
  12422. }
  12423. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12424. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12425. // X509_check_ip behavior and must hold for every backend.
  12426. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12427. using namespace httplib::tls;
  12428. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12429. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12430. ASSERT_TRUE(svr.is_valid());
  12431. svr.Get("/test", [](const Request &, Response &res) {
  12432. res.set_content("ok", "text/plain");
  12433. });
  12434. thread t([&]() { svr.listen(HOST, PORT); });
  12435. auto se = detail::scope_exit([&] {
  12436. svr.stop();
  12437. t.join();
  12438. });
  12439. svr.wait_until_ready();
  12440. bool verify_callback_called = false;
  12441. bool ip_matched_via_cn = true;
  12442. SSLClient cli(HOST, PORT);
  12443. cli.enable_server_certificate_verification(true);
  12444. cli.set_ca_cert_path(CA_CERT_FILE);
  12445. cli.set_connection_timeout(5);
  12446. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12447. verify_callback_called = true;
  12448. if (!ctx.cert) return false;
  12449. // The IP appears only in the CN, so it must NOT be accepted.
  12450. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12451. return true; // Accept for the purpose of this test
  12452. });
  12453. cli.Get("/test");
  12454. ASSERT_TRUE(verify_callback_called)
  12455. << "Verify callback should have been called";
  12456. EXPECT_FALSE(ip_matched_via_cn)
  12457. << "An IP host must not be authenticated via the certificate CN";
  12458. }
  12459. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12460. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12461. using namespace httplib::tls;
  12462. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12463. SSLServer svr(SERVER_CERT_IPV6_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 san_matched = false;
  12476. bool wrong_ipv6_matched = true;
  12477. bool cn_ipv6_matched = true;
  12478. SSLClient cli(HOST, PORT);
  12479. cli.enable_server_certificate_verification(true);
  12480. cli.set_ca_cert_path(CA_CERT_FILE);
  12481. cli.set_connection_timeout(5);
  12482. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12483. verify_callback_called = true;
  12484. if (!ctx.cert) return false;
  12485. // Matches the IPv6 iPAddress SAN.
  12486. san_matched = ctx.check_hostname("2001:db8::1");
  12487. // A different IPv6 address must not match.
  12488. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12489. // "::1" lives only in the CN, so it must not be accepted.
  12490. cn_ipv6_matched = ctx.check_hostname("::1");
  12491. return true; // Accept for the purpose of this test
  12492. });
  12493. cli.Get("/test");
  12494. ASSERT_TRUE(verify_callback_called)
  12495. << "Verify callback should have been called";
  12496. EXPECT_TRUE(san_matched)
  12497. << "verify_hostname should match an IPv6 iPAddress SAN";
  12498. EXPECT_FALSE(wrong_ipv6_matched)
  12499. << "verify_hostname should not match a non-matching IPv6 address";
  12500. EXPECT_FALSE(cn_ipv6_matched)
  12501. << "An IPv6 host must not be authenticated via the certificate CN";
  12502. }
  12503. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  12504. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  12505. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  12506. using namespace httplib::tls;
  12507. // SANs: DNS:a.zz, IP:42.46.122.122
  12508. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12509. ASSERT_TRUE(svr.is_valid());
  12510. svr.Get("/test", [](const Request &, Response &res) {
  12511. res.set_content("ok", "text/plain");
  12512. });
  12513. auto port = svr.bind_to_any_port(HOST);
  12514. thread t([&]() { svr.listen_after_bind(); });
  12515. auto se = detail::scope_exit([&] {
  12516. svr.stop();
  12517. t.join();
  12518. });
  12519. svr.wait_until_ready();
  12520. bool verify_callback_called = false;
  12521. bool dns_san_matched = false;
  12522. bool ip_san_matched = false;
  12523. bool ip_matched_via_dns_san = true;
  12524. bool dns_matched_via_ip_san = true;
  12525. SSLClient cli(HOST, port);
  12526. cli.enable_server_certificate_verification(true);
  12527. cli.set_ca_cert_path(CA_CERT_FILE);
  12528. cli.set_connection_timeout(5);
  12529. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12530. verify_callback_called = true;
  12531. if (!ctx.cert) return false;
  12532. dns_san_matched = ctx.check_hostname("a.zz");
  12533. ip_san_matched = ctx.check_hostname("42.46.122.122");
  12534. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  12535. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  12536. return true; // Accept for the purpose of this test
  12537. });
  12538. cli.Get("/test");
  12539. ASSERT_TRUE(verify_callback_called)
  12540. << "Verify callback should have been called";
  12541. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  12542. EXPECT_TRUE(ip_san_matched)
  12543. << "verify_hostname should match an iPAddress SAN";
  12544. EXPECT_FALSE(ip_matched_via_dns_san)
  12545. << "An IP host must not be authenticated via a dNSName SAN";
  12546. EXPECT_FALSE(dns_matched_via_ip_san)
  12547. << "A DNS host must not be authenticated via an iPAddress SAN";
  12548. }
  12549. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  12550. // "www.*.example.test" names one host and not every host under example.test.
  12551. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  12552. using namespace httplib::tls;
  12553. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  12554. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  12555. ASSERT_TRUE(svr.is_valid());
  12556. svr.Get("/test", [](const Request &, Response &res) {
  12557. res.set_content("ok", "text/plain");
  12558. });
  12559. auto port = svr.bind_to_any_port(HOST);
  12560. thread t([&]() { svr.listen_after_bind(); });
  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 leftmost_wildcard_matched = false;
  12568. bool wildcard_spanned_labels = true;
  12569. bool inner_wildcard_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. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  12578. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  12579. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  12580. return true; // Accept for the purpose of this test
  12581. });
  12582. cli.Get("/test");
  12583. ASSERT_TRUE(verify_callback_called)
  12584. << "Verify callback should have been called";
  12585. EXPECT_TRUE(leftmost_wildcard_matched)
  12586. << "A leftmost wildcard should match a single label";
  12587. EXPECT_FALSE(wildcard_spanned_labels)
  12588. << "A wildcard label must not match more than one label";
  12589. EXPECT_FALSE(inner_wildcard_matched)
  12590. << "A wildcard outside the leftmost label must not be honoured";
  12591. }
  12592. // sans() must report each SAN entry under its own type.
  12593. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  12594. using namespace httplib::tls;
  12595. // SANs: DNS:a.zz, IP:42.46.122.122
  12596. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  12597. ASSERT_TRUE(svr.is_valid());
  12598. svr.Get("/test", [](const Request &, Response &res) {
  12599. res.set_content("ok", "text/plain");
  12600. });
  12601. auto port = svr.bind_to_any_port(HOST);
  12602. thread t([&]() { svr.listen_after_bind(); });
  12603. auto se = detail::scope_exit([&] {
  12604. svr.stop();
  12605. t.join();
  12606. });
  12607. svr.wait_until_ready();
  12608. bool verify_callback_called = false;
  12609. std::vector<SanEntry> sans;
  12610. SSLClient cli(HOST, port);
  12611. cli.enable_server_certificate_verification(true);
  12612. cli.set_ca_cert_path(CA_CERT_FILE);
  12613. cli.set_connection_timeout(5);
  12614. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12615. verify_callback_called = true;
  12616. if (!ctx.cert) return false;
  12617. sans = ctx.sans();
  12618. return true; // Accept for the purpose of this test
  12619. });
  12620. cli.Get("/test");
  12621. ASSERT_TRUE(verify_callback_called)
  12622. << "Verify callback should have been called";
  12623. auto has_san = [&](SanType type, const std::string &value) {
  12624. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  12625. return san.type == type && san.value == value;
  12626. });
  12627. };
  12628. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  12629. << "sans() should report the dNSName SAN";
  12630. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  12631. << "sans() should report the iPAddress SAN";
  12632. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  12633. << "sans() must not report the dNSName SAN as an address";
  12634. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  12635. << "sans() must not report the iPAddress SAN as a DNS name";
  12636. }
  12637. #endif
  12638. // mbedTLS-specific callback constructor test
  12639. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12640. #ifdef CPPHTTPLIB_SSL_ENABLED
  12641. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12642. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12643. ASSERT_TRUE(svr.is_valid());
  12644. // Set up a handler to verify client certificate is present
  12645. bool client_cert_verified = false;
  12646. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12647. // Verify that client certificate was provided
  12648. client_cert_verified = true;
  12649. res.set_content("success", "text/plain");
  12650. });
  12651. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12652. auto se = detail::scope_exit([&] {
  12653. svr.stop();
  12654. t.join();
  12655. ASSERT_FALSE(svr.is_running());
  12656. });
  12657. svr.wait_until_ready();
  12658. // Client with certificate
  12659. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12660. cli.enable_server_certificate_verification(false);
  12661. cli.set_connection_timeout(30);
  12662. auto res = cli.Get("/test");
  12663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12664. ASSERT_EQ(StatusCode::OK_200, res->status);
  12665. ASSERT_TRUE(client_cert_verified);
  12666. EXPECT_EQ("success", res->body);
  12667. }
  12668. #endif
  12669. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12670. // backends
  12671. #ifdef CPPHTTPLIB_SSL_ENABLED
  12672. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12673. using namespace httplib::tls;
  12674. // Test that when client CA cert file is provided,
  12675. // the server properly requests and validates client certificates
  12676. // Create a server with client authentication
  12677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12678. ASSERT_TRUE(svr.is_valid());
  12679. bool handler_called = false;
  12680. svr.Get("/test", [&](const Request &req, Response &res) {
  12681. handler_called = true;
  12682. // Verify that a client certificate was provided
  12683. auto cert = req.peer_cert();
  12684. ASSERT_TRUE(static_cast<bool>(cert));
  12685. // Get the issuer name
  12686. std::string issuer_str = cert.issuer_name();
  12687. ASSERT_FALSE(issuer_str.empty());
  12688. // The client certificate should be issued by our test CA
  12689. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12690. res.set_content("authenticated", "text/plain");
  12691. });
  12692. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12693. auto se = detail::scope_exit([&] {
  12694. svr.stop();
  12695. t.join();
  12696. ASSERT_FALSE(svr.is_running());
  12697. });
  12698. svr.wait_until_ready();
  12699. // Connect with a client certificate issued by the CA
  12700. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12701. cli.enable_server_certificate_verification(false);
  12702. cli.set_connection_timeout(30);
  12703. auto res = cli.Get("/test");
  12704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12705. ASSERT_EQ(StatusCode::OK_200, res->status);
  12706. ASSERT_TRUE(handler_called);
  12707. EXPECT_EQ("authenticated", res->body);
  12708. }
  12709. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12710. using namespace httplib::tls;
  12711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12712. ASSERT_TRUE(svr.is_valid());
  12713. svr.Get("/test", [](const Request &, Response &res) {
  12714. res.set_content("ok", "text/plain");
  12715. });
  12716. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12717. auto se = detail::scope_exit([&] {
  12718. svr.stop();
  12719. t.join();
  12720. });
  12721. svr.wait_until_ready();
  12722. SSLClient cli(HOST, PORT);
  12723. cli.enable_server_certificate_verification(false);
  12724. cli.set_connection_timeout(30);
  12725. bool cert_checked = false;
  12726. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12727. if (ctx.cert) {
  12728. auto sans = ctx.sans();
  12729. // Test certificate may or may not have SANs - just verify the API
  12730. // works If SANs exist, verify the types are valid
  12731. for (const auto &san : sans) {
  12732. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12733. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12734. san.type == SanType::OTHER);
  12735. EXPECT_FALSE(san.value.empty());
  12736. }
  12737. cert_checked = true;
  12738. }
  12739. return true;
  12740. });
  12741. auto res = cli.Get("/test");
  12742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12743. EXPECT_TRUE(cert_checked);
  12744. }
  12745. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12746. using namespace httplib::tls;
  12747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12748. ASSERT_TRUE(svr.is_valid());
  12749. svr.Get("/test", [](const Request &, Response &res) {
  12750. res.set_content("ok", "text/plain");
  12751. });
  12752. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12753. auto se = detail::scope_exit([&] {
  12754. svr.stop();
  12755. t.join();
  12756. });
  12757. svr.wait_until_ready();
  12758. SSLClient cli(HOST, PORT);
  12759. cli.enable_server_certificate_verification(false);
  12760. cli.set_connection_timeout(30);
  12761. bool validity_checked = false;
  12762. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12763. if (ctx.cert) {
  12764. time_t not_before = 0, not_after = 0;
  12765. bool result = ctx.validity(not_before, not_after);
  12766. EXPECT_TRUE(result);
  12767. // Verify that not_before < now < not_after for a valid cert
  12768. time_t now = time(nullptr);
  12769. EXPECT_LT(not_before, now);
  12770. EXPECT_GT(not_after, now);
  12771. validity_checked = true;
  12772. }
  12773. return true;
  12774. });
  12775. auto res = cli.Get("/test");
  12776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12777. EXPECT_TRUE(validity_checked);
  12778. }
  12779. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12780. using namespace httplib::tls;
  12781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12782. ASSERT_TRUE(svr.is_valid());
  12783. svr.Get("/test", [](const Request &, Response &res) {
  12784. res.set_content("ok", "text/plain");
  12785. });
  12786. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12787. auto se = detail::scope_exit([&] {
  12788. svr.stop();
  12789. t.join();
  12790. });
  12791. svr.wait_until_ready();
  12792. SSLClient cli(HOST, PORT);
  12793. cli.enable_server_certificate_verification(false);
  12794. cli.set_connection_timeout(30);
  12795. bool serial_checked = false;
  12796. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12797. if (ctx.cert) {
  12798. std::string serial = ctx.serial();
  12799. EXPECT_FALSE(serial.empty());
  12800. // Serial should be a hex string
  12801. for (char c : serial) {
  12802. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12803. (c >= 'a' && c <= 'f'));
  12804. }
  12805. serial_checked = true;
  12806. }
  12807. return true;
  12808. });
  12809. auto res = cli.Get("/test");
  12810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12811. EXPECT_TRUE(serial_checked);
  12812. }
  12813. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12814. // Test 1: Valid CA file - no error should be recorded
  12815. {
  12816. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12817. CLIENT_CA_CERT_FILE);
  12818. ASSERT_TRUE(svr.is_valid());
  12819. // With valid setup, last_ssl_error should be 0
  12820. EXPECT_EQ(0, svr.ssl_last_error());
  12821. }
  12822. // Test 2: Invalid CA file content
  12823. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12824. {
  12825. // Create a temporary file with completely invalid content
  12826. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12827. {
  12828. std::ofstream ofs(temp_invalid_ca);
  12829. ofs << "This is not a certificate file at all\n";
  12830. ofs << "Just plain text content\n";
  12831. }
  12832. // Create server with invalid CA file
  12833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12834. // Clean up temporary file
  12835. std::remove(temp_invalid_ca);
  12836. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12837. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12838. // Note: SSL_CTX_load_verify_locations typically fails first,
  12839. // but our error handling code path is still exercised
  12840. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12841. }
  12842. }
  12843. TEST(VerifyCallbackTest, VerifyContextFields) {
  12844. using namespace httplib::tls;
  12845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12846. ASSERT_TRUE(svr.is_valid());
  12847. svr.Get("/test", [](const Request &, Response &res) {
  12848. res.set_content("ok", "text/plain");
  12849. });
  12850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12851. auto se = detail::scope_exit([&] {
  12852. svr.stop();
  12853. t.join();
  12854. });
  12855. svr.wait_until_ready();
  12856. SSLClient cli(HOST, PORT);
  12857. cli.enable_server_certificate_verification(false);
  12858. cli.set_connection_timeout(30);
  12859. int callback_count = 0;
  12860. bool saw_leaf_cert = false;
  12861. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12862. if (ctx.cert) {
  12863. callback_count++;
  12864. // We should see at least one certificate (the leaf)
  12865. std::string cn = ctx.subject_cn();
  12866. if (!cn.empty()) { saw_leaf_cert = true; }
  12867. // Verify context fields are populated
  12868. EXPECT_NE(ctx.session, nullptr);
  12869. EXPECT_GE(ctx.depth, 0);
  12870. }
  12871. return true;
  12872. });
  12873. auto res = cli.Get("/test");
  12874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12875. EXPECT_GT(callback_count, 0);
  12876. EXPECT_TRUE(saw_leaf_cert);
  12877. }
  12878. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12879. using httplib::tls::TlsError;
  12880. // Test that verify_error_to_string returns empty for success
  12881. std::string success_str = TlsError::verify_error_to_string(0);
  12882. EXPECT_TRUE(success_str.empty());
  12883. // Test that verify_error_to_string returns non-empty for error codes
  12884. // Using a common error code (certificate expired)
  12885. std::string error_str =
  12886. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12887. EXPECT_FALSE(error_str.empty());
  12888. }
  12889. TEST(SessionVerifierTest, CertificateAccepted) {
  12890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12891. ASSERT_TRUE(svr.is_valid());
  12892. svr.Get("/test", [](const Request &, Response &res) {
  12893. res.set_content("ok", "text/plain");
  12894. });
  12895. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12896. auto se = detail::scope_exit([&] {
  12897. svr.stop();
  12898. t.join();
  12899. });
  12900. svr.wait_until_ready();
  12901. SSLClient cli(HOST, PORT);
  12902. cli.enable_server_certificate_verification(false);
  12903. cli.set_connection_timeout(30);
  12904. bool callback_called = false;
  12905. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12906. EXPECT_NE(session, nullptr);
  12907. callback_called = true;
  12908. return SSLVerifierResponse::CertificateAccepted;
  12909. });
  12910. auto res = cli.Get("/test");
  12911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12912. EXPECT_EQ(200, res->status);
  12913. EXPECT_TRUE(callback_called);
  12914. }
  12915. TEST(SessionVerifierTest, CertificateRejected) {
  12916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12917. ASSERT_TRUE(svr.is_valid());
  12918. svr.Get("/test", [](const Request &, Response &res) {
  12919. res.set_content("ok", "text/plain");
  12920. });
  12921. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12922. auto se = detail::scope_exit([&] {
  12923. svr.stop();
  12924. t.join();
  12925. });
  12926. svr.wait_until_ready();
  12927. SSLClient cli(HOST, PORT);
  12928. cli.enable_server_certificate_verification(false);
  12929. cli.set_connection_timeout(30);
  12930. bool callback_called = false;
  12931. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12932. EXPECT_NE(session, nullptr);
  12933. callback_called = true;
  12934. return SSLVerifierResponse::CertificateRejected;
  12935. });
  12936. auto res = cli.Get("/test");
  12937. EXPECT_FALSE(res);
  12938. EXPECT_TRUE(callback_called);
  12939. }
  12940. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12941. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12942. ASSERT_TRUE(svr.is_valid());
  12943. svr.Get("/test", [](const Request &, Response &res) {
  12944. res.set_content("ok", "text/plain");
  12945. });
  12946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12947. auto se = detail::scope_exit([&] {
  12948. svr.stop();
  12949. t.join();
  12950. });
  12951. svr.wait_until_ready();
  12952. // NoDecisionMade with verification disabled should succeed (no default check)
  12953. SSLClient cli(HOST, PORT);
  12954. cli.enable_server_certificate_verification(false);
  12955. cli.set_connection_timeout(30);
  12956. bool callback_called = false;
  12957. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12958. EXPECT_NE(session, nullptr);
  12959. callback_called = true;
  12960. return SSLVerifierResponse::NoDecisionMade;
  12961. });
  12962. auto res = cli.Get("/test");
  12963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12964. EXPECT_EQ(200, res->status);
  12965. EXPECT_TRUE(callback_called);
  12966. }
  12967. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12968. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12969. ASSERT_TRUE(svr.is_valid());
  12970. svr.Get("/test", [](const Request &, Response &res) {
  12971. res.set_content("ok", "text/plain");
  12972. });
  12973. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12974. auto se = detail::scope_exit([&] {
  12975. svr.stop();
  12976. t.join();
  12977. });
  12978. svr.wait_until_ready();
  12979. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12980. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12981. // so we only check that the request fails, not whether the callback was
  12982. // called.
  12983. SSLClient cli(HOST, PORT);
  12984. cli.enable_server_certificate_verification(true);
  12985. cli.set_connection_timeout(30);
  12986. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12987. EXPECT_NE(session, nullptr);
  12988. return SSLVerifierResponse::NoDecisionMade;
  12989. });
  12990. auto res = cli.Get("/test");
  12991. EXPECT_FALSE(res);
  12992. }
  12993. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12994. // Test SSL server using PemMemory constructor with client CA certificates
  12995. // Read PEM files
  12996. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12997. read_file(SERVER_CERT_FILE, server_cert_pem);
  12998. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12999. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13000. // Create SSLServer with PemMemory constructor including client CA
  13001. SSLServer::PemMemory server_pem = {
  13002. server_cert_pem.c_str(),
  13003. server_cert_pem.size(),
  13004. server_key_pem.c_str(),
  13005. server_key_pem.size(),
  13006. client_ca_pem.c_str(),
  13007. client_ca_pem.size(),
  13008. nullptr // no password for server key
  13009. };
  13010. SSLServer svr(server_pem);
  13011. ASSERT_TRUE(svr.is_valid());
  13012. // No SSL error should be recorded for valid setup
  13013. EXPECT_EQ(0, svr.ssl_last_error());
  13014. // Set up server endpoints
  13015. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13016. res.set_content("ok", "text/plain");
  13017. });
  13018. // Start server in a thread
  13019. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13020. svr.wait_until_ready();
  13021. // Connect with client certificate (using constructor with paths)
  13022. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13023. cli.enable_server_certificate_verification(false);
  13024. auto res = cli.Get("/test-pem-ca");
  13025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13026. EXPECT_EQ(200, res->status);
  13027. EXPECT_EQ("ok", res->body);
  13028. svr.stop();
  13029. server_thread.join();
  13030. }
  13031. #endif
  13032. #ifdef _WIN32
  13033. TEST(CleanupTest, WSACleanup) {
  13034. int ret = WSACleanup();
  13035. ASSERT_EQ(0, ret);
  13036. }
  13037. #endif
  13038. #ifndef CPPHTTPLIB_SSL_ENABLED
  13039. TEST(NoSSLSupport, SimpleInterface) {
  13040. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13041. }
  13042. #endif
  13043. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13044. TEST(InvalidScheme, SimpleInterface) {
  13045. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13046. }
  13047. #endif
  13048. TEST(NoScheme, SimpleInterface) {
  13049. Client cli("yahoo.com:80");
  13050. ASSERT_TRUE(cli.is_valid());
  13051. }
  13052. TEST(SendAPI, SimpleInterface_Online) {
  13053. Client cli("http://yahoo.com");
  13054. Request req;
  13055. req.method = "GET";
  13056. req.path = "/";
  13057. auto res = cli.send(req);
  13058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13059. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13060. }
  13061. TEST(SendAPI, WithParamsInRequest) {
  13062. Server svr;
  13063. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13064. EXPECT_TRUE(req.has_param("test"));
  13065. EXPECT_EQ("test_value", req.get_param_value("test"));
  13066. });
  13067. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13068. auto se = detail::scope_exit([&] {
  13069. svr.stop();
  13070. t.join();
  13071. ASSERT_FALSE(svr.is_running());
  13072. });
  13073. svr.wait_until_ready();
  13074. Client cli(HOST, PORT);
  13075. {
  13076. Request req;
  13077. req.method = "GET";
  13078. req.path = "/";
  13079. req.params.emplace("test", "test_value");
  13080. auto res = cli.send(req);
  13081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13082. }
  13083. {
  13084. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13086. }
  13087. }
  13088. TEST(ClientImplMethods, GetSocketTest) {
  13089. httplib::Server svr;
  13090. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13091. res.status = StatusCode::OK_200;
  13092. });
  13093. auto port = svr.bind_to_any_port("127.0.0.1");
  13094. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13095. auto se = detail::scope_exit([&] {
  13096. svr.stop();
  13097. thread.join();
  13098. ASSERT_FALSE(svr.is_running());
  13099. });
  13100. svr.wait_until_ready();
  13101. {
  13102. httplib::Client cli("127.0.0.1", port);
  13103. cli.set_keep_alive(true);
  13104. // Use the behavior of cpp-httplib of opening the connection
  13105. // only when the first request happens. If that changes,
  13106. // this test would be obsolete.
  13107. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13108. // This also implicitly tests the server. But other tests would fail much
  13109. // earlier than this one to be considered.
  13110. auto res = cli.Get("/");
  13111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13112. EXPECT_EQ(StatusCode::OK_200, res->status);
  13113. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13114. }
  13115. }
  13116. #ifdef CPPHTTPLIB_SSL_ENABLED
  13117. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13118. Client cli("http://yahoo.com");
  13119. auto res = cli.Get("/");
  13120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13121. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13122. cli.set_follow_location(true);
  13123. res = cli.Get("/");
  13124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13125. EXPECT_EQ(StatusCode::OK_200, res->status);
  13126. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13127. }
  13128. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13129. Client cli("https://yahoo.com");
  13130. auto res = cli.Get("/");
  13131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13132. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13133. cli.set_follow_location(true);
  13134. res = cli.Get("/");
  13135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13136. EXPECT_EQ(StatusCode::OK_200, res->status);
  13137. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13138. }
  13139. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13140. Client cli("https://yahoo.com");
  13141. auto res = cli.Get("/");
  13142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13143. ASSERT_FALSE(!res);
  13144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13145. ASSERT_FALSE(res == nullptr);
  13146. ASSERT_TRUE(res != nullptr);
  13147. EXPECT_EQ(Error::Success, res.error());
  13148. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13149. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13150. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13151. cli.set_follow_location(true);
  13152. res = cli.Get("/");
  13153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13154. EXPECT_EQ(Error::Success, res.error());
  13155. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13156. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13157. EXPECT_EQ(StatusCode::OK_200, res->status);
  13158. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13159. }
  13160. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13161. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13162. Client cli("https://cdnjs.cloudflare.com");
  13163. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13164. Headers{{"Accept-Encoding", "br"}});
  13165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13166. EXPECT_EQ(StatusCode::OK_200, res->status);
  13167. EXPECT_EQ(287630U, res->body.size());
  13168. EXPECT_EQ("application/javascript; charset=utf-8",
  13169. res->get_header_value("Content-Type"));
  13170. }
  13171. #endif
  13172. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13173. #undef REDIR_HOST // Silence compiler warning
  13174. #define REDIR_HOST "https://httpbingo.org"
  13175. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13176. Client cli(REDIR_HOST);
  13177. cli.set_follow_location(true);
  13178. auto res =
  13179. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13181. EXPECT_EQ(StatusCode::OK_200, res->status);
  13182. }
  13183. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13184. Client cli(REDIR_HOST);
  13185. cli.set_follow_location(true);
  13186. Params params;
  13187. params.emplace("url", "http://example.com");
  13188. params.emplace("status_code", "302");
  13189. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13191. EXPECT_EQ(StatusCode::OK_200, res->status);
  13192. }
  13193. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13194. Client cli(REDIR_HOST);
  13195. cli.set_follow_location(true);
  13196. Params params;
  13197. params.emplace("url", "http://example.com");
  13198. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13200. EXPECT_EQ(StatusCode::OK_200, res->status);
  13201. }
  13202. TEST(HttpToHttpsRedirectTest, CertFile) {
  13203. auto ssl_port = PORT + 1;
  13204. Server svr;
  13205. ASSERT_TRUE(svr.is_valid());
  13206. svr.Get("/index", [&](const Request &, Response &res) {
  13207. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13208. "/index");
  13209. svr.stop();
  13210. });
  13211. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13212. ASSERT_TRUE(ssl_svr.is_valid());
  13213. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13214. res.set_content("test", "text/plain");
  13215. ssl_svr.stop();
  13216. });
  13217. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13218. thread t2 =
  13219. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13220. auto se = detail::scope_exit([&] {
  13221. t2.join();
  13222. t.join();
  13223. ASSERT_FALSE(svr.is_running());
  13224. });
  13225. svr.wait_until_ready();
  13226. ssl_svr.wait_until_ready();
  13227. Client cli("127.0.0.1", PORT);
  13228. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13229. cli.enable_server_certificate_verification(true);
  13230. cli.set_follow_location(true);
  13231. cli.set_connection_timeout(30);
  13232. auto res = cli.Get("/index");
  13233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13234. ASSERT_EQ(StatusCode::OK_200, res->status);
  13235. }
  13236. TEST(SSLClientRedirectTest, CertFile) {
  13237. auto ssl_port = PORT + 1;
  13238. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13239. ASSERT_TRUE(ssl_svr1.is_valid());
  13240. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13241. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13242. "/index");
  13243. ssl_svr1.stop();
  13244. });
  13245. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13246. ASSERT_TRUE(ssl_svr2.is_valid());
  13247. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13248. res.set_content("test", "text/plain");
  13249. ssl_svr2.stop();
  13250. });
  13251. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13252. thread t2 =
  13253. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13254. auto se = detail::scope_exit([&] {
  13255. t2.join();
  13256. t.join();
  13257. ASSERT_FALSE(ssl_svr1.is_running());
  13258. });
  13259. ssl_svr1.wait_until_ready();
  13260. ssl_svr2.wait_until_ready();
  13261. SSLClient cli("127.0.0.1", PORT);
  13262. std::string cert;
  13263. read_file(SERVER_CERT2_FILE, cert);
  13264. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13265. cli.enable_server_certificate_verification(true);
  13266. cli.set_follow_location(true);
  13267. cli.set_connection_timeout(30);
  13268. auto res = cli.Get("/index");
  13269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13270. ASSERT_EQ(StatusCode::OK_200, res->status);
  13271. }
  13272. #endif
  13273. #ifdef CPPHTTPLIB_SSL_ENABLED
  13274. // Test that set_ca_cert_store() skips system certs (consistent with
  13275. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  13276. // should be trusted - system certs should NOT be loaded.
  13277. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  13278. // Load a specific cert that is NOT a system CA cert
  13279. std::string cert;
  13280. read_file(SERVER_CERT2_FILE, cert);
  13281. SSLClient cli("google.com");
  13282. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13283. cli.enable_server_certificate_verification(true);
  13284. // This should FAIL because:
  13285. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  13286. // 2. System certs should NOT be loaded when custom store is set
  13287. // If system certs WERE loaded, this would succeed
  13288. auto res = cli.Get("/");
  13289. ASSERT_FALSE(res);
  13290. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13291. }
  13292. // Same as above, but through the native store handle path. Regression test:
  13293. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  13294. // merged system certs into the user-provided store.
  13295. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  13296. std::string cert;
  13297. read_file(SERVER_CERT2_FILE, cert);
  13298. SSLClient cli("google.com");
  13299. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13300. cli.enable_server_certificate_verification(true);
  13301. auto res = cli.Get("/");
  13302. ASSERT_FALSE(res);
  13303. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13304. }
  13305. // A custom store set via the native handle must still verify a server whose
  13306. // cert it does contain.
  13307. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  13308. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13309. ASSERT_TRUE(svr.is_valid());
  13310. svr.Get("/test", [&](const Request &, Response &res) {
  13311. res.set_content("test", "text/plain");
  13312. });
  13313. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13314. auto se = detail::scope_exit([&] {
  13315. svr.stop();
  13316. t.join();
  13317. ASSERT_FALSE(svr.is_running());
  13318. });
  13319. svr.wait_until_ready();
  13320. SSLClient cli("127.0.0.1", PORT);
  13321. std::string cert;
  13322. read_file(SERVER_CERT2_FILE, cert);
  13323. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  13324. cli.enable_server_certificate_verification(true);
  13325. cli.set_connection_timeout(30);
  13326. auto res = cli.Get("/test");
  13327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13328. ASSERT_EQ(StatusCode::OK_200, res->status);
  13329. }
  13330. // CA certs loaded through the universal Client must be transferred to the
  13331. // client created internally for following an HTTPS redirect. Regression test:
  13332. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  13333. // the CA data for redirect transfer.
  13334. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  13335. auto ssl_port = PORT + 1;
  13336. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13337. ASSERT_TRUE(ssl_svr1.is_valid());
  13338. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13339. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13340. "/index");
  13341. });
  13342. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13343. ASSERT_TRUE(ssl_svr2.is_valid());
  13344. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13345. res.set_content("test", "text/plain");
  13346. });
  13347. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13348. thread t2 =
  13349. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13350. auto se = detail::scope_exit([&] {
  13351. ssl_svr2.stop();
  13352. ssl_svr1.stop();
  13353. t2.join();
  13354. t.join();
  13355. ASSERT_FALSE(ssl_svr1.is_running());
  13356. });
  13357. ssl_svr1.wait_until_ready();
  13358. ssl_svr2.wait_until_ready();
  13359. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13360. std::string cert;
  13361. read_file(SERVER_CERT2_FILE, cert);
  13362. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13363. cli.enable_server_certificate_verification(true);
  13364. cli.set_follow_location(true);
  13365. cli.set_connection_timeout(30);
  13366. auto res = cli.Get("/index");
  13367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13368. ASSERT_EQ(StatusCode::OK_200, res->status);
  13369. }
  13370. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  13371. // so a host signed by a system CA verifies even though a custom CA is set
  13372. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  13373. std::string cert;
  13374. read_file(SERVER_CERT2_FILE, cert);
  13375. SSLClient cli("google.com");
  13376. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13377. cli.enable_system_ca(true);
  13378. cli.enable_server_certificate_verification(true);
  13379. auto res = cli.Get("/");
  13380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13381. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13382. }
  13383. // The custom CA remains effective when combined with the system CA
  13384. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  13385. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13386. ASSERT_TRUE(svr.is_valid());
  13387. svr.Get("/test", [&](const Request &, Response &res) {
  13388. res.set_content("test", "text/plain");
  13389. });
  13390. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13391. auto se = detail::scope_exit([&] {
  13392. svr.stop();
  13393. t.join();
  13394. ASSERT_FALSE(svr.is_running());
  13395. });
  13396. svr.wait_until_ready();
  13397. SSLClient cli("127.0.0.1", PORT);
  13398. std::string cert;
  13399. read_file(SERVER_CERT2_FILE, cert);
  13400. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13401. cli.enable_system_ca(true);
  13402. cli.enable_server_certificate_verification(true);
  13403. cli.set_connection_timeout(30);
  13404. auto res = cli.Get("/test");
  13405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13406. ASSERT_EQ(StatusCode::OK_200, res->status);
  13407. }
  13408. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13409. // skip chain verification entirely (only the certificate identity was
  13410. // checked), so a server presenting an untrusted certificate with a matching
  13411. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13412. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13413. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13414. ASSERT_TRUE(svr.is_valid());
  13415. svr.Get("/test", [&](const Request &, Response &res) {
  13416. res.set_content("test", "text/plain");
  13417. });
  13418. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13419. auto se = detail::scope_exit([&] {
  13420. svr.stop();
  13421. t.join();
  13422. ASSERT_FALSE(svr.is_running());
  13423. });
  13424. svr.wait_until_ready();
  13425. SSLClient cli("127.0.0.1", PORT);
  13426. std::string cert;
  13427. // A trusted CA that did not sign the server certificate. The server cert
  13428. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13429. // this connection.
  13430. read_file(CLIENT_CA_CERT_FILE, cert);
  13431. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13432. cli.enable_server_certificate_verification(true);
  13433. cli.set_connection_timeout(30);
  13434. auto res = cli.Get("/test");
  13435. ASSERT_FALSE(res);
  13436. }
  13437. // enable_system_ca(false) prevents system CA loading entirely
  13438. TEST(SSLClientTest, DisableSystemCa_Online) {
  13439. SSLClient cli("google.com");
  13440. cli.enable_system_ca(false);
  13441. cli.enable_server_certificate_verification(true);
  13442. auto res = cli.Get("/");
  13443. ASSERT_FALSE(res);
  13444. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13445. // itself when the CA chain is empty
  13446. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13447. res.error() == Error::SSLConnection);
  13448. }
  13449. // The universal Client forwards enable_system_ca()
  13450. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13451. std::string cert;
  13452. read_file(SERVER_CERT2_FILE, cert);
  13453. Client cli("https://google.com");
  13454. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13455. cli.enable_system_ca(true);
  13456. cli.enable_server_certificate_verification(true);
  13457. auto res = cli.Get("/");
  13458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13459. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13460. }
  13461. // The system CA policy must carry over to the client created internally for
  13462. // following a cross-host HTTPS redirect
  13463. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13464. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13465. ASSERT_TRUE(svr.is_valid());
  13466. svr.Get("/index", [&](const Request &, Response &res) {
  13467. res.set_redirect("https://www.google.com/");
  13468. });
  13469. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13470. auto se = detail::scope_exit([&] {
  13471. svr.stop();
  13472. t.join();
  13473. ASSERT_FALSE(svr.is_running());
  13474. });
  13475. svr.wait_until_ready();
  13476. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13477. std::string cert;
  13478. read_file(SERVER_CERT2_FILE, cert);
  13479. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13480. cli.enable_system_ca(true);
  13481. cli.enable_server_certificate_verification(true);
  13482. cli.set_follow_location(true);
  13483. cli.set_connection_timeout(30);
  13484. // Receiving any response proves the redirect client completed the TLS
  13485. // handshake with a system-CA-signed host
  13486. auto res = cli.Get("/index");
  13487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13488. }
  13489. TEST(MultipartFormDataTest, LargeData) {
  13490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13491. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13492. const ContentReader &content_reader) {
  13493. if (req.is_multipart_form_data()) {
  13494. std::vector<FormData> items;
  13495. content_reader(
  13496. [&](const FormData &file) {
  13497. items.push_back(file);
  13498. return true;
  13499. },
  13500. [&](const char *data, size_t data_length) {
  13501. items.back().content.append(data, data_length);
  13502. return true;
  13503. });
  13504. EXPECT_TRUE(std::string(items[0].name) == "document");
  13505. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13506. EXPECT_TRUE(items[0].filename == "2MB_data");
  13507. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13508. EXPECT_TRUE(items[1].name == "hello");
  13509. EXPECT_TRUE(items[1].content == "world");
  13510. EXPECT_TRUE(items[1].filename == "");
  13511. EXPECT_TRUE(items[1].content_type == "");
  13512. } else {
  13513. std::string body;
  13514. content_reader([&](const char *data, size_t data_length) {
  13515. body.append(data, data_length);
  13516. return true;
  13517. });
  13518. }
  13519. });
  13520. auto port = svr.bind_to_any_port(HOST);
  13521. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13522. auto se = detail::scope_exit([&] {
  13523. svr.stop();
  13524. t.join();
  13525. ASSERT_FALSE(svr.is_running());
  13526. });
  13527. svr.wait_until_ready();
  13528. {
  13529. std::string data(1024 * 1024 * 2, '.');
  13530. std::stringstream buffer;
  13531. buffer << data;
  13532. SSLClient cli(HOST, port);
  13533. cli.enable_server_certificate_verification(false);
  13534. UploadFormDataItems items{
  13535. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13536. {"hello", "world", "", ""},
  13537. };
  13538. auto res = cli.Post("/post", items);
  13539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13540. ASSERT_EQ(StatusCode::OK_200, res->status);
  13541. }
  13542. }
  13543. TEST(MultipartFormDataTest, DataProviderItems) {
  13544. std::random_device seed_gen;
  13545. std::mt19937 random(seed_gen());
  13546. std::string rand1;
  13547. rand1.resize(1000);
  13548. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13549. std::string rand2;
  13550. rand2.resize(3000);
  13551. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13553. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13554. const ContentReader &content_reader) {
  13555. ASSERT_FALSE(req.is_multipart_form_data());
  13556. std::string body;
  13557. content_reader([&](const char *data, size_t data_length) {
  13558. body.append(data, data_length);
  13559. return true;
  13560. });
  13561. EXPECT_EQ(body, "");
  13562. });
  13563. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13564. const ContentReader &content_reader) {
  13565. ASSERT_TRUE(req.is_multipart_form_data());
  13566. std::vector<FormData> items;
  13567. content_reader(
  13568. [&](const FormData &file) {
  13569. items.push_back(file);
  13570. return true;
  13571. },
  13572. [&](const char *data, size_t data_length) {
  13573. items.back().content.append(data, data_length);
  13574. return true;
  13575. });
  13576. ASSERT_TRUE(items.size() == 2);
  13577. EXPECT_EQ(std::string(items[0].name), "name1");
  13578. EXPECT_EQ(items[0].content, "Testing123");
  13579. EXPECT_EQ(items[0].filename, "filename1");
  13580. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13581. EXPECT_EQ(items[1].name, "name2");
  13582. EXPECT_EQ(items[1].content, "Testing456");
  13583. EXPECT_EQ(items[1].filename, "");
  13584. EXPECT_EQ(items[1].content_type, "");
  13585. });
  13586. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13587. const ContentReader &content_reader) {
  13588. ASSERT_TRUE(req.is_multipart_form_data());
  13589. std::vector<FormData> items;
  13590. content_reader(
  13591. [&](const FormData &file) {
  13592. items.push_back(file);
  13593. return true;
  13594. },
  13595. [&](const char *data, size_t data_length) {
  13596. items.back().content.append(data, data_length);
  13597. return true;
  13598. });
  13599. ASSERT_TRUE(items.size() == 2);
  13600. EXPECT_EQ(items[0].name, "name3");
  13601. EXPECT_EQ(items[0].content, rand1);
  13602. EXPECT_EQ(items[0].filename, "filename3");
  13603. EXPECT_EQ(items[0].content_type, "");
  13604. EXPECT_EQ(items[1].name, "name4");
  13605. EXPECT_EQ(items[1].content, rand2);
  13606. EXPECT_EQ(items[1].filename, "filename4");
  13607. EXPECT_EQ(items[1].content_type, "");
  13608. });
  13609. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13610. const ContentReader &content_reader) {
  13611. ASSERT_TRUE(req.is_multipart_form_data());
  13612. std::vector<FormData> items;
  13613. content_reader(
  13614. [&](const FormData &file) {
  13615. items.push_back(file);
  13616. return true;
  13617. },
  13618. [&](const char *data, size_t data_length) {
  13619. items.back().content.append(data, data_length);
  13620. return true;
  13621. });
  13622. ASSERT_TRUE(items.size() == 4);
  13623. EXPECT_EQ(std::string(items[0].name), "name1");
  13624. EXPECT_EQ(items[0].content, "Testing123");
  13625. EXPECT_EQ(items[0].filename, "filename1");
  13626. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13627. EXPECT_EQ(items[1].name, "name2");
  13628. EXPECT_EQ(items[1].content, "Testing456");
  13629. EXPECT_EQ(items[1].filename, "");
  13630. EXPECT_EQ(items[1].content_type, "");
  13631. EXPECT_EQ(items[2].name, "name3");
  13632. EXPECT_EQ(items[2].content, rand1);
  13633. EXPECT_EQ(items[2].filename, "filename3");
  13634. EXPECT_EQ(items[2].content_type, "");
  13635. EXPECT_EQ(items[3].name, "name4");
  13636. EXPECT_EQ(items[3].content, rand2);
  13637. EXPECT_EQ(items[3].filename, "filename4");
  13638. EXPECT_EQ(items[3].content_type, "");
  13639. });
  13640. auto port = svr.bind_to_any_port("localhost");
  13641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13642. auto se = detail::scope_exit([&] {
  13643. svr.stop();
  13644. t.join();
  13645. ASSERT_FALSE(svr.is_running());
  13646. });
  13647. svr.wait_until_ready();
  13648. {
  13649. SSLClient cli("localhost", port);
  13650. cli.enable_server_certificate_verification(false);
  13651. UploadFormDataItems items{
  13652. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13653. {"name2", "Testing456", "", ""}, // not a file
  13654. };
  13655. {
  13656. auto res = cli.Post("/post-none", {}, {}, {});
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. ASSERT_EQ(StatusCode::OK_200, res->status);
  13659. }
  13660. FormDataProviderItems providers;
  13661. {
  13662. auto res =
  13663. cli.Post("/post-items", {}, items, providers); // empty providers
  13664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13665. ASSERT_EQ(StatusCode::OK_200, res->status);
  13666. }
  13667. providers.push_back({"name3",
  13668. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13669. // test the offset is given correctly at each step
  13670. if (!offset)
  13671. sink.os.write(rand1.data(), 30);
  13672. else if (offset == 30)
  13673. sink.os.write(rand1.data() + 30, 300);
  13674. else if (offset == 330)
  13675. sink.os.write(rand1.data() + 330, 670);
  13676. else if (offset == rand1.size())
  13677. sink.done();
  13678. return true;
  13679. },
  13680. "filename3",
  13681. {}});
  13682. providers.push_back({"name4",
  13683. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13684. // test the offset is given correctly at each step
  13685. if (!offset)
  13686. sink.os.write(rand2.data(), 2000);
  13687. else if (offset == 2000)
  13688. sink.os.write(rand2.data() + 2000, 1);
  13689. else if (offset == 2001)
  13690. sink.os.write(rand2.data() + 2001, 999);
  13691. else if (offset == rand2.size())
  13692. sink.done();
  13693. return true;
  13694. },
  13695. "filename4",
  13696. {}});
  13697. {
  13698. auto res = cli.Post("/post-providers", {}, {}, providers);
  13699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13700. ASSERT_EQ(StatusCode::OK_200, res->status);
  13701. }
  13702. {
  13703. auto res = cli.Post("/post-both", {}, items, providers);
  13704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13705. ASSERT_EQ(StatusCode::OK_200, res->status);
  13706. }
  13707. }
  13708. }
  13709. TEST(MultipartFormDataTest, BadHeader) {
  13710. Server svr;
  13711. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13712. res.set_content("ok", "text/plain");
  13713. });
  13714. thread t = thread([&] { svr.listen(HOST, PORT); });
  13715. auto se = detail::scope_exit([&] {
  13716. svr.stop();
  13717. t.join();
  13718. ASSERT_FALSE(svr.is_running());
  13719. });
  13720. svr.wait_until_ready();
  13721. const std::string body =
  13722. "This is the preamble. It is to be ignored, though it\r\n"
  13723. "is a handy place for composition agents to include an\r\n"
  13724. "explanatory note to non-MIME conformant readers.\r\n"
  13725. "\r\n"
  13726. "\r\n"
  13727. "--simple boundary\r\n"
  13728. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13729. ": BAD...\r\n"
  13730. "\r\n"
  13731. "value1\r\n"
  13732. "--simple boundary\r\n"
  13733. "Content-Disposition: form-data; name=\"field2\"; "
  13734. "filename=\"example.txt\"\r\n"
  13735. "\r\n"
  13736. "value2\r\n"
  13737. "--simple boundary--\r\n"
  13738. "This is the epilogue. It is also to be ignored.\r\n";
  13739. std::string content_type =
  13740. R"(multipart/form-data; boundary="simple boundary")";
  13741. Client cli(HOST, PORT);
  13742. auto res = cli.Post("/post", body, content_type.c_str());
  13743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13744. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13745. }
  13746. TEST(MultipartFormDataTest, WithPreamble) {
  13747. Server svr;
  13748. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13749. res.set_content("ok", "text/plain");
  13750. });
  13751. thread t = thread([&] { svr.listen(HOST, PORT); });
  13752. auto se = detail::scope_exit([&] {
  13753. svr.stop();
  13754. t.join();
  13755. ASSERT_FALSE(svr.is_running());
  13756. });
  13757. svr.wait_until_ready();
  13758. const std::string body =
  13759. "This is the preamble. It is to be ignored, though it\r\n"
  13760. "is a handy place for composition agents to include an\r\n"
  13761. "explanatory note to non-MIME conformant readers.\r\n"
  13762. "\r\n"
  13763. "\r\n"
  13764. "--simple boundary\r\n"
  13765. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13766. "\r\n"
  13767. "value1\r\n"
  13768. "--simple boundary\r\n"
  13769. "Content-Disposition: form-data; name=\"field2\"; "
  13770. "filename=\"example.txt\"\r\n"
  13771. "\r\n"
  13772. "value2\r\n"
  13773. "--simple boundary--\r\n"
  13774. "This is the epilogue. It is also to be ignored.\r\n";
  13775. std::string content_type =
  13776. R"(multipart/form-data; boundary="simple boundary")";
  13777. Client cli(HOST, PORT);
  13778. auto res = cli.Post("/post", body, content_type.c_str());
  13779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13780. EXPECT_EQ(StatusCode::OK_200, res->status);
  13781. }
  13782. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13784. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13785. const ContentReader &content_reader) {
  13786. if (req.is_multipart_form_data()) {
  13787. std::vector<FormData> items;
  13788. content_reader(
  13789. [&](const FormData &file) {
  13790. items.push_back(file);
  13791. return true;
  13792. },
  13793. [&](const char *data, size_t data_length) {
  13794. items.back().content.append(data, data_length);
  13795. return true;
  13796. });
  13797. EXPECT_TRUE(std::string(items[0].name) == "document");
  13798. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13799. EXPECT_TRUE(items[0].filename == "2MB_data");
  13800. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13801. EXPECT_TRUE(items[1].name == "hello");
  13802. EXPECT_TRUE(items[1].content == "world");
  13803. EXPECT_TRUE(items[1].filename == "");
  13804. EXPECT_TRUE(items[1].content_type == "");
  13805. } else {
  13806. std::string body;
  13807. content_reader([&](const char *data, size_t data_length) {
  13808. body.append(data, data_length);
  13809. return true;
  13810. });
  13811. }
  13812. });
  13813. auto port = svr.bind_to_any_port("localhost");
  13814. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13815. auto se = detail::scope_exit([&] {
  13816. svr.stop();
  13817. t.join();
  13818. ASSERT_FALSE(svr.is_running());
  13819. });
  13820. svr.wait_until_ready();
  13821. {
  13822. std::string data(1024 * 1024 * 2, '.');
  13823. std::stringstream buffer;
  13824. buffer << data;
  13825. SSLClient cli("localhost", port);
  13826. cli.enable_server_certificate_verification(false);
  13827. UploadFormDataItems items{
  13828. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13829. {"hello", "world", "", ""},
  13830. };
  13831. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13833. ASSERT_EQ(StatusCode::OK_200, res->status);
  13834. }
  13835. }
  13836. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13837. std::string data(1024 * 1024 * 2, '&');
  13838. std::stringstream buffer;
  13839. buffer << data;
  13840. Client cli("https://localhost:8080");
  13841. UploadFormDataItems items{
  13842. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13843. {"hello", "world", "", ""},
  13844. };
  13845. for (const char &c : " \t\r\n") {
  13846. auto res =
  13847. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13848. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13849. ASSERT_FALSE(res);
  13850. }
  13851. }
  13852. TEST(MultipartFormDataTest, PutFormData) {
  13853. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13854. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13855. const ContentReader &content_reader) {
  13856. if (req.is_multipart_form_data()) {
  13857. std::vector<FormData> items;
  13858. content_reader(
  13859. [&](const FormData &file) {
  13860. items.push_back(file);
  13861. return true;
  13862. },
  13863. [&](const char *data, size_t data_length) {
  13864. items.back().content.append(data, data_length);
  13865. return true;
  13866. });
  13867. EXPECT_TRUE(std::string(items[0].name) == "document");
  13868. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13869. EXPECT_TRUE(items[0].filename == "2MB_data");
  13870. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13871. EXPECT_TRUE(items[1].name == "hello");
  13872. EXPECT_TRUE(items[1].content == "world");
  13873. EXPECT_TRUE(items[1].filename == "");
  13874. EXPECT_TRUE(items[1].content_type == "");
  13875. } else {
  13876. std::string body;
  13877. content_reader([&](const char *data, size_t data_length) {
  13878. body.append(data, data_length);
  13879. return true;
  13880. });
  13881. }
  13882. });
  13883. auto port = svr.bind_to_any_port("localhost");
  13884. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13885. auto se = detail::scope_exit([&] {
  13886. svr.stop();
  13887. t.join();
  13888. ASSERT_FALSE(svr.is_running());
  13889. });
  13890. svr.wait_until_ready();
  13891. {
  13892. std::string data(1024 * 1024 * 2, '&');
  13893. std::stringstream buffer;
  13894. buffer << data;
  13895. SSLClient cli("localhost", port);
  13896. cli.enable_server_certificate_verification(false);
  13897. UploadFormDataItems items{
  13898. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13899. {"hello", "world", "", ""},
  13900. };
  13901. auto res = cli.Put("/put", items);
  13902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13903. ASSERT_EQ(StatusCode::OK_200, res->status);
  13904. }
  13905. }
  13906. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13908. svr.Put("/put_customboundary",
  13909. [&](const Request &req, const Response & /*res*/,
  13910. const ContentReader &content_reader) {
  13911. if (req.is_multipart_form_data()) {
  13912. std::vector<FormData> items;
  13913. content_reader(
  13914. [&](const FormData &file) {
  13915. items.push_back(file);
  13916. return true;
  13917. },
  13918. [&](const char *data, size_t data_length) {
  13919. items.back().content.append(data, data_length);
  13920. return true;
  13921. });
  13922. EXPECT_TRUE(std::string(items[0].name) == "document");
  13923. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13924. EXPECT_TRUE(items[0].filename == "2MB_data");
  13925. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13926. EXPECT_TRUE(items[1].name == "hello");
  13927. EXPECT_TRUE(items[1].content == "world");
  13928. EXPECT_TRUE(items[1].filename == "");
  13929. EXPECT_TRUE(items[1].content_type == "");
  13930. } else {
  13931. std::string body;
  13932. content_reader([&](const char *data, size_t data_length) {
  13933. body.append(data, data_length);
  13934. return true;
  13935. });
  13936. }
  13937. });
  13938. auto port = svr.bind_to_any_port("localhost");
  13939. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13940. auto se = detail::scope_exit([&] {
  13941. svr.stop();
  13942. t.join();
  13943. ASSERT_FALSE(svr.is_running());
  13944. });
  13945. svr.wait_until_ready();
  13946. {
  13947. std::string data(1024 * 1024 * 2, '&');
  13948. std::stringstream buffer;
  13949. buffer << data;
  13950. SSLClient cli("localhost", port);
  13951. cli.enable_server_certificate_verification(false);
  13952. UploadFormDataItems items{
  13953. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13954. {"hello", "world", "", ""},
  13955. };
  13956. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13958. ASSERT_EQ(StatusCode::OK_200, res->status);
  13959. }
  13960. }
  13961. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13962. std::string data(1024 * 1024 * 2, '&');
  13963. std::stringstream buffer;
  13964. buffer << data;
  13965. Client cli("https://localhost:8080");
  13966. cli.enable_server_certificate_verification(false);
  13967. UploadFormDataItems items{
  13968. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13969. {"hello", "world", "", ""},
  13970. };
  13971. for (const char &c : " \t\r\n") {
  13972. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13973. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13974. ASSERT_FALSE(res);
  13975. }
  13976. }
  13977. TEST(MultipartFormDataTest, AlternateFilename) {
  13978. auto handled = false;
  13979. Server svr;
  13980. svr.Post("/test", [&](const Request &req, Response &res) {
  13981. ASSERT_EQ(2u, req.form.files.size());
  13982. ASSERT_EQ(1u, req.form.fields.size());
  13983. // Test files
  13984. const auto &file1 = req.form.get_file("file1");
  13985. ASSERT_EQ("file1", file1.name);
  13986. ASSERT_EQ("A.txt", file1.filename);
  13987. ASSERT_EQ("text/plain", file1.content_type);
  13988. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13989. const auto &file2 = req.form.get_file("file2");
  13990. ASSERT_EQ("file2", file2.name);
  13991. ASSERT_EQ("a.html", file2.filename);
  13992. ASSERT_EQ("text/html", file2.content_type);
  13993. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13994. file2.content);
  13995. // Test text field
  13996. const auto &text = req.form.get_field("text");
  13997. ASSERT_EQ("text default", text);
  13998. res.set_content("ok", "text/plain");
  13999. handled = true;
  14000. });
  14001. thread t = thread([&] { svr.listen(HOST, PORT); });
  14002. auto se = detail::scope_exit([&] {
  14003. svr.stop();
  14004. t.join();
  14005. ASSERT_FALSE(svr.is_running());
  14006. ASSERT_TRUE(handled);
  14007. });
  14008. svr.wait_until_ready();
  14009. auto req = "POST /test HTTP/1.1\r\n"
  14010. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14011. "Content-Length: 399\r\n"
  14012. "\r\n"
  14013. "----------\r\n"
  14014. "Content-Disposition: form-data; name=\"text\"\r\n"
  14015. "\r\n"
  14016. "text default\r\n"
  14017. "----------\r\n"
  14018. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14019. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14020. "Content-Type: text/plain\r\n"
  14021. "\r\n"
  14022. "Content of a.txt.\r\n"
  14023. "\r\n"
  14024. "----------\r\n"
  14025. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14026. "\"a.html\"\r\n"
  14027. "Content-Type: text/html\r\n"
  14028. "\r\n"
  14029. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14030. "\r\n"
  14031. "------------\r\n";
  14032. ASSERT_TRUE(send_request(1, req));
  14033. }
  14034. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14035. auto handled = false;
  14036. Server svr;
  14037. svr.Post("/test", [&](const Request &req, Response &res) {
  14038. // Case-insensitive "utf-8''" prefix with a long value
  14039. const auto &file = req.form.get_file("file1");
  14040. ASSERT_EQ("file1", file.name);
  14041. // 8000 chars exercises both the Content-Disposition parser and the
  14042. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14043. // Prior to the fix, std::regex_match on this header would cause O(N)
  14044. // stack recursion in libstdc++, leading to SIGSEGV.
  14045. std::string expected_filename(8000, 'A');
  14046. ASSERT_EQ(expected_filename, file.filename);
  14047. res.set_content("ok", "text/plain");
  14048. handled = true;
  14049. });
  14050. thread t = thread([&] { svr.listen(HOST, PORT); });
  14051. auto se = detail::scope_exit([&] {
  14052. svr.stop();
  14053. t.join();
  14054. ASSERT_FALSE(svr.is_running());
  14055. ASSERT_TRUE(handled);
  14056. });
  14057. svr.wait_until_ready();
  14058. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14059. // Regression test for GHSA-qq6v-r583-3h69
  14060. std::string long_filename(8000, 'A');
  14061. std::string body = "----------\r\n"
  14062. "Content-Disposition: form-data; name=\"file1\"; "
  14063. "filename*=\"Utf-8''" +
  14064. long_filename +
  14065. "\"\r\n"
  14066. "\r\n"
  14067. "hello\r\n"
  14068. "------------\r\n";
  14069. auto req = "POST /test HTTP/1.1\r\n"
  14070. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14071. "Content-Length: " +
  14072. std::to_string(body.size()) + "\r\n\r\n" + body;
  14073. ASSERT_TRUE(send_request(1, req));
  14074. }
  14075. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14076. auto handled = false;
  14077. Server svr;
  14078. svr.Post("/test", [&](const Request &req, Response &) {
  14079. ASSERT_EQ(2u, req.form.fields.size());
  14080. const auto &text1 = req.form.get_field("text1");
  14081. ASSERT_EQ("text1", text1);
  14082. const auto &text2 = req.form.get_field("text2");
  14083. ASSERT_EQ("text2", text2);
  14084. handled = true;
  14085. });
  14086. thread t = thread([&] { svr.listen(HOST, PORT); });
  14087. auto se = detail::scope_exit([&] {
  14088. svr.stop();
  14089. t.join();
  14090. ASSERT_FALSE(svr.is_running());
  14091. ASSERT_TRUE(handled);
  14092. });
  14093. svr.wait_until_ready();
  14094. auto req = "POST /test HTTP/1.1\r\n"
  14095. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14096. "Content-Length: 146\r\n"
  14097. "\r\n----------\r\n"
  14098. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14099. "\r\n"
  14100. "text1"
  14101. "\r\n----------\r\n"
  14102. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14103. "\r\n"
  14104. "text2"
  14105. "\r\n------------";
  14106. std::string response;
  14107. ASSERT_TRUE(send_request(1, req, &response));
  14108. ASSERT_EQ("200", response.substr(9, 3));
  14109. }
  14110. TEST(MultipartFormDataTest, ContentLength) {
  14111. auto handled = false;
  14112. Server svr;
  14113. svr.Post("/test", [&](const Request &req, Response &) {
  14114. ASSERT_EQ(2u, req.form.fields.size());
  14115. const auto &text1 = req.form.get_field("text1");
  14116. ASSERT_EQ("text1", text1);
  14117. const auto &text2 = req.form.get_field("text2");
  14118. ASSERT_EQ("text2", text2);
  14119. handled = true;
  14120. });
  14121. thread t = thread([&] { svr.listen(HOST, PORT); });
  14122. auto se = detail::scope_exit([&] {
  14123. svr.stop();
  14124. t.join();
  14125. ASSERT_FALSE(svr.is_running());
  14126. ASSERT_TRUE(handled);
  14127. });
  14128. svr.wait_until_ready();
  14129. auto req = "POST /test HTTP/1.1\r\n"
  14130. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14131. "Content-Length: 167\r\n"
  14132. "\r\n----------\r\n"
  14133. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14134. "Content-Length: 5\r\n"
  14135. "\r\n"
  14136. "text1"
  14137. "\r\n----------\r\n"
  14138. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14139. "\r\n"
  14140. "text2"
  14141. "\r\n------------\r\n";
  14142. std::string response;
  14143. ASSERT_TRUE(send_request(1, req, &response));
  14144. ASSERT_EQ("200", response.substr(9, 3));
  14145. }
  14146. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14147. auto handled = false;
  14148. Server svr;
  14149. svr.Post("/test", [&](const Request &req, Response &) {
  14150. ASSERT_EQ(2u, req.form.fields.size());
  14151. const auto &text1 = req.form.get_field("text1");
  14152. ASSERT_EQ("text1", text1);
  14153. // TODO: Add header access for text fields if needed
  14154. const auto &text2 = req.form.get_field("text2");
  14155. ASSERT_EQ("text2", text2);
  14156. // TODO: Header access for text fields needs to be implemented
  14157. // auto &headers = it->second.headers;
  14158. // ASSERT_EQ(3U, headers.size());
  14159. // auto custom_header = headers.find("x-whatever");
  14160. // ASSERT_TRUE(custom_header != headers.end());
  14161. // ASSERT_NE("customvalue", custom_header->second);
  14162. // ASSERT_EQ("CustomValue", custom_header->second);
  14163. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14164. handled = true;
  14165. });
  14166. thread t = thread([&] { svr.listen(HOST, PORT); });
  14167. auto se = detail::scope_exit([&] {
  14168. svr.stop();
  14169. t.join();
  14170. ASSERT_FALSE(svr.is_running());
  14171. ASSERT_TRUE(handled);
  14172. });
  14173. svr.wait_until_ready();
  14174. auto req = "POST /test HTTP/1.1\r\n"
  14175. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14176. "Content-Length: 232\r\n"
  14177. "\r\n----------\r\n"
  14178. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14179. "Content-Length: 5\r\n"
  14180. "X-Test: 1\r\n"
  14181. "\r\n"
  14182. "text1"
  14183. "\r\n----------\r\n"
  14184. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14185. "Content-Type: text/plain\r\n"
  14186. "X-Whatever: CustomValue\r\n"
  14187. "\r\n"
  14188. "text2"
  14189. "\r\n------------\r\n"
  14190. "That should be disregarded. Not even read";
  14191. std::string response;
  14192. ASSERT_TRUE(send_request(1, req, &response));
  14193. ASSERT_EQ("200", response.substr(9, 3));
  14194. }
  14195. TEST(MultipartFormDataTest, LargeHeader) {
  14196. auto handled = false;
  14197. Server svr;
  14198. svr.Post("/test", [&](const Request &req, Response &) {
  14199. ASSERT_EQ(1u, req.form.fields.size());
  14200. const auto &text = req.form.get_field("name1");
  14201. ASSERT_EQ("text1", text);
  14202. handled = true;
  14203. });
  14204. thread t = thread([&] { svr.listen(HOST, PORT); });
  14205. auto se = detail::scope_exit([&] {
  14206. svr.stop();
  14207. t.join();
  14208. ASSERT_FALSE(svr.is_running());
  14209. ASSERT_TRUE(handled);
  14210. });
  14211. svr.wait_until_ready();
  14212. auto boundary = std::string("cpp-httplib-multipart-data");
  14213. std::string content = "--" + boundary +
  14214. "\r\n"
  14215. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14216. "\r\n"
  14217. "text1\r\n"
  14218. "--" +
  14219. boundary + "--\r\n";
  14220. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14221. "Content-Type: multipart/form-data;boundary=" +
  14222. boundary +
  14223. "\r\n"
  14224. "Content-Length: " +
  14225. std::to_string(content.size()) +
  14226. "\r\n"
  14227. "Dummy-Header: ";
  14228. std::string header_suffix = "\r\n"
  14229. "\r\n";
  14230. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14231. size_t header_dummy_size =
  14232. read_buff_size -
  14233. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14234. auto header_dummy = std::string(header_dummy_size, '@');
  14235. auto req = header_prefix + header_dummy + header_suffix + content;
  14236. std::string response;
  14237. ASSERT_TRUE(send_request(1, req, &response));
  14238. ASSERT_EQ("200", response.substr(9, 3));
  14239. }
  14240. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14241. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14242. // (not chunked Transfer-Encoding) after the streaming refactor.
  14243. auto handled = false;
  14244. Server svr;
  14245. svr.Post("/upload", [&](const Request &req, Response &res) {
  14246. auto cl_it = req.headers.find("Content-Length");
  14247. EXPECT_TRUE(cl_it != req.headers.end());
  14248. auto te_it = req.headers.find("Transfer-Encoding");
  14249. EXPECT_TRUE(te_it == req.headers.end());
  14250. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  14251. res.set_content("ok", "text/plain");
  14252. handled = true;
  14253. });
  14254. auto port = svr.bind_to_any_port(HOST);
  14255. auto t = thread([&] { svr.listen_after_bind(); });
  14256. auto se = detail::scope_exit([&] {
  14257. svr.stop();
  14258. t.join();
  14259. ASSERT_FALSE(svr.is_running());
  14260. ASSERT_TRUE(handled);
  14261. });
  14262. svr.wait_until_ready();
  14263. UploadFormDataItems items = {
  14264. {"field1", "hello", "", "text/plain"},
  14265. {"file1", "world", "test.txt", "application/octet-stream"},
  14266. };
  14267. Client cli(HOST, port);
  14268. auto res = cli.Post("/upload", {}, items);
  14269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14270. EXPECT_EQ(StatusCode::OK_200, res->status);
  14271. }
  14272. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  14273. // Verify that make_multipart_content_provider coalesces many small segments
  14274. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  14275. constexpr size_t kItemCount = 1000;
  14276. UploadFormDataItems items;
  14277. items.reserve(kItemCount);
  14278. for (size_t i = 0; i < kItemCount; i++) {
  14279. items.push_back(
  14280. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14281. }
  14282. const std::string boundary = "----test-boundary";
  14283. auto content_length = detail::get_multipart_content_length(items, boundary);
  14284. auto provider = detail::make_multipart_content_provider(items, boundary);
  14285. // Drive the provider the same way write_content_with_progress does
  14286. size_t write_count = 0;
  14287. size_t total_bytes = 0;
  14288. DataSink sink;
  14289. size_t offset = 0;
  14290. sink.write = [&](const char *d, size_t l) -> bool {
  14291. (void)d;
  14292. write_count++;
  14293. total_bytes += l;
  14294. offset += l;
  14295. return true;
  14296. };
  14297. sink.is_writable = []() -> bool { return true; };
  14298. while (offset < content_length) {
  14299. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  14300. }
  14301. EXPECT_EQ(content_length, total_bytes);
  14302. // The total number of segments is 3 * kItemCount + 1 = 3001.
  14303. // With buffering into 64KB blocks, write_count should be much smaller.
  14304. auto segment_count = 3 * kItemCount + 1;
  14305. EXPECT_LT(write_count, segment_count / 10);
  14306. }
  14307. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  14308. // Integration test: send many UploadFormDataItems and verify the server
  14309. // receives all of them correctly (#2410).
  14310. constexpr size_t kItemCount = 500;
  14311. auto handled = false;
  14312. Server svr;
  14313. svr.Post("/upload", [&](const Request &req, Response &res) {
  14314. EXPECT_EQ(kItemCount, req.form.fields.size());
  14315. for (size_t i = 0; i < kItemCount; i++) {
  14316. auto key = "field" + std::to_string(i);
  14317. auto val = "value" + std::to_string(i);
  14318. auto it = req.form.fields.find(key);
  14319. if (it != req.form.fields.end()) {
  14320. EXPECT_EQ(val, it->second.content);
  14321. } else {
  14322. ADD_FAILURE() << "Missing field: " << key;
  14323. }
  14324. }
  14325. res.set_content("ok", "text/plain");
  14326. handled = true;
  14327. });
  14328. auto port = svr.bind_to_any_port(HOST);
  14329. auto t = thread([&] { svr.listen_after_bind(); });
  14330. auto se = detail::scope_exit([&] {
  14331. svr.stop();
  14332. t.join();
  14333. ASSERT_FALSE(svr.is_running());
  14334. ASSERT_TRUE(handled);
  14335. });
  14336. svr.wait_until_ready();
  14337. UploadFormDataItems items;
  14338. items.reserve(kItemCount);
  14339. for (size_t i = 0; i < kItemCount; i++) {
  14340. items.push_back(
  14341. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  14342. }
  14343. Client cli(HOST, port);
  14344. auto res = cli.Post("/upload", items);
  14345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14346. EXPECT_EQ(StatusCode::OK_200, res->status);
  14347. }
  14348. TEST(MultipartFormDataTest, MakeFileProvider) {
  14349. // Verify make_file_provider sends a file's contents correctly.
  14350. const std::string file_content(4096, 'Z');
  14351. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  14352. {
  14353. std::ofstream ofs(tmp_path, std::ios::binary);
  14354. ofs.write(file_content.data(),
  14355. static_cast<std::streamsize>(file_content.size()));
  14356. }
  14357. auto handled = false;
  14358. Server svr;
  14359. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  14360. const ContentReader &content_reader) {
  14361. ASSERT_TRUE(req.is_multipart_form_data());
  14362. std::vector<FormData> items;
  14363. content_reader(
  14364. [&](const FormData &file) {
  14365. items.push_back(file);
  14366. return true;
  14367. },
  14368. [&](const char *data, size_t data_length) {
  14369. items.back().content.append(data, data_length);
  14370. return true;
  14371. });
  14372. ASSERT_EQ(1u, items.size());
  14373. EXPECT_EQ("myfile", items[0].name);
  14374. EXPECT_EQ("data.bin", items[0].filename);
  14375. EXPECT_EQ("application/octet-stream", items[0].content_type);
  14376. EXPECT_EQ(file_content, items[0].content);
  14377. handled = true;
  14378. });
  14379. auto port = svr.bind_to_any_port(HOST);
  14380. auto t = thread([&] { svr.listen_after_bind(); });
  14381. auto se = detail::scope_exit([&] {
  14382. svr.stop();
  14383. t.join();
  14384. ASSERT_FALSE(svr.is_running());
  14385. ASSERT_TRUE(handled);
  14386. std::remove(tmp_path.c_str());
  14387. });
  14388. svr.wait_until_ready();
  14389. FormDataProviderItems providers;
  14390. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  14391. "application/octet-stream"));
  14392. Client cli(HOST, port);
  14393. auto res = cli.Post("/upload", {}, {}, providers);
  14394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14395. EXPECT_EQ(StatusCode::OK_200, res->status);
  14396. }
  14397. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14398. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14399. // (100) headers is rejected with a 400 Bad Request response.
  14400. Server svr;
  14401. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14402. res.set_content("ok", "text/plain");
  14403. });
  14404. thread t = thread([&] { svr.listen(HOST, PORT); });
  14405. auto se = detail::scope_exit([&] {
  14406. svr.stop();
  14407. t.join();
  14408. ASSERT_FALSE(svr.is_running());
  14409. });
  14410. svr.wait_until_ready();
  14411. // Build a multipart part with 101 custom headers (exceeding
  14412. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14413. std::stringstream body;
  14414. body << "--simpleboundary\r\n"
  14415. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14416. for (int i = 0; i < 101; i++) {
  14417. body << "X-Custom-Header-" << i << ": value\r\n";
  14418. }
  14419. body << "\r\n"
  14420. << "value1\r\n"
  14421. << "--simpleboundary--\r\n";
  14422. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14423. Client cli(HOST, PORT);
  14424. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14426. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14427. }
  14428. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14429. // A body that never contains the declared boundary must not be accumulated
  14430. // while the parser waits for it. Buffering it would also make every read
  14431. // rescan everything seen so far, which is quadratic in the body size.
  14432. Server svr;
  14433. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14434. res.set_content("ok", "text/plain");
  14435. });
  14436. auto port = svr.bind_to_any_port(HOST);
  14437. thread t = thread([&] { svr.listen_after_bind(); });
  14438. auto se = detail::scope_exit([&] {
  14439. svr.stop();
  14440. t.join();
  14441. ASSERT_FALSE(svr.is_running());
  14442. });
  14443. svr.wait_until_ready();
  14444. Client cli(HOST, port);
  14445. cli.set_read_timeout(60, 0);
  14446. cli.set_write_timeout(60, 0);
  14447. // '-' is the worst case: it matches the first character of the boundary, so
  14448. // every position has to be checked against it.
  14449. auto post_dashes = [&](size_t size) {
  14450. const std::string body(size, '-');
  14451. auto start = std::chrono::steady_clock::now();
  14452. auto res =
  14453. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14454. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14455. std::chrono::steady_clock::now() - start)
  14456. .count();
  14457. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14458. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14459. return ms;
  14460. };
  14461. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14462. // Windows.
  14463. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14464. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14465. // Comparing the two sizes rather than checking an absolute duration keeps
  14466. // this meaningful across build types and CI load, both of which move the
  14467. // absolute numbers by more than an order of magnitude. Four times the bytes
  14468. // costs about four times the time when parsing is linear, and about sixteen
  14469. // times when the body is buffered and rescanned.
  14470. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14471. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14472. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14473. << "ms, which suggests the body is being buffered and rescanned";
  14474. }
  14475. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14476. // A boundary can only be followed by CRLF or by "--", so anything else is
  14477. // malformed no matter what comes next. The parser must say so right away
  14478. // instead of buffering the rest of the declared body.
  14479. Server svr;
  14480. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14481. res.set_content("ok", "text/plain");
  14482. });
  14483. auto port = svr.bind_to_any_port(HOST);
  14484. thread t = thread([&] { svr.listen_after_bind(); });
  14485. auto se = detail::scope_exit([&] {
  14486. svr.stop();
  14487. t.join();
  14488. ASSERT_FALSE(svr.is_running());
  14489. });
  14490. svr.wait_until_ready();
  14491. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14492. // buffers instead of failing would still be waiting for the remaining bytes.
  14493. const std::string body = "--zzzz\r\n"
  14494. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14495. "\r\n"
  14496. "text1"
  14497. "\r\n--zzzzXX";
  14498. const std::string req = "POST /post HTTP/1.1\r\n"
  14499. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14500. "Content-Length: 1048576\r\n"
  14501. "\r\n" +
  14502. body;
  14503. std::string response;
  14504. ASSERT_TRUE(send_request(3, req, &response, port));
  14505. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14506. EXPECT_EQ("400", response.substr(9, 3));
  14507. }
  14508. // Posts a multipart body split into two writes, so that the server sees the
  14509. // split at whatever offset the caller chose, and expects the single "text1"
  14510. // field to come through.
  14511. static void expect_split_multipart_ok(const std::string &body1,
  14512. const std::string &body2) {
  14513. auto handled = false;
  14514. Server svr;
  14515. svr.Post("/post", [&](const Request &req, Response &) {
  14516. EXPECT_EQ(1u, req.form.fields.size());
  14517. EXPECT_EQ("text1", req.form.get_field("text1"));
  14518. handled = true;
  14519. });
  14520. auto port = svr.bind_to_any_port(HOST);
  14521. thread t = thread([&] { svr.listen_after_bind(); });
  14522. auto se = detail::scope_exit([&] {
  14523. svr.stop();
  14524. t.join();
  14525. ASSERT_FALSE(svr.is_running());
  14526. ASSERT_TRUE(handled);
  14527. });
  14528. svr.wait_until_ready();
  14529. // "Connection: close" makes the server close once it has answered, so the
  14530. // response drain ends immediately instead of idling until the read timeout.
  14531. const std::string head =
  14532. "POST /post HTTP/1.1\r\n"
  14533. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14534. "Connection: close\r\n"
  14535. "Content-Length: " +
  14536. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14537. std::string response;
  14538. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14539. ASSERT_GE(response.size(), 12u) << "no response";
  14540. EXPECT_EQ("200", response.substr(9, 3));
  14541. }
  14542. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14543. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14544. // ignored, including when it does not arrive in the same read as the
  14545. // close-delimiter itself.
  14546. expect_split_multipart_ok("--zzzz\r\n"
  14547. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14548. "\r\n"
  14549. "text1"
  14550. "\r\n--zzzz--",
  14551. "\r\nthis epilogue must be ignored\r\n");
  14552. }
  14553. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14554. // The initial boundary may be preceded by a preamble of any length and may
  14555. // straddle a read boundary. Discarding data while waiting for it must not
  14556. // throw away a partial boundary sitting at the end of the buffer.
  14557. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14558. "zz\r\n"
  14559. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14560. "\r\n"
  14561. "text1"
  14562. "\r\n--zzzz--\r\n");
  14563. }
  14564. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14565. // The received boundary was only checked for being non-empty, so it could be
  14566. // as long as a header is allowed to be. The parser scans the body for
  14567. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14568. // costs a nearly full comparison at nearly every position, making the
  14569. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14570. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14571. Server svr;
  14572. svr.Post("/post", [](const Request &req, Response &res) {
  14573. EXPECT_EQ(1u, req.form.fields.size());
  14574. EXPECT_EQ("text1", req.form.get_field("text1"));
  14575. res.set_content("ok", "text/plain");
  14576. });
  14577. auto port = svr.bind_to_any_port(HOST);
  14578. thread t = thread([&] { svr.listen_after_bind(); });
  14579. auto se = detail::scope_exit([&] {
  14580. svr.stop();
  14581. t.join();
  14582. ASSERT_FALSE(svr.is_running());
  14583. });
  14584. svr.wait_until_ready();
  14585. Client cli(HOST, port);
  14586. auto post_with_boundary_of_length = [&](size_t len) {
  14587. const std::string boundary(len, 'a');
  14588. const std::string body =
  14589. "--" + boundary +
  14590. "\r\n"
  14591. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14592. "\r\n"
  14593. "text1"
  14594. "\r\n--" +
  14595. boundary + "--\r\n";
  14596. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14597. };
  14598. auto res = post_with_boundary_of_length(70);
  14599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14600. EXPECT_EQ(StatusCode::OK_200, res->status);
  14601. res = post_with_boundary_of_length(71);
  14602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14603. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14604. }
  14605. TEST(MakeFileBodyTest, Basic) {
  14606. const std::string file_content(4096, 'Z');
  14607. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14608. {
  14609. std::ofstream ofs(tmp_path, std::ios::binary);
  14610. ofs.write(file_content.data(),
  14611. static_cast<std::streamsize>(file_content.size()));
  14612. }
  14613. auto handled = false;
  14614. Server svr;
  14615. svr.Post("/upload", [&](const Request &req, Response &res) {
  14616. EXPECT_EQ(file_content, req.body);
  14617. handled = true;
  14618. res.status = StatusCode::OK_200;
  14619. });
  14620. auto port = svr.bind_to_any_port(HOST);
  14621. auto t = thread([&] { svr.listen_after_bind(); });
  14622. auto se = detail::scope_exit([&] {
  14623. svr.stop();
  14624. t.join();
  14625. ASSERT_FALSE(svr.is_running());
  14626. ASSERT_TRUE(handled);
  14627. std::remove(tmp_path.c_str());
  14628. });
  14629. svr.wait_until_ready();
  14630. auto fb = make_file_body(tmp_path);
  14631. ASSERT_GT(fb.first, 0u);
  14632. Client cli(HOST, port);
  14633. auto res =
  14634. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14636. EXPECT_EQ(StatusCode::OK_200, res->status);
  14637. }
  14638. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14639. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14640. {
  14641. std::ofstream ofs(path, std::ios::binary);
  14642. const std::string content(100, 'A');
  14643. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14644. }
  14645. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14646. auto body = make_file_body(path);
  14647. ASSERT_EQ(100u, body.first);
  14648. ASSERT_TRUE(static_cast<bool>(body.second));
  14649. // Rewritten shorter after its length was measured - and, on a server, after
  14650. // that length has already gone out as Content-Length.
  14651. {
  14652. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14653. const std::string content(10, 'A');
  14654. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14655. }
  14656. std::string written;
  14657. DataSink sink;
  14658. sink.write = [&](const char *d, size_t l) {
  14659. written.append(d, l);
  14660. return true;
  14661. };
  14662. // The provider has to report failure. write_content_with_progress() advances
  14663. // its offset only by what was written, so a provider that returns true
  14664. // without completing the length it promised is called again straight away,
  14665. // and again.
  14666. EXPECT_FALSE(body.second(0, body.first, sink));
  14667. EXPECT_EQ(std::string(10, 'A'), written);
  14668. }
  14669. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14670. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14671. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14672. {
  14673. std::ofstream ofs(path, std::ios::binary);
  14674. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14675. }
  14676. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14677. auto body = make_file_body(path);
  14678. ASSERT_EQ(content.size(), body.first);
  14679. ASSERT_TRUE(static_cast<bool>(body.second));
  14680. std::string written;
  14681. DataSink sink;
  14682. sink.write = [&](const char *d, size_t l) {
  14683. written.append(d, l);
  14684. return true;
  14685. };
  14686. EXPECT_TRUE(body.second(0, body.first, sink));
  14687. EXPECT_EQ(content, written);
  14688. }
  14689. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14690. static constexpr unsigned int number_of_tasks{1000000};
  14691. std::atomic_uint count{0};
  14692. std::unique_ptr<TaskQueue> task_queue{
  14693. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14694. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14695. auto queued = task_queue->enqueue(
  14696. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14697. EXPECT_TRUE(queued);
  14698. }
  14699. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14700. task_queue->shutdown();
  14701. #else
  14702. EXPECT_NO_THROW(task_queue->shutdown());
  14703. #endif
  14704. EXPECT_EQ(number_of_tasks, count.load());
  14705. }
  14706. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14707. static constexpr unsigned int number_of_tasks{1000000};
  14708. static constexpr unsigned int qlimit{2};
  14709. unsigned int queued_count{0};
  14710. std::atomic_uint count{0};
  14711. std::unique_ptr<TaskQueue> task_queue{
  14712. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14713. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14714. if (task_queue->enqueue(
  14715. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14716. queued_count++;
  14717. }
  14718. }
  14719. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14720. task_queue->shutdown();
  14721. #else
  14722. EXPECT_NO_THROW(task_queue->shutdown());
  14723. #endif
  14724. EXPECT_EQ(queued_count, count.load());
  14725. EXPECT_TRUE(queued_count <= number_of_tasks);
  14726. EXPECT_TRUE(queued_count >= qlimit);
  14727. }
  14728. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14729. // Use a short idle timeout so a dynamic thread spawns, times out and
  14730. // exits during the test, and the pool keeps working afterwards.
  14731. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14732. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14733. /*idle_timeout_sec=*/1}};
  14734. std::atomic_uint count{0};
  14735. std::condition_variable cv;
  14736. std::mutex mtx;
  14737. bool release = false;
  14738. // Block the base thread so the second task spawns a dynamic thread.
  14739. EXPECT_TRUE(task_queue->enqueue([&] {
  14740. std::unique_lock<std::mutex> lock(mtx);
  14741. while (!release) {
  14742. cv.wait(lock);
  14743. }
  14744. count++;
  14745. }));
  14746. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14747. // Let the dynamic thread finish its task and exceed the idle timeout.
  14748. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14749. {
  14750. std::unique_lock<std::mutex> lock(mtx);
  14751. release = true;
  14752. }
  14753. cv.notify_all();
  14754. // The pool must still accept and run tasks after the dynamic thread exited.
  14755. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14756. task_queue->shutdown();
  14757. EXPECT_EQ(3u, count.load());
  14758. }
  14759. TEST(TaskQueueTest, MaxQueuedRequests) {
  14760. static constexpr unsigned int qlimit{3};
  14761. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14762. std::condition_variable sem_cv;
  14763. std::mutex sem_mtx;
  14764. int credits = 0;
  14765. bool queued;
  14766. /* Fill up the queue with tasks that will block until we give them credits to
  14767. * complete. */
  14768. for (unsigned int n = 0; n <= qlimit;) {
  14769. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14770. std::unique_lock<std::mutex> lock(sem_mtx);
  14771. while (credits <= 0) {
  14772. sem_cv.wait(lock);
  14773. }
  14774. /* Consume the credit and signal the test code if they are all gone. */
  14775. if (--credits == 0) { sem_cv.notify_one(); }
  14776. });
  14777. if (n < qlimit) {
  14778. /* The first qlimit enqueues must succeed. */
  14779. EXPECT_TRUE(queued);
  14780. } else {
  14781. /* The last one will succeed only when the worker thread
  14782. * starts and dequeues the first blocking task. Although
  14783. * not necessary for the correctness of this test, we sleep for
  14784. * a short while to avoid busy waiting. */
  14785. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14786. }
  14787. if (queued) { n++; }
  14788. }
  14789. /* Further enqueues must fail since the queue is full. */
  14790. for (auto i = 0; i < 4; i++) {
  14791. queued = task_queue->enqueue([] {});
  14792. EXPECT_FALSE(queued);
  14793. }
  14794. /* Give the credits to allow the previous tasks to complete. */
  14795. {
  14796. std::unique_lock<std::mutex> lock(sem_mtx);
  14797. credits += qlimit + 1;
  14798. }
  14799. sem_cv.notify_all();
  14800. /* Wait for all the credits to be consumed. */
  14801. {
  14802. std::unique_lock<std::mutex> lock(sem_mtx);
  14803. while (credits > 0) {
  14804. sem_cv.wait(lock);
  14805. }
  14806. }
  14807. /* Check that we are able again to enqueue at least qlimit tasks. */
  14808. for (unsigned int i = 0; i < qlimit; i++) {
  14809. queued = task_queue->enqueue([] {});
  14810. EXPECT_TRUE(queued);
  14811. }
  14812. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14813. task_queue->shutdown();
  14814. #else
  14815. EXPECT_NO_THROW(task_queue->shutdown());
  14816. #endif
  14817. }
  14818. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  14819. Server svr;
  14820. std::string method;
  14821. std::string body;
  14822. auto has_content_length = false;
  14823. auto has_transfer_encoding = false;
  14824. std::atomic<int> bad_requests{0};
  14825. // Leftover body bytes get parsed as a malformed request and answered with
  14826. // 400
  14827. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  14828. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  14829. });
  14830. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  14831. res.set_redirect("/down", StatusCode::SeeOther_303);
  14832. });
  14833. svr.Get("/down", [&](const Request &req, Response &res) {
  14834. method = req.method;
  14835. body = req.body;
  14836. has_content_length = req.has_header("Content-Length");
  14837. has_transfer_encoding = req.has_header("Transfer-Encoding");
  14838. res.set_content("ok", "text/plain");
  14839. });
  14840. auto port = svr.bind_to_any_port(HOST);
  14841. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14842. auto se = detail::scope_exit([&] {
  14843. svr.stop();
  14844. thread.join();
  14845. ASSERT_FALSE(svr.is_running());
  14846. });
  14847. svr.wait_until_ready();
  14848. const std::string payload = "SECRET-BODY";
  14849. auto check = [&](Client &cli, const Result &res) {
  14850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14851. EXPECT_EQ(StatusCode::OK_200, res->status);
  14852. EXPECT_EQ("ok", res->body);
  14853. EXPECT_EQ("GET", method);
  14854. EXPECT_TRUE(body.empty());
  14855. EXPECT_FALSE(has_content_length);
  14856. EXPECT_FALSE(has_transfer_encoding);
  14857. // Nothing of the original body may be left on the connection
  14858. auto res2 = cli.Get("/down");
  14859. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  14860. EXPECT_EQ(StatusCode::OK_200, res2->status);
  14861. EXPECT_EQ("ok", res2->body);
  14862. EXPECT_EQ(0, bad_requests);
  14863. };
  14864. // With content length
  14865. {
  14866. Client cli(HOST, port);
  14867. cli.set_keep_alive(true);
  14868. cli.set_follow_location(true);
  14869. auto res = cli.Post(
  14870. "/up", payload.size(),
  14871. [&](size_t offset, size_t length, DataSink &sink) {
  14872. return sink.write(payload.data() + offset, length);
  14873. },
  14874. "text/plain");
  14875. check(cli, res);
  14876. }
  14877. // Without content length (chunked)
  14878. {
  14879. Client cli(HOST, port);
  14880. cli.set_keep_alive(true);
  14881. cli.set_follow_location(true);
  14882. auto res = cli.Post(
  14883. "/up",
  14884. [&](size_t /*offset*/, DataSink &sink) {
  14885. sink.write(payload.data(), payload.size());
  14886. sink.done();
  14887. return true;
  14888. },
  14889. "text/plain");
  14890. check(cli, res);
  14891. }
  14892. }
  14893. TEST(RedirectTest, LocationPathIsNotDecoded) {
  14894. Server svr;
  14895. std::string target;
  14896. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  14897. // Echo the still-encoded name back in the Location
  14898. const std::string prefix = "/start/";
  14899. res.status = StatusCode::Found_302;
  14900. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  14901. });
  14902. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  14903. target = req.target;
  14904. res.set_content("ok", "text/plain");
  14905. });
  14906. auto port = svr.bind_to_any_port(HOST);
  14907. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14908. auto se = detail::scope_exit([&] {
  14909. svr.stop();
  14910. thread.join();
  14911. ASSERT_FALSE(svr.is_running());
  14912. });
  14913. svr.wait_until_ready();
  14914. // Decoding the Location path would turn the first four into a path
  14915. // separator, a query delimiter, a fragment delimiter and a different
  14916. // percent-encoded octet. The rest must keep reaching the server as they are.
  14917. const std::vector<std::string> names = {
  14918. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  14919. };
  14920. for (auto path_encode : {true, false}) {
  14921. Client cli(HOST, port);
  14922. cli.set_follow_location(true);
  14923. cli.set_path_encode(path_encode);
  14924. for (const auto &name : names) {
  14925. target.clear();
  14926. auto res = cli.Get("/start/" + name);
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. EXPECT_EQ(StatusCode::OK_200, res->status);
  14929. EXPECT_EQ("/dest/" + name, target);
  14930. }
  14931. }
  14932. }
  14933. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14934. Server svr;
  14935. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14936. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14937. });
  14938. svr.Get("/hello", [](const Request &req, Response &res) {
  14939. res.set_content(req.get_param_value("key"), "text/plain");
  14940. });
  14941. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. thread.join();
  14945. ASSERT_FALSE(svr.is_running());
  14946. });
  14947. svr.wait_until_ready();
  14948. {
  14949. Client cli(HOST, PORT);
  14950. cli.set_follow_location(true);
  14951. auto res = cli.Get("/");
  14952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14953. EXPECT_EQ(StatusCode::OK_200, res->status);
  14954. EXPECT_EQ("val&key2=val2", res->body);
  14955. }
  14956. }
  14957. #endif
  14958. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14959. Server svr;
  14960. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14961. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14962. });
  14963. svr.Get("/hello", [](const Request &req, Response &res) {
  14964. res.set_content(req.get_param_value("key"), "text/plain");
  14965. });
  14966. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14967. auto se = detail::scope_exit([&] {
  14968. svr.stop();
  14969. thread.join();
  14970. ASSERT_FALSE(svr.is_running());
  14971. });
  14972. svr.wait_until_ready();
  14973. {
  14974. Client cli(HOST, PORT);
  14975. cli.set_follow_location(true);
  14976. auto res = cli.Get("/");
  14977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14978. EXPECT_EQ(StatusCode::OK_200, res->status);
  14979. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14980. }
  14981. }
  14982. TEST(RedirectTest, RedirectWithPlusInPath) {
  14983. Server svr;
  14984. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14985. res.set_redirect("/a+b");
  14986. });
  14987. // Route pattern uses regex; escape + as \\+
  14988. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14989. res.set_content(req.path, "text/plain");
  14990. });
  14991. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14992. auto se = detail::scope_exit([&] {
  14993. svr.stop();
  14994. thread.join();
  14995. ASSERT_FALSE(svr.is_running());
  14996. });
  14997. svr.wait_until_ready();
  14998. {
  14999. Client cli(HOST, PORT);
  15000. cli.set_follow_location(true);
  15001. auto res = cli.Get("/");
  15002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15003. EXPECT_EQ(StatusCode::OK_200, res->status);
  15004. EXPECT_EQ("/a+b", res->body);
  15005. }
  15006. }
  15007. TEST(RedirectTest, ResolveRelativeLocation) {
  15008. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15009. const std::vector<std::pair<std::string, std::string>> cases = {
  15010. {"g", "/b/c/g"},
  15011. {"./g", "/b/c/g"},
  15012. {"g/", "/b/c/g/"},
  15013. {"?y", "/b/c/d;p?y"},
  15014. {"g?y", "/b/c/g?y"},
  15015. {"#s", "/b/c/d;p?q#s"},
  15016. {"g#s", "/b/c/g#s"},
  15017. {"g?y#s", "/b/c/g?y#s"},
  15018. {";x", "/b/c/;x"},
  15019. {"g;x", "/b/c/g;x"},
  15020. {".", "/b/c/"},
  15021. {"./", "/b/c/"},
  15022. {"..", "/b/"},
  15023. {"../", "/b/"},
  15024. {"../g", "/b/g"},
  15025. {"../..", "/"},
  15026. {"../../", "/"},
  15027. {"../../g", "/g"},
  15028. {"../../../g", "/g"},
  15029. {"g.", "/b/c/g."},
  15030. {".g", "/b/c/.g"},
  15031. {"g..", "/b/c/g.."},
  15032. {"..g", "/b/c/..g"},
  15033. {"./../g", "/b/g"},
  15034. {"./g/.", "/b/c/g/"},
  15035. {"g/./h", "/b/c/g/h"},
  15036. {"g/../h", "/b/c/h"},
  15037. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15038. {"g;x=1/../y", "/b/c/y"},
  15039. {"g?y/./x", "/b/c/g?y/./x"},
  15040. {"g#s/../x", "/b/c/g#s/../x"},
  15041. // Not relative-path references, so left for parse_url.
  15042. {"/g", "/g"},
  15043. {"//g", "//g"},
  15044. {"http://g/x", "http://g/x"},
  15045. {"g:h", "g:h"},
  15046. };
  15047. for (const auto &c : cases) {
  15048. EXPECT_EQ(c.second,
  15049. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15050. << c.first;
  15051. }
  15052. }
  15053. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15054. Server svr;
  15055. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15056. res.set_redirect(req.get_param_value("to"));
  15057. });
  15058. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15059. res.set_content(req.target, "text/plain");
  15060. });
  15061. svr.Get("/other", [](const Request &req, Response &res) {
  15062. res.set_content(req.target, "text/plain");
  15063. });
  15064. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15065. auto se = detail::scope_exit([&] {
  15066. svr.stop();
  15067. thread.join();
  15068. ASSERT_FALSE(svr.is_running());
  15069. });
  15070. svr.wait_until_ready();
  15071. const std::vector<std::pair<std::string, std::string>> cases = {
  15072. {"next", "/dir/next"},
  15073. {"./next?x=1", "/dir/next?x=1"},
  15074. {"../other", "/other"},
  15075. };
  15076. for (const auto &c : cases) {
  15077. Client cli(HOST, PORT);
  15078. cli.set_follow_location(true);
  15079. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15080. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15081. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15082. EXPECT_EQ(c.second, res->body) << c.first;
  15083. }
  15084. }
  15085. #ifdef CPPHTTPLIB_SSL_ENABLED
  15086. TEST(RedirectTest, Issue2185_Online) {
  15087. SSLClient client("github.com");
  15088. client.set_follow_location(true);
  15089. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15090. "Coollab-Windows.zip");
  15091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15092. EXPECT_EQ(StatusCode::OK_200, res->status);
  15093. EXPECT_EQ(9920427U, res->body.size());
  15094. }
  15095. #endif
  15096. TEST(VulnerabilityTest, CRLFInjection) {
  15097. Server svr;
  15098. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15099. res.set_content("Hello 1", "text/plain");
  15100. });
  15101. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15102. res.set_content("Hello 2", "text/plain");
  15103. });
  15104. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15105. res.set_content("Hello 3", "text/plain");
  15106. });
  15107. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15108. res.set_content("Hello 4", "text/plain");
  15109. });
  15110. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15111. for (const auto &x : req.headers) {
  15112. auto key = x.first;
  15113. EXPECT_STRNE("evil", key.c_str());
  15114. }
  15115. });
  15116. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15117. auto se = detail::scope_exit([&] {
  15118. svr.stop();
  15119. thread.join();
  15120. ASSERT_FALSE(svr.is_running());
  15121. });
  15122. svr.wait_until_ready();
  15123. {
  15124. Client cli(HOST, PORT);
  15125. cli.Post("/test1", "A=B",
  15126. "application/x-www-form-urlencoded\r\nevil: hello1");
  15127. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15128. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15129. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15130. }
  15131. }
  15132. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15133. auto server_thread = std::thread([] {
  15134. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15135. default_socket_options(srv);
  15136. sockaddr_in addr{};
  15137. addr.sin_family = AF_INET;
  15138. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15139. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15140. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15141. ::listen(srv, 1);
  15142. sockaddr_in cli_addr{};
  15143. socklen_t cli_len = sizeof(cli_addr);
  15144. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15145. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15146. std::string buf_all;
  15147. char buf[2048];
  15148. ssize_t n;
  15149. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15150. buf_all.append(buf, static_cast<size_t>(n));
  15151. size_t pos;
  15152. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15153. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15154. auto e = request_block.find("\r\n");
  15155. if (e != std::string::npos) {
  15156. auto request_line = request_block.substr(0, e);
  15157. std::string msg =
  15158. "CRLF injection detected in request line: '" + request_line + "'";
  15159. EXPECT_FALSE(true) << msg;
  15160. }
  15161. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15162. ::send(cli,
  15163. #ifdef _WIN32
  15164. static_cast<const char *>(resp.c_str()),
  15165. static_cast<int>(resp.size()),
  15166. #else
  15167. resp.c_str(), resp.size(),
  15168. #endif
  15169. 0);
  15170. buf_all.erase(0, pos + 4);
  15171. }
  15172. }
  15173. detail::close_socket(cli);
  15174. detail::close_socket(srv);
  15175. });
  15176. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15177. auto cli = Client("127.0.0.1", PORT + 1);
  15178. auto headers = Headers{
  15179. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15180. {"Connection", "keep-alive"}};
  15181. auto res = cli.Get("/hi", headers);
  15182. EXPECT_FALSE(res);
  15183. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15184. server_thread.join();
  15185. }
  15186. // A request rejected before any byte reaches the socket must fail right away
  15187. // instead of waiting for a response the server will never send.
  15188. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15189. // The kernel completes the TCP handshake from the listen backlog, so the
  15190. // client connects, but nothing ever reads, responds or closes.
  15191. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15192. default_socket_options(srv);
  15193. sockaddr_in addr{};
  15194. addr.sin_family = AF_INET;
  15195. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15196. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15197. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15198. ASSERT_EQ(0, ::listen(srv, 8));
  15199. auto cli = Client("127.0.0.1", PORT + 1);
  15200. cli.set_read_timeout(10, 0);
  15201. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15202. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15203. std::chrono::steady_clock::now() - start)
  15204. .count();
  15205. };
  15206. {
  15207. Request req;
  15208. req.method = "GE T";
  15209. req.path = "/";
  15210. auto start = std::chrono::steady_clock::now();
  15211. auto res = cli.send(req);
  15212. EXPECT_FALSE(res);
  15213. EXPECT_EQ(Error::Write, res.error());
  15214. EXPECT_LT(elapsed_ms(start), 1000);
  15215. }
  15216. {
  15217. auto start = std::chrono::steady_clock::now();
  15218. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15219. EXPECT_FALSE(res);
  15220. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15221. EXPECT_LT(elapsed_ms(start), 1000);
  15222. }
  15223. EXPECT_FALSE(cli.is_socket_open());
  15224. detail::close_socket(srv);
  15225. }
  15226. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15227. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15228. default_socket_options(srv);
  15229. sockaddr_in addr{};
  15230. addr.sin_family = AF_INET;
  15231. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15232. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15233. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15234. ASSERT_EQ(0, ::listen(srv, 1));
  15235. std::string received;
  15236. auto server_thread = std::thread([&] {
  15237. auto sock = ::accept(srv, nullptr, nullptr);
  15238. if (sock == INVALID_SOCKET) { return; }
  15239. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15240. char buf[2048];
  15241. ssize_t n;
  15242. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15243. received.append(buf, static_cast<size_t>(n));
  15244. }
  15245. detail::close_socket(sock);
  15246. });
  15247. {
  15248. auto cli = Client("127.0.0.1", PORT + 1);
  15249. // "Z" sorts after the default headers, so writing straight to the socket
  15250. // would have sent the request line and those headers before the rejection.
  15251. auto handle =
  15252. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  15253. EXPECT_FALSE(handle.is_valid());
  15254. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  15255. }
  15256. server_thread.join();
  15257. detail::close_socket(srv);
  15258. EXPECT_TRUE(received.empty()) << received;
  15259. }
  15260. TEST(PathParamsTest, StaticMatch) {
  15261. const auto pattern = "/users/all";
  15262. detail::PathParamsMatcher matcher(pattern);
  15263. Request request;
  15264. request.path = "/users/all";
  15265. ASSERT_TRUE(matcher.match(request));
  15266. std::unordered_map<std::string, std::string> expected_params = {};
  15267. EXPECT_EQ(request.path_params, expected_params);
  15268. }
  15269. TEST(PathParamsTest, StaticMismatch) {
  15270. const auto pattern = "/users/all";
  15271. detail::PathParamsMatcher matcher(pattern);
  15272. Request request;
  15273. request.path = "/users/1";
  15274. ASSERT_FALSE(matcher.match(request));
  15275. }
  15276. TEST(PathParamsTest, SingleParamInTheMiddle) {
  15277. const auto pattern = "/users/:id/subscriptions";
  15278. detail::PathParamsMatcher matcher(pattern);
  15279. Request request;
  15280. request.path = "/users/42/subscriptions";
  15281. ASSERT_TRUE(matcher.match(request));
  15282. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15283. EXPECT_EQ(request.path_params, expected_params);
  15284. }
  15285. TEST(PathParamsTest, SingleParamInTheEnd) {
  15286. const auto pattern = "/users/:id";
  15287. detail::PathParamsMatcher matcher(pattern);
  15288. Request request;
  15289. request.path = "/users/24";
  15290. ASSERT_TRUE(matcher.match(request));
  15291. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  15292. EXPECT_EQ(request.path_params, expected_params);
  15293. }
  15294. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  15295. const auto pattern = "/users/:id/";
  15296. detail::PathParamsMatcher matcher(pattern);
  15297. Request request;
  15298. request.path = "/users/42/";
  15299. ASSERT_TRUE(matcher.match(request));
  15300. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  15301. EXPECT_EQ(request.path_params, expected_params);
  15302. }
  15303. TEST(PathParamsTest, EmptyParam) {
  15304. const auto pattern = "/users/:id/";
  15305. detail::PathParamsMatcher matcher(pattern);
  15306. Request request;
  15307. request.path = "/users//";
  15308. ASSERT_TRUE(matcher.match(request));
  15309. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  15310. EXPECT_EQ(request.path_params, expected_params);
  15311. }
  15312. TEST(PathParamsTest, FragmentMismatch) {
  15313. const auto pattern = "/users/:id/";
  15314. detail::PathParamsMatcher matcher(pattern);
  15315. Request request;
  15316. request.path = "/admins/24/";
  15317. ASSERT_FALSE(matcher.match(request));
  15318. }
  15319. TEST(PathParamsTest, ExtraFragments) {
  15320. const auto pattern = "/users/:id";
  15321. detail::PathParamsMatcher matcher(pattern);
  15322. Request request;
  15323. request.path = "/users/42/subscriptions";
  15324. ASSERT_FALSE(matcher.match(request));
  15325. }
  15326. TEST(PathParamsTest, MissingTrailingParam) {
  15327. const auto pattern = "/users/:id";
  15328. detail::PathParamsMatcher matcher(pattern);
  15329. Request request;
  15330. request.path = "/users";
  15331. ASSERT_FALSE(matcher.match(request));
  15332. }
  15333. TEST(PathParamsTest, MissingParamInTheMiddle) {
  15334. const auto pattern = "/users/:id/subscriptions";
  15335. detail::PathParamsMatcher matcher(pattern);
  15336. Request request;
  15337. request.path = "/users/subscriptions";
  15338. ASSERT_FALSE(matcher.match(request));
  15339. }
  15340. TEST(PathParamsTest, MultipleParams) {
  15341. const auto pattern = "/users/:userid/subscriptions/:subid";
  15342. detail::PathParamsMatcher matcher(pattern);
  15343. Request request;
  15344. request.path = "/users/42/subscriptions/2";
  15345. ASSERT_TRUE(matcher.match(request));
  15346. std::unordered_map<std::string, std::string> expected_params = {
  15347. {"userid", "42"}, {"subid", "2"}};
  15348. EXPECT_EQ(request.path_params, expected_params);
  15349. }
  15350. TEST(PathParamsTest, SequenceOfParams) {
  15351. const auto pattern = "/values/:x/:y/:z";
  15352. detail::PathParamsMatcher matcher(pattern);
  15353. Request request;
  15354. request.path = "/values/1/2/3";
  15355. ASSERT_TRUE(matcher.match(request));
  15356. std::unordered_map<std::string, std::string> expected_params = {
  15357. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  15358. EXPECT_EQ(request.path_params, expected_params);
  15359. }
  15360. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  15361. const auto pattern = "/prefix:suffix";
  15362. detail::PathParamsMatcher matcher(pattern);
  15363. Request request;
  15364. request.path = "/prefix:suffix";
  15365. ASSERT_TRUE(matcher.match(request));
  15366. const std::unordered_map<std::string, std::string> expected_params = {};
  15367. EXPECT_EQ(request.path_params, expected_params);
  15368. }
  15369. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  15370. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  15371. // calling thread's stack on a long enough path for a quantified pattern;
  15372. // RegexMatcher must refuse to run regex matching on paths beyond
  15373. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  15374. detail::RegexMatcher matcher("/files/(.*)");
  15375. Request within_limit;
  15376. within_limit.path = "/files/" + std::string(10, 'A');
  15377. EXPECT_TRUE(matcher.match(within_limit));
  15378. Request over_limit;
  15379. over_limit.path =
  15380. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  15381. EXPECT_FALSE(matcher.match(over_limit));
  15382. }
  15383. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  15384. Server svr;
  15385. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  15386. res.set_content("ok", "text/plain");
  15387. });
  15388. auto port = svr.bind_to_any_port(HOST);
  15389. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15390. auto se = detail::scope_exit([&] {
  15391. svr.stop();
  15392. thread.join();
  15393. ASSERT_FALSE(svr.is_running());
  15394. });
  15395. svr.wait_until_ready();
  15396. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  15397. // request URI limit; this used to be able to crash the process.
  15398. std::string path =
  15399. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  15400. std::string req = "GET " + path +
  15401. " HTTP/1.1\r\n"
  15402. "Host: " +
  15403. std::string(HOST) + ":" + std::to_string(port) +
  15404. "\r\n"
  15405. "Connection: close\r\n"
  15406. "\r\n";
  15407. std::string response;
  15408. ASSERT_TRUE(send_request(5, req, &response, port));
  15409. EXPECT_NE(std::string::npos, response.find("404"));
  15410. }
  15411. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  15412. Server svr;
  15413. auto handler = [](const Request & /*req*/, Response &res) {
  15414. res.set_content("hit", "text/plain");
  15415. };
  15416. // No regex metacharacter, so this one is compared literally
  15417. svr.Get("/literal/route", handler);
  15418. // '.' is a regex metacharacter, so this one must keep regex semantics
  15419. svr.Get("/a.c", handler);
  15420. auto port = svr.bind_to_any_port(HOST);
  15421. std::thread t([&]() { svr.listen_after_bind(); });
  15422. auto se = detail::scope_exit([&] {
  15423. svr.stop();
  15424. t.join();
  15425. ASSERT_FALSE(svr.is_running());
  15426. });
  15427. svr.wait_until_ready();
  15428. Client cli(HOST, port);
  15429. struct {
  15430. const char *path;
  15431. int status;
  15432. } cases[] = {
  15433. {"/literal/route", StatusCode::OK_200},
  15434. {"/literal/routes", StatusCode::NotFound_404},
  15435. {"/literal/rout", StatusCode::NotFound_404},
  15436. {"/abc", StatusCode::OK_200},
  15437. {"/a.c", StatusCode::OK_200},
  15438. };
  15439. for (const auto &x : cases) {
  15440. auto res = cli.Get(x.path);
  15441. ASSERT_TRUE(res) << x.path;
  15442. EXPECT_EQ(x.status, res->status) << x.path;
  15443. }
  15444. }
  15445. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  15446. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  15447. // from exhausting the stack, so it must only constrain routes that actually
  15448. // run a regular expression. A literal route is matched by comparison and
  15449. // stays usable at any length.
  15450. Server svr;
  15451. const std::string pattern =
  15452. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  15453. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  15454. res.set_content("hit", "text/plain");
  15455. });
  15456. auto port = svr.bind_to_any_port(HOST);
  15457. std::thread t([&]() { svr.listen_after_bind(); });
  15458. auto se = detail::scope_exit([&] {
  15459. svr.stop();
  15460. t.join();
  15461. ASSERT_FALSE(svr.is_running());
  15462. });
  15463. svr.wait_until_ready();
  15464. Client cli(HOST, port);
  15465. auto res = cli.Get(pattern);
  15466. ASSERT_TRUE(res);
  15467. EXPECT_EQ(StatusCode::OK_200, res->status);
  15468. }
  15469. TEST(ParseUrlTest, VariousPatterns) {
  15470. {
  15471. detail::UrlComponents uc;
  15472. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  15473. EXPECT_EQ("http", uc.scheme);
  15474. EXPECT_EQ("example.com", uc.host);
  15475. EXPECT_EQ("8080", uc.port);
  15476. EXPECT_EQ("/path", uc.path);
  15477. EXPECT_EQ("?q=1", uc.query);
  15478. }
  15479. {
  15480. detail::UrlComponents uc;
  15481. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  15482. EXPECT_EQ("https", uc.scheme);
  15483. EXPECT_EQ("example.com", uc.host);
  15484. EXPECT_TRUE(uc.port.empty());
  15485. EXPECT_EQ("/path", uc.path);
  15486. }
  15487. {
  15488. detail::UrlComponents uc;
  15489. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  15490. EXPECT_EQ("::1", uc.host);
  15491. EXPECT_EQ("8080", uc.port);
  15492. EXPECT_EQ("/path", uc.path);
  15493. }
  15494. {
  15495. detail::UrlComponents uc;
  15496. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  15497. }
  15498. {
  15499. // Bytes after the IPv6 literal must be a delimiter, not folded into
  15500. // the path while the connection still targets the bracketed host.
  15501. detail::UrlComponents uc;
  15502. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  15503. }
  15504. {
  15505. detail::UrlComponents uc;
  15506. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  15507. }
  15508. {
  15509. detail::UrlComponents uc;
  15510. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15511. EXPECT_EQ("::1", uc.host);
  15512. EXPECT_TRUE(uc.port.empty());
  15513. EXPECT_EQ("/path", uc.path);
  15514. }
  15515. {
  15516. detail::UrlComponents uc;
  15517. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15518. EXPECT_TRUE(uc.scheme.empty());
  15519. EXPECT_EQ("example.com", uc.host);
  15520. EXPECT_EQ("/path", uc.path);
  15521. EXPECT_EQ("?q=1", uc.query);
  15522. }
  15523. {
  15524. detail::UrlComponents uc;
  15525. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15526. EXPECT_TRUE(uc.host.empty());
  15527. EXPECT_EQ("/path", uc.path);
  15528. EXPECT_EQ("?q=1", uc.query);
  15529. }
  15530. {
  15531. detail::UrlComponents uc;
  15532. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15533. EXPECT_EQ("example.com", uc.host);
  15534. EXPECT_EQ("8080", uc.port);
  15535. }
  15536. {
  15537. // Unix socket path — must not be parsed as host
  15538. detail::UrlComponents uc;
  15539. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15540. EXPECT_TRUE(uc.host.empty());
  15541. }
  15542. {
  15543. detail::UrlComponents uc;
  15544. ASSERT_TRUE(detail::parse_url("", uc));
  15545. EXPECT_TRUE(uc.host.empty());
  15546. EXPECT_TRUE(uc.path.empty());
  15547. }
  15548. {
  15549. detail::UrlComponents uc;
  15550. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15551. }
  15552. {
  15553. detail::UrlComponents uc;
  15554. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15555. }
  15556. {
  15557. // Accepted by parse_url; callers restrict to http/https
  15558. detail::UrlComponents uc;
  15559. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15560. EXPECT_EQ("ftp", uc.scheme);
  15561. }
  15562. {
  15563. detail::UrlComponents uc;
  15564. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15565. }
  15566. {
  15567. detail::UrlComponents uc;
  15568. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15569. }
  15570. }
  15571. TEST(ParseUrlTest, FragmentHandling) {
  15572. {
  15573. detail::UrlComponents uc;
  15574. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15575. EXPECT_EQ("/path", uc.path);
  15576. EXPECT_TRUE(uc.query.empty());
  15577. }
  15578. {
  15579. detail::UrlComponents uc;
  15580. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15581. EXPECT_TRUE(uc.path.empty());
  15582. EXPECT_TRUE(uc.query.empty());
  15583. }
  15584. }
  15585. TEST(ParseUrlTest, UserinfoHandling) {
  15586. // Userinfo with @ but no colon — host includes @
  15587. detail::UrlComponents uc;
  15588. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15589. EXPECT_EQ("user@host.com", uc.host);
  15590. EXPECT_EQ("/path", uc.path);
  15591. }
  15592. TEST(ParseUrlTest, IPv6EdgeCases) {
  15593. {
  15594. detail::UrlComponents uc;
  15595. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15596. EXPECT_TRUE(uc.scheme.empty());
  15597. EXPECT_EQ("::1", uc.host);
  15598. EXPECT_EQ("8080", uc.port);
  15599. }
  15600. {
  15601. // Zone ID '%25' is not in [a-fA-F0-9:]
  15602. detail::UrlComponents uc;
  15603. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15604. }
  15605. }
  15606. TEST(ParseUrlTest, SchemeEdgeCases) {
  15607. {
  15608. detail::UrlComponents uc;
  15609. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15610. }
  15611. {
  15612. detail::UrlComponents uc;
  15613. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15614. }
  15615. {
  15616. detail::UrlComponents uc;
  15617. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15618. }
  15619. }
  15620. TEST(ParseUrlTest, PortEdgeCases) {
  15621. {
  15622. detail::UrlComponents uc;
  15623. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15624. EXPECT_TRUE(uc.port.empty());
  15625. EXPECT_EQ("/path", uc.path);
  15626. }
  15627. {
  15628. // parse_url accepts any port string; validation is done by parse_port
  15629. detail::UrlComponents uc;
  15630. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15631. EXPECT_EQ("abc", uc.port);
  15632. }
  15633. }
  15634. TEST(ParseUrlTest, WebSocketPatterns) {
  15635. {
  15636. detail::UrlComponents uc;
  15637. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15638. EXPECT_EQ("ws", uc.scheme);
  15639. EXPECT_EQ("echo.example.com", uc.host);
  15640. EXPECT_EQ("8080", uc.port);
  15641. EXPECT_EQ("/ws", uc.path);
  15642. }
  15643. {
  15644. detail::UrlComponents uc;
  15645. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15646. EXPECT_EQ("wss", uc.scheme);
  15647. EXPECT_EQ("echo.example.com", uc.host);
  15648. EXPECT_TRUE(uc.port.empty());
  15649. EXPECT_EQ("/ws", uc.path);
  15650. }
  15651. }
  15652. TEST(ParseUrlTest, QueryOnly) {
  15653. detail::UrlComponents uc;
  15654. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15655. EXPECT_TRUE(uc.host.empty());
  15656. EXPECT_TRUE(uc.path.empty());
  15657. EXPECT_EQ("?q=1&r=2", uc.query);
  15658. }
  15659. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15660. detail::UrlComponents uc;
  15661. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15662. EXPECT_TRUE(uc.scheme.empty());
  15663. EXPECT_EQ("example.com", uc.host);
  15664. EXPECT_EQ("443", uc.port);
  15665. EXPECT_EQ("/path", uc.path);
  15666. }
  15667. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15668. // If ipv6 regex working, regex match codepath is taken.
  15669. // else port will default to 80 in Client impl
  15670. int clientImplMagicPort = 80;
  15671. int port = 4321;
  15672. // above ports must be different to avoid false negative
  15673. EXPECT_NE(clientImplMagicPort, port);
  15674. std::string ipV6TestURL = "http://[ff06::c3]";
  15675. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15676. CLIENT_PRIVATE_KEY_FILE);
  15677. EXPECT_EQ(cli.port(), port);
  15678. }
  15679. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15680. auto file_path = "./www/dir/index.html";
  15681. auto dir_path = "./www/dir";
  15682. detail::FileStat stat_file(file_path);
  15683. EXPECT_TRUE(stat_file.is_file());
  15684. EXPECT_FALSE(stat_file.is_dir());
  15685. detail::FileStat stat_dir(dir_path);
  15686. EXPECT_FALSE(stat_dir.is_file());
  15687. EXPECT_TRUE(stat_dir.is_dir());
  15688. }
  15689. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15690. // IPv4 with default HTTP port (80)
  15691. EXPECT_EQ("example.com",
  15692. detail::make_host_and_port_string("example.com", 80, false));
  15693. // IPv4 with default HTTPS port (443)
  15694. EXPECT_EQ("example.com",
  15695. detail::make_host_and_port_string("example.com", 443, true));
  15696. // IPv4 with non-default HTTP port
  15697. EXPECT_EQ("example.com:8080",
  15698. detail::make_host_and_port_string("example.com", 8080, false));
  15699. // IPv4 with non-default HTTPS port
  15700. EXPECT_EQ("example.com:8443",
  15701. detail::make_host_and_port_string("example.com", 8443, true));
  15702. // IPv6 with default HTTP port (80)
  15703. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15704. // IPv6 with default HTTPS port (443)
  15705. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15706. // IPv6 with non-default HTTP port
  15707. EXPECT_EQ("[::1]:8080",
  15708. detail::make_host_and_port_string("::1", 8080, false));
  15709. // IPv6 with non-default HTTPS port
  15710. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15711. // IPv6 full address with default port
  15712. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15713. detail::make_host_and_port_string(
  15714. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15715. // IPv6 full address with non-default port
  15716. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15717. detail::make_host_and_port_string(
  15718. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15719. // IPv6 localhost with non-default port
  15720. EXPECT_EQ("[::1]:3000",
  15721. detail::make_host_and_port_string("::1", 3000, false));
  15722. // IPv6 with zone ID (link-local address) with default port
  15723. EXPECT_EQ("[fe80::1%eth0]",
  15724. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15725. // IPv6 with zone ID (link-local address) with non-default port
  15726. EXPECT_EQ("[fe80::1%eth0]:8080",
  15727. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15728. // Edge case: Port 443 with is_ssl=false (should add port)
  15729. EXPECT_EQ("example.com:443",
  15730. detail::make_host_and_port_string("example.com", 443, false));
  15731. // Edge case: Port 80 with is_ssl=true (should add port)
  15732. EXPECT_EQ("example.com:80",
  15733. detail::make_host_and_port_string("example.com", 80, true));
  15734. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15735. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15736. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15737. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15738. // Security fix: Already bracketed IPv6 should not get double brackets
  15739. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15740. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15741. EXPECT_EQ("[::1]:8080",
  15742. detail::make_host_and_port_string("[::1]", 8080, false));
  15743. EXPECT_EQ("[2001:db8::1]:8080",
  15744. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15745. EXPECT_EQ("[fe80::1%eth0]",
  15746. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15747. EXPECT_EQ("[fe80::1%eth0]:8080",
  15748. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15749. // Edge case: Empty host (should return as-is)
  15750. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15751. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15752. // This is a known limitation but shouldn't crash
  15753. EXPECT_EQ("[host:name]",
  15754. detail::make_host_and_port_string("host:name", 80, false));
  15755. // Port number edge cases (no validation, but should not crash)
  15756. EXPECT_EQ("example.com:0",
  15757. detail::make_host_and_port_string("example.com", 0, false));
  15758. EXPECT_EQ("example.com:-1",
  15759. detail::make_host_and_port_string("example.com", -1, false));
  15760. EXPECT_EQ("example.com:65535",
  15761. detail::make_host_and_port_string("example.com", 65535, false));
  15762. EXPECT_EQ("example.com:65536",
  15763. detail::make_host_and_port_string("example.com", 65536, false));
  15764. }
  15765. #ifdef CPPHTTPLIB_SSL_ENABLED
  15766. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15767. httplib::SSLClient cli("roblox.com", 443);
  15768. cli.set_follow_location(true);
  15769. auto res = cli.Get("/");
  15770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15771. EXPECT_EQ(StatusCode::OK_200, res->status);
  15772. }
  15773. #endif
  15774. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15775. Server svr;
  15776. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15777. EXPECT_EQ(res.status, 400);
  15778. });
  15779. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15780. auto se = detail::scope_exit([&] {
  15781. svr.stop();
  15782. thread.join();
  15783. ASSERT_FALSE(svr.is_running());
  15784. });
  15785. svr.wait_until_ready();
  15786. Client cli(HOST, PORT);
  15787. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15788. }
  15789. TEST(InvalidHeaderCharsTest, is_field_name) {
  15790. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15791. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15792. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15793. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15794. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15795. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15796. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15797. EXPECT_FALSE(detail::fields::is_field_name(""));
  15798. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15799. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15800. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15801. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15802. }
  15803. TEST(InvalidHeaderCharsTest, is_field_value) {
  15804. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15805. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15806. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15807. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15808. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15809. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15810. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15811. EXPECT_TRUE(detail::fields::is_field_value(""));
  15812. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15813. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15814. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15815. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15816. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15817. }
  15818. TEST(InvalidHeaderCharsTest, OnServer) {
  15819. Server svr;
  15820. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15821. std::string header = "Not Set";
  15822. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15823. res.set_header(header, "value");
  15824. res.set_content("Page Content Page Content", "text/plain");
  15825. });
  15826. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15827. std::string header = "Not Set";
  15828. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15829. res.set_header("X-Test", header);
  15830. res.set_content("Page Content Page Content", "text/plain");
  15831. });
  15832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15833. auto se = detail::scope_exit([&] {
  15834. svr.stop();
  15835. thread.join();
  15836. ASSERT_FALSE(svr.is_running());
  15837. });
  15838. svr.wait_until_ready();
  15839. Client cli(HOST, PORT);
  15840. {
  15841. auto res = cli.Get(
  15842. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15844. EXPECT_EQ("Page Content Page Content", res->body);
  15845. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15846. }
  15847. {
  15848. auto res = cli.Get(
  15849. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15851. EXPECT_EQ("Page Content Page Content", res->body);
  15852. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15853. }
  15854. }
  15855. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15856. auto handled = false;
  15857. Server svr;
  15858. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15859. thread t = thread([&] { svr.listen(HOST, PORT); });
  15860. auto se = detail::scope_exit([&] {
  15861. svr.stop();
  15862. t.join();
  15863. ASSERT_FALSE(svr.is_running());
  15864. ASSERT_FALSE(handled);
  15865. });
  15866. svr.wait_until_ready();
  15867. auto req = "POST /test HTTP/1.1\r\n"
  15868. "Content-Length: x\r\n"
  15869. "\r\n";
  15870. std::string response;
  15871. ASSERT_TRUE(send_request(1, req, &response));
  15872. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15873. response.substr(0, response.find("\r\n")));
  15874. }
  15875. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15876. // case-insensitive, and a server that receives a 100-continue expectation in
  15877. // an HTTP/1.0 request MUST ignore it.
  15878. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15879. std::string response;
  15880. ASSERT_TRUE(send_request(1, req, &response, port));
  15881. *got_100 = response.find("100 Continue") != std::string::npos;
  15882. }
  15883. class ExpectTokenTest : public ::testing::Test {
  15884. protected:
  15885. void SetUp() override {
  15886. svr_.Post("/p", [](const Request &, Response &res) {
  15887. res.set_content("ok", "text/plain");
  15888. });
  15889. port_ = svr_.bind_to_any_port(HOST);
  15890. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15891. svr_.wait_until_ready();
  15892. }
  15893. void TearDown() override {
  15894. svr_.stop();
  15895. if (thread_.joinable()) { thread_.join(); }
  15896. }
  15897. std::string request(const char *version, const char *expect_value) const {
  15898. return std::string("POST /p ") + version +
  15899. "\r\n"
  15900. "Host: localhost\r\n"
  15901. "Content-Length: 2\r\n"
  15902. "Connection: close\r\n"
  15903. "Expect: " +
  15904. expect_value +
  15905. "\r\n"
  15906. "\r\n"
  15907. "hi";
  15908. }
  15909. Server svr_;
  15910. int port_ = 0;
  15911. thread thread_;
  15912. };
  15913. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15914. bool got_100 = false;
  15915. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15916. EXPECT_TRUE(got_100);
  15917. }
  15918. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15919. bool got_100 = true;
  15920. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15921. EXPECT_FALSE(got_100);
  15922. }
  15923. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15924. bool got_100 = false;
  15925. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15926. EXPECT_TRUE(got_100);
  15927. }
  15928. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15929. bool got_100 = false;
  15930. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15931. EXPECT_TRUE(got_100);
  15932. }
  15933. // `100 Continue` is sent only when the server starts reading the body, so a
  15934. // request rejected before that never invites the client to send it. The
  15935. // requests below carry the expectation but withhold the body, as a client
  15936. // waiting for `100 Continue` would.
  15937. // A POST that expects `100 Continue` and withholds its two-byte body.
  15938. static std::string expect_headers_only(const std::string &path) {
  15939. return "POST " + path +
  15940. " HTTP/1.1\r\n"
  15941. "Host: localhost\r\n"
  15942. "Content-Length: 2\r\n"
  15943. "Expect: 100-continue\r\n"
  15944. "\r\n";
  15945. }
  15946. class ExpectLazyContinueTest : public ::testing::Test {
  15947. protected:
  15948. void SetUp() override {
  15949. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15950. if (req.path == "/pre-routing") {
  15951. res.status = StatusCode::Unauthorized_401;
  15952. return Server::HandlerResponse::Handled;
  15953. }
  15954. return Server::HandlerResponse::Unhandled;
  15955. });
  15956. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15957. if (req.matched_route == "/pre-request") {
  15958. res.status = StatusCode::Forbidden_403;
  15959. return Server::HandlerResponse::Handled;
  15960. }
  15961. return Server::HandlerResponse::Unhandled;
  15962. });
  15963. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15964. res.set_content("ok", "text/plain");
  15965. });
  15966. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15967. res.set_content("ok", "text/plain");
  15968. });
  15969. svr_.Post("/reader-used", [](const Request &, Response &res,
  15970. const ContentReader &content_reader) {
  15971. std::string body;
  15972. content_reader([&](const char *data, size_t len) {
  15973. body.append(data, len);
  15974. return true;
  15975. });
  15976. res.set_content(body, "text/plain");
  15977. });
  15978. svr_.Post("/reader-unused",
  15979. [](const Request &, Response &res, const ContentReader &) {
  15980. res.set_content("ignored", "text/plain");
  15981. });
  15982. port_ = svr_.bind_to_any_port(HOST);
  15983. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15984. svr_.wait_until_ready();
  15985. }
  15986. void TearDown() override {
  15987. svr_.stop();
  15988. if (thread_.joinable()) { thread_.join(); }
  15989. }
  15990. // Sends `req` and reads until the server closes the connection. Returns
  15991. // false if the read had to wait for the client-side timeout instead.
  15992. bool send_until_closed(const std::string &req, std::string *resp) const {
  15993. auto start = std::chrono::steady_clock::now();
  15994. if (!send_request(3, req, resp, port_)) { return false; }
  15995. auto elapsed = std::chrono::steady_clock::now() - start;
  15996. return elapsed < std::chrono::seconds(2);
  15997. }
  15998. // The final response comes without `100 Continue`, and the server closes
  15999. // the connection since the body may or may not follow.
  16000. void expect_final_without_interim(const std::string &path,
  16001. const char *status_line) const {
  16002. std::string resp;
  16003. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16004. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16005. EXPECT_EQ(0u, resp.find(status_line));
  16006. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16007. }
  16008. Server svr_;
  16009. int port_ = 0;
  16010. thread thread_;
  16011. };
  16012. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16013. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16014. }
  16015. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16016. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16017. }
  16018. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16019. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16020. }
  16021. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16022. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16023. }
  16024. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16025. // The body follows once `100 Continue` has had time to arrive.
  16026. auto req = expect_headers_only("/reader-used");
  16027. req.insert(req.size() - 2, "Connection: close\r\n");
  16028. std::string resp;
  16029. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16030. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16031. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16032. EXPECT_NE(std::string::npos, resp.find("hi"));
  16033. }
  16034. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16035. // Large enough for the client to add `Expect: 100-continue` itself.
  16036. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16037. std::atomic<bool> body_sent{false};
  16038. Client cli(HOST, port_);
  16039. auto res = cli.Post(
  16040. "/pre-request", length,
  16041. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16042. body_sent = true;
  16043. std::string chunk(len, 'x');
  16044. sink.write(chunk.data(), chunk.size());
  16045. return true;
  16046. },
  16047. "application/octet-stream");
  16048. ASSERT_TRUE(res);
  16049. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16050. EXPECT_FALSE(body_sent);
  16051. }
  16052. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16053. Server svr;
  16054. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16055. return StatusCode::ExpectationFailed_417;
  16056. });
  16057. svr.Post("/p", [](const Request &, Response &res) {
  16058. res.set_content("ok", "text/plain");
  16059. });
  16060. auto port = svr.bind_to_any_port(HOST);
  16061. thread t = thread([&] { svr.listen_after_bind(); });
  16062. auto se = detail::scope_exit([&] {
  16063. svr.stop();
  16064. t.join();
  16065. });
  16066. svr.wait_until_ready();
  16067. std::string resp;
  16068. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16069. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16070. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16071. // Exactly one response: the route handler must not run after the 417.
  16072. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16073. }
  16074. #ifndef _WIN32
  16075. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16076. static constexpr char reject[] = "Unauthorized";
  16077. static constexpr char accept[] = "Upload accepted";
  16078. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16079. Server svr;
  16080. svr.set_expect_100_continue_handler(
  16081. [](const Request & /*req*/, Response &res) {
  16082. res.status = StatusCode::Unauthorized_401;
  16083. res.set_content(reject, "text/plain");
  16084. return res.status;
  16085. });
  16086. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16087. res.set_content(accept, "text/plain");
  16088. });
  16089. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16090. auto se = detail::scope_exit([&] {
  16091. svr.stop();
  16092. thread.join();
  16093. ASSERT_FALSE(svr.is_running());
  16094. });
  16095. svr.wait_until_ready();
  16096. {
  16097. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16098. curl_easy_init(), &curl_easy_cleanup};
  16099. ASSERT_NE(curl, nullptr);
  16100. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16101. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16102. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16103. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16104. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16105. &curl_slist_free_all};
  16106. ASSERT_NE(list, nullptr);
  16107. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16108. struct read_data {
  16109. size_t read_size;
  16110. size_t total_size;
  16111. } data = {0, total_size};
  16112. using read_callback_t =
  16113. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16114. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16115. void *userdata) -> size_t {
  16116. read_data *d = (read_data *)userdata;
  16117. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16118. std::fill_n(ptr, size * nmemb, 'A');
  16119. d->read_size += size * nmemb;
  16120. return size * nmemb;
  16121. };
  16122. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16123. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16124. std::vector<char> buffer;
  16125. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16126. using write_callback_t =
  16127. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16128. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16129. void *userdata) -> size_t {
  16130. std::vector<char> *buf = (std::vector<char> *)userdata;
  16131. buf->reserve(buf->size() + size * nmemb + 1);
  16132. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16133. return size * nmemb;
  16134. };
  16135. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16136. {
  16137. const auto res = curl_easy_perform(curl.get());
  16138. ASSERT_EQ(res, CURLE_OK);
  16139. }
  16140. {
  16141. auto response_code = long{};
  16142. const auto res =
  16143. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16144. ASSERT_EQ(res, CURLE_OK);
  16145. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16146. }
  16147. {
  16148. auto dl = curl_off_t{};
  16149. const auto res =
  16150. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16151. ASSERT_EQ(res, CURLE_OK);
  16152. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16153. }
  16154. {
  16155. buffer.push_back('\0');
  16156. ASSERT_STRCASEEQ(buffer.data(), reject);
  16157. }
  16158. }
  16159. }
  16160. #endif
  16161. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16162. // Regression test for #2458.
  16163. //
  16164. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16165. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16166. // ticket can make the client socket spuriously readable during the
  16167. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16168. // the client withholds the body and then blocks reading a response that never
  16169. // comes, failing with `Failed to read connection`.
  16170. //
  16171. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16172. // within the timeout. This raw OpenSSL server deliberately never sends
  16173. // `100 Continue`; the client must still deliver the body and receive 200.
  16174. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16175. signal(SIGPIPE, SIG_IGN);
  16176. const auto port = PORT + 4;
  16177. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16178. ASSERT_NE(srv, INVALID_SOCKET);
  16179. int opt = 1;
  16180. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16181. sockaddr_in addr{};
  16182. addr.sin_family = AF_INET;
  16183. addr.sin_port = htons(static_cast<uint16_t>(port));
  16184. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16185. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16186. ASSERT_EQ(0, ::listen(srv, 1));
  16187. std::atomic<size_t> server_body_bytes{0};
  16188. auto server_thread = std::thread([&] {
  16189. sockaddr_in cli_addr{};
  16190. socklen_t cli_len = sizeof(cli_addr);
  16191. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16192. if (cli == INVALID_SOCKET) { return; }
  16193. // Bound the lifetime of the server side so a buggy client (which never
  16194. // sends the body) cannot make this thread block forever on join.
  16195. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16196. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16197. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16198. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16199. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16200. SSL *ssl = SSL_new(ctx);
  16201. SSL_set_fd(ssl, static_cast<int>(cli));
  16202. if (SSL_accept(ssl) > 0) {
  16203. // Read the request headers. Reading here also flushes the TLS 1.3
  16204. // session tickets to the client. Deliberately do NOT send
  16205. // `100 Continue`.
  16206. std::string buf;
  16207. char tmp[1024];
  16208. while (buf.find("\r\n\r\n") == std::string::npos) {
  16209. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16210. if (n <= 0) { break; }
  16211. buf.append(tmp, static_cast<size_t>(n));
  16212. }
  16213. // A correct client sends the body now; count what arrives.
  16214. auto pos = buf.find("\r\n\r\n");
  16215. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16216. while (body < 4096) {
  16217. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16218. if (n <= 0) { break; }
  16219. body += static_cast<size_t>(n);
  16220. }
  16221. server_body_bytes = body;
  16222. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16223. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16224. SSL_shutdown(ssl);
  16225. }
  16226. SSL_free(ssl);
  16227. detail::close_socket(cli);
  16228. SSL_CTX_free(ctx);
  16229. });
  16230. auto se = detail::scope_exit([&] {
  16231. server_thread.join();
  16232. detail::close_socket(srv);
  16233. });
  16234. SSLClient cli("127.0.0.1", port);
  16235. cli.enable_server_certificate_verification(false);
  16236. cli.set_connection_timeout(5, 0);
  16237. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16238. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16239. std::string body(4096, 'A');
  16240. auto res = cli.Put("/api/test", body, "application/json");
  16241. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16242. EXPECT_EQ(StatusCode::OK_200, res->status);
  16243. EXPECT_EQ(body.size(), server_body_bytes.load());
  16244. }
  16245. #endif
  16246. template <typename S, typename C>
  16247. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  16248. svr.Get("/stream", [&](const Request &, Response &res) {
  16249. auto data = new std::string("01234567890123456789");
  16250. res.set_content_provider(
  16251. data->size(), "text/plain",
  16252. [&, data](size_t offset, size_t length, DataSink &sink) {
  16253. const size_t DATA_CHUNK_SIZE = 4;
  16254. const auto &d = *data;
  16255. std::this_thread::sleep_for(std::chrono::seconds(1));
  16256. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  16257. return true;
  16258. },
  16259. [data](bool success) {
  16260. EXPECT_FALSE(success);
  16261. delete data;
  16262. });
  16263. });
  16264. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  16265. auto i = new size_t(0);
  16266. res.set_content_provider(
  16267. "text/plain",
  16268. [i](size_t, DataSink &sink) {
  16269. if (*i < 5) {
  16270. std::this_thread::sleep_for(std::chrono::seconds(1));
  16271. sink.write("abcd", 4);
  16272. (*i)++;
  16273. } else {
  16274. sink.done();
  16275. }
  16276. return true;
  16277. },
  16278. [i](bool success) {
  16279. EXPECT_FALSE(success);
  16280. delete i;
  16281. });
  16282. });
  16283. svr.Get("/chunked", [&](const Request &, Response &res) {
  16284. auto i = new size_t(0);
  16285. res.set_chunked_content_provider(
  16286. "text/plain",
  16287. [i](size_t, DataSink &sink) {
  16288. if (*i < 5) {
  16289. std::this_thread::sleep_for(std::chrono::seconds(1));
  16290. sink.os << "abcd";
  16291. (*i)++;
  16292. } else {
  16293. sink.done();
  16294. }
  16295. return true;
  16296. },
  16297. [i](bool success) {
  16298. EXPECT_FALSE(success);
  16299. delete i;
  16300. });
  16301. });
  16302. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  16303. auto se = detail::scope_exit([&] {
  16304. svr.stop();
  16305. listen_thread.join();
  16306. ASSERT_FALSE(svr.is_running());
  16307. });
  16308. svr.wait_until_ready();
  16309. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  16310. {
  16311. auto start = std::chrono::steady_clock::now();
  16312. auto res = cli.Get("/stream");
  16313. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16314. std::chrono::steady_clock::now() - start)
  16315. .count();
  16316. ASSERT_FALSE(res);
  16317. EXPECT_EQ(Error::Read, res.error());
  16318. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16319. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16320. }
  16321. {
  16322. auto start = std::chrono::steady_clock::now();
  16323. auto res = cli.Get("/stream_without_length");
  16324. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16325. std::chrono::steady_clock::now() - start)
  16326. .count();
  16327. ASSERT_FALSE(res);
  16328. EXPECT_EQ(Error::Read, res.error());
  16329. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16330. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16331. }
  16332. {
  16333. auto start = std::chrono::steady_clock::now();
  16334. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  16335. EXPECT_EQ("abcd", string(data, data_length));
  16336. return true;
  16337. });
  16338. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  16339. std::chrono::steady_clock::now() - start)
  16340. .count();
  16341. ASSERT_FALSE(res);
  16342. EXPECT_EQ(Error::Read, res.error());
  16343. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  16344. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  16345. }
  16346. }
  16347. TEST(MaxTimeoutTest, ContentStream) {
  16348. time_t timeout = 2000;
  16349. time_t threshold = 200;
  16350. Server svr;
  16351. Client cli("localhost", PORT);
  16352. max_timeout_test(svr, cli, timeout, threshold);
  16353. }
  16354. #ifdef CPPHTTPLIB_SSL_ENABLED
  16355. TEST(MaxTimeoutTest, ContentStreamSSL) {
  16356. time_t timeout = 2000;
  16357. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  16358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16359. SSLClient cli("localhost", PORT);
  16360. cli.enable_server_certificate_verification(false);
  16361. max_timeout_test(svr, cli, timeout, threshold);
  16362. }
  16363. #endif
  16364. class EventDispatcher {
  16365. public:
  16366. EventDispatcher() {}
  16367. bool wait_event(DataSink *sink) {
  16368. unique_lock<mutex> lk(m_);
  16369. int id = id_;
  16370. // Wait with timeout to prevent hanging if client disconnects
  16371. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  16372. [&] { return cid_ == id; })) {
  16373. return false; // Timeout occurred
  16374. }
  16375. sink->write(message_.data(), message_.size());
  16376. return true;
  16377. }
  16378. void send_event(const string &message) {
  16379. lock_guard<mutex> lk(m_);
  16380. cid_ = id_++;
  16381. message_ = message;
  16382. cv_.notify_all();
  16383. }
  16384. private:
  16385. mutex m_;
  16386. condition_variable cv_;
  16387. atomic_int id_{0};
  16388. atomic_int cid_{-1};
  16389. string message_;
  16390. };
  16391. TEST(ClientInThreadTest, Issue2068) {
  16392. EventDispatcher ed;
  16393. Server svr;
  16394. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  16395. res.set_chunked_content_provider("text/event-stream",
  16396. [&](size_t /*offset*/, DataSink &sink) {
  16397. return ed.wait_event(&sink);
  16398. });
  16399. });
  16400. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  16401. svr.wait_until_ready();
  16402. thread event_thread([&] {
  16403. int id = 0;
  16404. while (svr.is_running()) {
  16405. this_thread::sleep_for(chrono::milliseconds(500));
  16406. std::stringstream ss;
  16407. ss << "data: " << id << "\n\n";
  16408. ed.send_event(ss.str());
  16409. id++;
  16410. }
  16411. });
  16412. auto se = detail::scope_exit([&] {
  16413. svr.stop();
  16414. listen_thread.join();
  16415. event_thread.join();
  16416. ASSERT_FALSE(svr.is_running());
  16417. });
  16418. {
  16419. auto client = detail::make_unique<Client>(HOST, PORT);
  16420. client->set_read_timeout(std::chrono::minutes(10));
  16421. std::atomic<bool> stop{false};
  16422. std::thread t([&] {
  16423. client->Get("/event1",
  16424. [&](const char *, size_t) -> bool { return !stop; });
  16425. });
  16426. std::this_thread::sleep_for(std::chrono::seconds(2));
  16427. stop = true;
  16428. client->stop();
  16429. t.join();
  16430. // Reset client after thread has finished
  16431. client.reset();
  16432. }
  16433. }
  16434. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  16435. auto handled = false;
  16436. Server svr;
  16437. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  16438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16439. auto se = detail::scope_exit([&] {
  16440. svr.stop();
  16441. t.join();
  16442. ASSERT_FALSE(svr.is_running());
  16443. ASSERT_FALSE(handled);
  16444. });
  16445. svr.wait_until_ready();
  16446. // Two Content-Length headers with different values — must be rejected
  16447. auto req = "POST /test HTTP/1.1\r\n"
  16448. "Content-Length: 5\r\n"
  16449. "Content-Length: 10\r\n"
  16450. "\r\n"
  16451. "hello";
  16452. std::string response;
  16453. ASSERT_TRUE(send_request(1, req, &response));
  16454. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16455. response.substr(0, response.find("\r\n")));
  16456. }
  16457. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  16458. auto handled = false;
  16459. Server svr;
  16460. svr.Post("/test", [&](const Request &, Response &res) {
  16461. handled = true;
  16462. res.set_content("ok", "text/plain");
  16463. });
  16464. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16465. auto se = detail::scope_exit([&] {
  16466. svr.stop();
  16467. t.join();
  16468. ASSERT_FALSE(svr.is_running());
  16469. ASSERT_TRUE(handled);
  16470. });
  16471. svr.wait_until_ready();
  16472. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  16473. auto req = "POST /test HTTP/1.1\r\n"
  16474. "Content-Length: 5\r\n"
  16475. "Content-Length: 5\r\n"
  16476. "\r\n"
  16477. "hello";
  16478. std::string response;
  16479. ASSERT_TRUE(send_request(1, req, &response));
  16480. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  16481. }
  16482. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  16483. Server svr;
  16484. svr.Get("/test", [](const Request &, Response &res) {
  16485. res.set_content("ok", "text/plain");
  16486. });
  16487. auto port = svr.bind_to_any_port(HOST);
  16488. thread t = thread([&] { svr.listen_after_bind(); });
  16489. auto se = detail::scope_exit([&] {
  16490. svr.stop();
  16491. t.join();
  16492. ASSERT_FALSE(svr.is_running());
  16493. });
  16494. svr.wait_until_ready();
  16495. auto status_line = [&](const std::string &host_lines) {
  16496. std::string res;
  16497. send_request(
  16498. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  16499. &res, port);
  16500. return res.substr(0, res.find("\r\n"));
  16501. };
  16502. const char *accepted[] = {
  16503. "Host: localhost\r\n",
  16504. "Host: a.example:8080\r\n",
  16505. "Host: my_service\r\n",
  16506. "Host: [::1]:8080\r\n",
  16507. "Host: [fe80::1%25eth0]\r\n",
  16508. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  16509. };
  16510. for (auto host_lines : accepted) {
  16511. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  16512. }
  16513. const char *rejected[] = {
  16514. "Host: a.example\r\nHost: b.example\r\n",
  16515. "Host: a.example\r\nHost: a.example\r\n",
  16516. "Host: a@b.example\r\n",
  16517. "Host: a.example/b\r\n",
  16518. "Host: a.example\\b\r\n",
  16519. "Host: a.example?b\r\n",
  16520. "Host: a.example#b\r\n",
  16521. "Host: a.example b.example\r\n",
  16522. };
  16523. for (auto host_lines : rejected) {
  16524. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  16525. << host_lines;
  16526. }
  16527. }
  16528. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  16529. Server svr;
  16530. svr.Get("/", [](const Request &req, Response &res) {
  16531. EXPECT_EQ(2U, req.trailers.size());
  16532. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  16533. // Denied
  16534. EXPECT_FALSE(req.has_trailer("Content-Length"));
  16535. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  16536. // Accepted
  16537. EXPECT_TRUE(req.has_trailer("X-Hello"));
  16538. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  16539. EXPECT_TRUE(req.has_trailer("X-World"));
  16540. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  16541. res.set_content("ok", "text/plain");
  16542. });
  16543. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16544. auto se = detail::scope_exit([&] {
  16545. svr.stop();
  16546. t.join();
  16547. ASSERT_FALSE(svr.is_running());
  16548. });
  16549. svr.wait_until_ready();
  16550. const std::string req = "GET / HTTP/1.1\r\n"
  16551. "Transfer-Encoding: chunked\r\n"
  16552. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  16553. "\r\n"
  16554. "0\r\n"
  16555. "Content-Length: 10\r\n"
  16556. "Host: internal.local\r\n"
  16557. "Content-Type: malicious/content\r\n"
  16558. "Cookie: any\r\n"
  16559. "Set-Cookie: any\r\n"
  16560. "X-Forwarded-For: attacker.com\r\n"
  16561. "X-Real-Ip: 1.1.1.1\r\n"
  16562. "X-Hello: hello\r\n"
  16563. "X-World: world\r\n"
  16564. "\r\n";
  16565. std::string res;
  16566. ASSERT_TRUE(send_request(1, req, &res));
  16567. }
  16568. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16569. // several field lines, and the combined value is what has to be parsed. A
  16570. // Trailer field split across lines therefore declares every name it lists;
  16571. // reading only the first line silently drops the trailers the later lines
  16572. // declare. The prohibited-trailer filter still applies to every line.
  16573. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16574. Server svr;
  16575. size_t observed_trailer_count = 0;
  16576. std::string observed_hello;
  16577. std::string observed_world;
  16578. bool observed_content_length = true;
  16579. svr.Get("/", [&](const Request &req, Response &res) {
  16580. observed_trailer_count = req.trailers.size();
  16581. observed_hello = req.get_trailer_value("X-Hello");
  16582. observed_world = req.get_trailer_value("X-World");
  16583. observed_content_length = req.has_trailer("Content-Length");
  16584. res.set_content("ok", "text/plain");
  16585. });
  16586. auto port = svr.bind_to_any_port(HOST);
  16587. thread t = thread([&]() { svr.listen_after_bind(); });
  16588. auto se = detail::scope_exit([&] {
  16589. svr.stop();
  16590. t.join();
  16591. ASSERT_FALSE(svr.is_running());
  16592. });
  16593. svr.wait_until_ready();
  16594. const std::string req = "GET / HTTP/1.1\r\n"
  16595. "Transfer-Encoding: chunked\r\n"
  16596. "Trailer: X-Hello\r\n"
  16597. "Trailer: X-World, Content-Length\r\n"
  16598. "\r\n"
  16599. "0\r\n"
  16600. "X-Hello: hello\r\n"
  16601. "X-World: world\r\n"
  16602. "Content-Length: 10\r\n"
  16603. "\r\n";
  16604. std::string res;
  16605. ASSERT_TRUE(send_request(1, req, &res, port));
  16606. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16607. // Accepted: both field lines contribute to the declared set
  16608. EXPECT_EQ(2U, observed_trailer_count);
  16609. EXPECT_EQ(observed_hello, "hello");
  16610. EXPECT_EQ(observed_world, "world");
  16611. // Denied: a prohibited name stays prohibited on a later field line
  16612. EXPECT_FALSE(observed_content_length);
  16613. }
  16614. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16615. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16616. // unbounded run of fields that are never declared, because the counter would
  16617. // only advance for declared fields.
  16618. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16619. Server svr;
  16620. bool handler_called = false;
  16621. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16622. handler_called = true;
  16623. res.set_content("ok", "text/plain");
  16624. });
  16625. auto port = svr.bind_to_any_port(HOST);
  16626. thread t = thread([&]() { svr.listen_after_bind(); });
  16627. auto se = detail::scope_exit([&] {
  16628. svr.stop();
  16629. t.join();
  16630. ASSERT_FALSE(svr.is_running());
  16631. });
  16632. svr.wait_until_ready();
  16633. // Declare nothing, then send far more undeclared trailer fields than the
  16634. // header-count limit. Parsing must stop and reject the request rather than
  16635. // read every line.
  16636. std::string req = "GET / HTTP/1.1\r\n"
  16637. "Transfer-Encoding: chunked\r\n"
  16638. "\r\n"
  16639. "0\r\n";
  16640. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16641. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16642. }
  16643. req += "\r\n";
  16644. std::string res;
  16645. ASSERT_TRUE(send_request(1, req, &res, port));
  16646. // The request is rejected before the handler runs.
  16647. EXPECT_FALSE(handler_called);
  16648. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16649. }
  16650. // The set of declared trailer names is capped so a peer cannot grow it without
  16651. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16652. // declared past the cap is not honored, even if the field is actually sent.
  16653. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16654. Server svr;
  16655. // One name inside the cap and one past it, so the test tracks the cap rather
  16656. // than a fixed count.
  16657. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16658. const std::string within_cap_name = "X-T-0";
  16659. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16660. bool observed_within_cap = false;
  16661. bool observed_past_cap = false;
  16662. svr.Get("/", [&](const Request &req, Response &res) {
  16663. observed_within_cap = req.has_trailer(within_cap_name);
  16664. observed_past_cap = req.has_trailer(past_cap_name);
  16665. res.set_content("ok", "text/plain");
  16666. });
  16667. auto port = svr.bind_to_any_port(HOST);
  16668. thread t = thread([&]() { svr.listen_after_bind(); });
  16669. auto se = detail::scope_exit([&] {
  16670. svr.stop();
  16671. t.join();
  16672. ASSERT_FALSE(svr.is_running());
  16673. });
  16674. svr.wait_until_ready();
  16675. // Declare more trailer names than the cap in a single Trailer field, then
  16676. // actually send the first (within the cap) and the last (past it).
  16677. std::string trailer_decl = "Trailer: ";
  16678. for (int i = 0; i < declared_count; i++) {
  16679. if (i != 0) { trailer_decl += ", "; }
  16680. trailer_decl += "X-T-" + std::to_string(i);
  16681. }
  16682. trailer_decl += "\r\n";
  16683. const std::string req = "GET / HTTP/1.1\r\n"
  16684. "Transfer-Encoding: chunked\r\n" +
  16685. trailer_decl +
  16686. "\r\n"
  16687. "0\r\n" +
  16688. within_cap_name + ": a\r\n" + past_cap_name +
  16689. ": b\r\n"
  16690. "\r\n";
  16691. std::string res;
  16692. ASSERT_TRUE(send_request(1, req, &res, port));
  16693. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16694. // A name within the cap is honored; one declared past the cap is dropped.
  16695. EXPECT_TRUE(observed_within_cap);
  16696. EXPECT_FALSE(observed_past_cap);
  16697. }
  16698. // A direct client that is not listed in trusted_proxies must not be able to
  16699. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16700. // the peer address on the actual TCP connection determines whether the
  16701. // header is honored.
  16702. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16703. Server svr;
  16704. // Deliberately does NOT include the loopback address the test client
  16705. // actually connects from, so the direct connection is not a trusted proxy.
  16706. svr.set_trusted_proxies({"203.0.113.66"});
  16707. std::string observed_remote_addr;
  16708. svr.Get("/ip", [&](const Request &req, Response &res) {
  16709. observed_remote_addr = req.remote_addr;
  16710. res.set_content("ok", "text/plain");
  16711. });
  16712. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16713. auto se = detail::scope_exit([&] {
  16714. svr.stop();
  16715. t.join();
  16716. ASSERT_FALSE(svr.is_running());
  16717. });
  16718. svr.wait_until_ready();
  16719. Client cli(HOST, PORT);
  16720. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16722. EXPECT_EQ(StatusCode::OK_200, res->status);
  16723. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16724. // ignored entirely and the real connection-level address retained.
  16725. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16726. observed_remote_addr == "127.0.0.1");
  16727. }
  16728. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16729. Server svr;
  16730. std::string observed_remote_addr;
  16731. std::string observed_xff;
  16732. svr.Get("/ip", [&](const Request &req, Response &res) {
  16733. observed_remote_addr = req.remote_addr;
  16734. observed_xff = req.get_header_value("X-Forwarded-For");
  16735. res.set_content("ok", "text/plain");
  16736. });
  16737. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16738. auto se = detail::scope_exit([&] {
  16739. svr.stop();
  16740. t.join();
  16741. ASSERT_FALSE(svr.is_running());
  16742. });
  16743. svr.wait_until_ready();
  16744. Client cli(HOST, PORT);
  16745. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16747. EXPECT_EQ(StatusCode::OK_200, res->status);
  16748. EXPECT_EQ(observed_xff, "203.0.113.66");
  16749. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16750. observed_remote_addr == "127.0.0.1");
  16751. }
  16752. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16753. Server svr;
  16754. svr.set_trusted_proxies({"203.0.113.66"});
  16755. std::string observed_remote_addr;
  16756. std::string observed_xff;
  16757. svr.Get("/ip", [&](const Request &req, Response &res) {
  16758. observed_remote_addr = req.remote_addr;
  16759. observed_xff = req.get_header_value("X-Forwarded-For");
  16760. res.set_content("ok", "text/plain");
  16761. });
  16762. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16763. auto se = detail::scope_exit([&] {
  16764. svr.stop();
  16765. t.join();
  16766. ASSERT_FALSE(svr.is_running());
  16767. });
  16768. svr.wait_until_ready();
  16769. Client cli(HOST, PORT);
  16770. auto res = cli.Get("/ip");
  16771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16772. EXPECT_EQ(StatusCode::OK_200, res->status);
  16773. EXPECT_EQ(observed_xff, "");
  16774. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16775. observed_remote_addr == "127.0.0.1");
  16776. }
  16777. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16778. Server svr;
  16779. // Include the loopback address the test client actually connects from, so
  16780. // the direct connection itself is recognized as the trusted proxy hop.
  16781. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16782. std::string observed_remote_addr;
  16783. std::string observed_xff;
  16784. svr.Get("/ip", [&](const Request &req, Response &res) {
  16785. observed_remote_addr = req.remote_addr;
  16786. observed_xff = req.get_header_value("X-Forwarded-For");
  16787. res.set_content("ok", "text/plain");
  16788. });
  16789. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16790. auto se = detail::scope_exit([&] {
  16791. svr.stop();
  16792. t.join();
  16793. ASSERT_FALSE(svr.is_running());
  16794. });
  16795. svr.wait_until_ready();
  16796. Client cli(HOST, PORT);
  16797. auto res = cli.Get(
  16798. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16800. EXPECT_EQ(StatusCode::OK_200, res->status);
  16801. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16802. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16803. }
  16804. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16805. Server svr;
  16806. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16807. std::string observed_remote_addr;
  16808. std::string observed_xff;
  16809. svr.Get("/ip", [&](const Request &req, Response &res) {
  16810. observed_remote_addr = req.remote_addr;
  16811. observed_xff = req.get_header_value("X-Forwarded-For");
  16812. res.set_content("ok", "text/plain");
  16813. });
  16814. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16815. auto se = detail::scope_exit([&] {
  16816. svr.stop();
  16817. t.join();
  16818. ASSERT_FALSE(svr.is_running());
  16819. });
  16820. svr.wait_until_ready();
  16821. Client cli(HOST, PORT);
  16822. auto res = cli.Get(
  16823. "/ip",
  16824. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16826. EXPECT_EQ(StatusCode::OK_200, res->status);
  16827. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16828. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16829. }
  16830. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16831. Server svr;
  16832. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16833. std::string observed_remote_addr;
  16834. std::string observed_xff;
  16835. svr.Get("/ip", [&](const Request &req, Response &res) {
  16836. observed_remote_addr = req.remote_addr;
  16837. observed_xff = req.get_header_value("X-Forwarded-For");
  16838. res.set_content("ok", "text/plain");
  16839. });
  16840. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16841. auto se = detail::scope_exit([&] {
  16842. svr.stop();
  16843. t.join();
  16844. ASSERT_FALSE(svr.is_running());
  16845. });
  16846. svr.wait_until_ready();
  16847. Client cli(HOST, PORT);
  16848. auto res = cli.Get(
  16849. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16851. EXPECT_EQ(StatusCode::OK_200, res->status);
  16852. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16853. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16854. // and must not be selected.
  16855. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16856. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16857. }
  16858. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16859. Server svr;
  16860. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16861. std::string observed_remote_addr;
  16862. svr.Get("/ip", [&](const Request &req, Response &res) {
  16863. observed_remote_addr = req.remote_addr;
  16864. res.set_content("ok", "text/plain");
  16865. });
  16866. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16867. auto se = detail::scope_exit([&] {
  16868. svr.stop();
  16869. t.join();
  16870. ASSERT_FALSE(svr.is_running());
  16871. });
  16872. svr.wait_until_ready();
  16873. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16874. // a forged address and the trusted proxy's own address; the forged value must
  16875. // not win over the address the trusted proxy actually recorded.
  16876. Client cli(HOST, PORT);
  16877. auto res = cli.Get(
  16878. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16880. EXPECT_EQ(StatusCode::OK_200, res->status);
  16881. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16882. }
  16883. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16884. Server svr;
  16885. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16886. std::string observed_remote_addr;
  16887. std::string observed_xff;
  16888. svr.Get("/ip", [&](const Request &req, Response &res) {
  16889. observed_remote_addr = req.remote_addr;
  16890. observed_xff = req.get_header_value("X-Forwarded-For");
  16891. res.set_content("ok", "text/plain");
  16892. });
  16893. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16894. auto se = detail::scope_exit([&] {
  16895. svr.stop();
  16896. t.join();
  16897. ASSERT_FALSE(svr.is_running());
  16898. });
  16899. svr.wait_until_ready();
  16900. Client cli(HOST, PORT);
  16901. auto res = cli.Get(
  16902. "/ip",
  16903. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16905. EXPECT_EQ(StatusCode::OK_200, res->status);
  16906. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16907. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16908. }
  16909. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16910. Server svr;
  16911. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16912. std::string observed_remote_addr;
  16913. std::string observed_xff;
  16914. svr.Get("/ip", [&](const Request &req, Response &res) {
  16915. observed_remote_addr = req.remote_addr;
  16916. observed_xff = req.get_header_value("X-Forwarded-For");
  16917. res.set_content("ok", "text/plain");
  16918. });
  16919. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16920. auto se = detail::scope_exit([&] {
  16921. svr.stop();
  16922. t.join();
  16923. ASSERT_FALSE(svr.is_running());
  16924. });
  16925. svr.wait_until_ready();
  16926. std::string raw_req =
  16927. "GET /ip HTTP/1.1\r\n"
  16928. "Host: localhost\r\n"
  16929. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16930. "Connection: close\r\n"
  16931. "\r\n";
  16932. std::string out;
  16933. ASSERT_TRUE(send_request(5, raw_req, &out));
  16934. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16935. // Header parser trims surrounding whitespace of the header value
  16936. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16937. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16938. }
  16939. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16940. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16941. // their own X-Forwarded-For as a separate field line rather than extending the
  16942. // one the client sent, so every occurrence has to be taken into account.
  16943. // Reading only the first one hands back the address the client chose.
  16944. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16945. Server svr;
  16946. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16947. std::string observed_remote_addr;
  16948. size_t observed_xff_count = 0;
  16949. svr.Get("/ip", [&](const Request &req, Response &res) {
  16950. observed_remote_addr = req.remote_addr;
  16951. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16952. res.set_content("ok", "text/plain");
  16953. });
  16954. auto port = svr.bind_to_any_port(HOST);
  16955. thread t = thread([&]() { svr.listen_after_bind(); });
  16956. auto se = detail::scope_exit([&] {
  16957. svr.stop();
  16958. t.join();
  16959. ASSERT_FALSE(svr.is_running());
  16960. });
  16961. svr.wait_until_ready();
  16962. // The client supplies the first field line; the trusted proxy appends the
  16963. // address it observed as a second one.
  16964. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16965. "Host: localhost\r\n"
  16966. "X-Forwarded-For: 1.2.3.4\r\n"
  16967. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16968. "Connection: close\r\n"
  16969. "\r\n";
  16970. std::string out;
  16971. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16972. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16973. EXPECT_EQ(observed_xff_count, 2U);
  16974. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16975. // The same chain spread over one field line per hop derives the same client
  16976. // address, i.e. the split and the comma-joined representations agree.
  16977. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16978. "Host: localhost\r\n"
  16979. "X-Forwarded-For: 1.2.3.4\r\n"
  16980. "X-Forwarded-For: 198.51.100.23\r\n"
  16981. "X-Forwarded-For: 192.0.2.45\r\n"
  16982. "Connection: close\r\n"
  16983. "\r\n";
  16984. out.clear();
  16985. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16986. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16987. EXPECT_EQ(observed_xff_count, 3U);
  16988. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16989. }
  16990. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16991. // crash the server (it used to call front() on an empty vector inside
  16992. // get_client_ip). The connection-level remote address must be retained instead.
  16993. static void run_malformed_xff_test(const std::string &xff_value) {
  16994. Server svr;
  16995. svr.set_trusted_proxies({"192.0.2.45"});
  16996. std::string observed_remote_addr;
  16997. svr.Get("/ip", [&](const Request &req, Response &res) {
  16998. observed_remote_addr = req.remote_addr;
  16999. res.set_content("ok", "text/plain");
  17000. });
  17001. int port = 0;
  17002. thread t = thread([&]() {
  17003. port = svr.bind_to_any_port(HOST);
  17004. svr.listen_after_bind();
  17005. });
  17006. auto se = detail::scope_exit([&] {
  17007. svr.stop();
  17008. t.join();
  17009. ASSERT_FALSE(svr.is_running());
  17010. });
  17011. svr.wait_until_ready();
  17012. Client cli(HOST, port);
  17013. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17015. EXPECT_EQ(StatusCode::OK_200, res->status);
  17016. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17017. observed_remote_addr == "127.0.0.1");
  17018. }
  17019. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17020. run_malformed_xff_test("");
  17021. }
  17022. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17023. run_malformed_xff_test(",");
  17024. }
  17025. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17026. run_malformed_xff_test(", , ,");
  17027. }
  17028. // The same rule applies to Accept: a request whose acceptable types are spread
  17029. // over several field lines must be negotiated against all of them.
  17030. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17031. // case-insensitive connection options. Comparing the whole field value against
  17032. // one option misses a client that sends several of them, and misses every
  17033. // casing but the one written in the comparison.
  17034. //
  17035. // Sends req, reads the response, then reuses the same socket for a second
  17036. // request to find out whether the server kept the connection.
  17037. static void probe_connection_reuse(int port, const std::string &req,
  17038. bool *announced_close, bool *reusable) {
  17039. auto error = Error::Success;
  17040. auto sock = detail::create_client_socket(
  17041. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17042. /*connection_timeout_sec=*/5, 0,
  17043. /*read_timeout_sec=*/1, 0,
  17044. /*write_timeout_sec=*/5, 0, std::string(), error);
  17045. ASSERT_NE(sock, INVALID_SOCKET);
  17046. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17047. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17048. "Host: localhost\r\n"
  17049. "Connection: close\r\n"
  17050. "\r\n";
  17051. std::string first_response;
  17052. std::string second_response;
  17053. detail::process_client_socket(
  17054. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17055. [&](Stream &strm) {
  17056. if (strm.write(req.data(), req.size()) !=
  17057. static_cast<ssize_t>(req.size())) {
  17058. return false;
  17059. }
  17060. char buf[512];
  17061. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17062. // Headers plus the two-byte body of the handler below
  17063. while (reader.getline()) {
  17064. first_response += reader.ptr();
  17065. if (first_response.find("ok") != std::string::npos) { break; }
  17066. }
  17067. if (strm.write(second.data(), second.size()) !=
  17068. static_cast<ssize_t>(second.size())) {
  17069. return true;
  17070. }
  17071. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17072. while (reader2.getline()) {
  17073. second_response += reader2.ptr();
  17074. if (second_response.find("ok") != std::string::npos) { break; }
  17075. }
  17076. return true;
  17077. });
  17078. *announced_close =
  17079. first_response.find("Connection: close") != std::string::npos;
  17080. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17081. }
  17082. class ConnectionTokenTest : public ::testing::Test {
  17083. protected:
  17084. void SetUp() override {
  17085. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17086. res.set_content("ok", "text/plain");
  17087. });
  17088. port_ = svr_.bind_to_any_port(HOST);
  17089. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17090. svr_.wait_until_ready();
  17091. }
  17092. void TearDown() override {
  17093. svr_.stop();
  17094. if (thread_.joinable()) { thread_.join(); }
  17095. }
  17096. Server svr_;
  17097. int port_ = 0;
  17098. thread thread_;
  17099. };
  17100. // "close" alongside another option still closes the connection, and the
  17101. // response says so rather than leaving the peer to discover it.
  17102. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17103. bool announced_close = false;
  17104. bool reusable = true;
  17105. probe_connection_reuse(port_,
  17106. "GET /keepalive HTTP/1.1\r\n"
  17107. "Host: localhost\r\n"
  17108. "Connection: keep-alive, close\r\n"
  17109. "\r\n",
  17110. &announced_close, &reusable);
  17111. EXPECT_TRUE(announced_close);
  17112. EXPECT_FALSE(reusable);
  17113. }
  17114. // "close" split over two field lines is the same list, so it is honored too.
  17115. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17116. bool announced_close = false;
  17117. bool reusable = true;
  17118. probe_connection_reuse(port_,
  17119. "GET /keepalive HTTP/1.1\r\n"
  17120. "Host: localhost\r\n"
  17121. "Connection: keep-alive\r\n"
  17122. "Connection: close\r\n"
  17123. "\r\n",
  17124. &announced_close, &reusable);
  17125. EXPECT_TRUE(announced_close);
  17126. EXPECT_FALSE(reusable);
  17127. }
  17128. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17129. // keep-alive in the spelling everyone actually sends keeps its connection.
  17130. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17131. bool announced_close = false;
  17132. bool reusable = false;
  17133. probe_connection_reuse(port_,
  17134. "GET /keepalive HTTP/1.0\r\n"
  17135. "Host: localhost\r\n"
  17136. "Connection: keep-alive\r\n"
  17137. "\r\n",
  17138. &announced_close, &reusable);
  17139. EXPECT_FALSE(announced_close);
  17140. EXPECT_TRUE(reusable);
  17141. }
  17142. // A token the value merely contains is not the token itself.
  17143. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17144. bool announced_close = false;
  17145. bool reusable = false;
  17146. probe_connection_reuse(port_,
  17147. "GET /keepalive HTTP/1.1\r\n"
  17148. "Host: localhost\r\n"
  17149. "Connection: notclose\r\n"
  17150. "\r\n",
  17151. &announced_close, &reusable);
  17152. EXPECT_FALSE(announced_close);
  17153. EXPECT_TRUE(reusable);
  17154. }
  17155. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17156. Server svr;
  17157. std::vector<std::string> observed_types;
  17158. svr.Get("/", [&](const Request &req, Response &res) {
  17159. observed_types = req.accept_content_types;
  17160. res.set_content("ok", "text/plain");
  17161. });
  17162. auto port = svr.bind_to_any_port(HOST);
  17163. thread t = thread([&]() { svr.listen_after_bind(); });
  17164. auto se = detail::scope_exit([&] {
  17165. svr.stop();
  17166. t.join();
  17167. ASSERT_FALSE(svr.is_running());
  17168. });
  17169. svr.wait_until_ready();
  17170. Client cli(HOST, port);
  17171. Headers headers;
  17172. headers.emplace("Accept", "text/plain;q=0.5");
  17173. headers.emplace("Accept", "application/json");
  17174. auto res = cli.Get("/", headers);
  17175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17176. EXPECT_EQ(StatusCode::OK_200, res->status);
  17177. // Sorted by q-value, so the second field line's type comes first
  17178. ASSERT_EQ(2U, observed_types.size());
  17179. EXPECT_EQ("application/json", observed_types[0]);
  17180. EXPECT_EQ("text/plain", observed_types[1]);
  17181. }
  17182. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17183. // empty field line must not contribute a bare comma to the combined value.
  17184. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17185. Server svr;
  17186. std::vector<std::string> observed_types;
  17187. svr.Get("/", [&](const Request &req, Response &res) {
  17188. observed_types = req.accept_content_types;
  17189. res.set_content("ok", "text/plain");
  17190. });
  17191. auto port = svr.bind_to_any_port(HOST);
  17192. thread t = thread([&]() { svr.listen_after_bind(); });
  17193. auto se = detail::scope_exit([&] {
  17194. svr.stop();
  17195. t.join();
  17196. ASSERT_FALSE(svr.is_running());
  17197. });
  17198. svr.wait_until_ready();
  17199. // Empty first field line, then a real one
  17200. std::string raw_req = "GET / HTTP/1.1\r\n"
  17201. "Host: localhost\r\n"
  17202. "Accept:\r\n"
  17203. "Accept: application/json\r\n"
  17204. "Connection: close\r\n"
  17205. "\r\n";
  17206. std::string out;
  17207. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17208. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17209. ASSERT_EQ(1U, observed_types.size());
  17210. EXPECT_EQ("application/json", observed_types[0]);
  17211. }
  17212. // The skip in get_combined_header_value() is what keeps an empty field line
  17213. // from contributing a bare comma. Only a trailing empty field line exercises
  17214. // it: a leading one is already covered by the "combined is still empty" check,
  17215. // and parse_accept_header() now ignores the empty element either way, so the
  17216. // request-level test above can no longer tell the two apart.
  17217. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17218. Headers headers;
  17219. headers.emplace("Accept", "text/html");
  17220. headers.emplace("Accept", "");
  17221. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17222. headers.clear();
  17223. headers.emplace("Accept", "");
  17224. headers.emplace("Accept", "application/json");
  17225. EXPECT_EQ("application/json",
  17226. detail::get_combined_header_value(headers, "Accept"));
  17227. }
  17228. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17229. // An encoding offered on a later Accept-Encoding field line is still offered.
  17230. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17231. Server svr;
  17232. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17233. res.set_content(std::string(1024, 'x'), "text/plain");
  17234. });
  17235. auto port = svr.bind_to_any_port(HOST);
  17236. thread t = thread([&]() { svr.listen_after_bind(); });
  17237. auto se = detail::scope_exit([&] {
  17238. svr.stop();
  17239. t.join();
  17240. ASSERT_FALSE(svr.is_running());
  17241. });
  17242. svr.wait_until_ready();
  17243. Client cli(HOST, port);
  17244. cli.set_decompress(false);
  17245. Headers headers;
  17246. headers.emplace("Accept-Encoding", "identity");
  17247. headers.emplace("Accept-Encoding", "gzip");
  17248. auto res = cli.Get("/", headers);
  17249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17250. EXPECT_EQ(StatusCode::OK_200, res->status);
  17251. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  17252. }
  17253. #endif
  17254. #ifndef _WIN32
  17255. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  17256. Server svr;
  17257. svr.Post("/post", [&](const Request &req, Response &res) {
  17258. res.set_content(req.body, "text/plain");
  17259. });
  17260. svr.Put("/put", [&](const Request &req, Response &res) {
  17261. res.set_content(req.body, "text/plain");
  17262. });
  17263. svr.Patch("/patch", [&](const Request &req, Response &res) {
  17264. res.set_content(req.body, "text/plain");
  17265. });
  17266. svr.Delete("/delete", [&](const Request &req, Response &res) {
  17267. res.set_content(req.body, "text/plain");
  17268. });
  17269. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17270. auto se = detail::scope_exit([&] {
  17271. svr.stop();
  17272. t.join();
  17273. ASSERT_FALSE(svr.is_running());
  17274. });
  17275. svr.wait_until_ready();
  17276. std::string resp;
  17277. // POST without Content-Length
  17278. ASSERT_TRUE(send_request(5,
  17279. "POST /post HTTP/1.1\r\n"
  17280. "Host: localhost\r\n"
  17281. "Connection: close\r\n"
  17282. "\r\n",
  17283. &resp));
  17284. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17285. // PUT without Content-Length
  17286. resp.clear();
  17287. ASSERT_TRUE(send_request(5,
  17288. "PUT /put HTTP/1.1\r\n"
  17289. "Host: localhost\r\n"
  17290. "Connection: close\r\n"
  17291. "\r\n",
  17292. &resp));
  17293. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17294. // PATCH without Content-Length
  17295. resp.clear();
  17296. ASSERT_TRUE(send_request(5,
  17297. "PATCH /patch HTTP/1.1\r\n"
  17298. "Host: localhost\r\n"
  17299. "Connection: close\r\n"
  17300. "\r\n",
  17301. &resp));
  17302. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17303. // DELETE without Content-Length
  17304. resp.clear();
  17305. ASSERT_TRUE(send_request(5,
  17306. "DELETE /delete HTTP/1.1\r\n"
  17307. "Host: localhost\r\n"
  17308. "Connection: close\r\n"
  17309. "\r\n",
  17310. &resp));
  17311. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  17312. }
  17313. #endif
  17314. //==============================================================================
  17315. // open_stream() Tests
  17316. //==============================================================================
  17317. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  17318. std::string result;
  17319. char buf[8192];
  17320. ssize_t n;
  17321. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17322. result.append(buf, static_cast<size_t>(n));
  17323. }
  17324. return result;
  17325. }
  17326. // Mock stream for unit tests
  17327. class MockStream : public Stream {
  17328. public:
  17329. std::string data;
  17330. size_t pos = 0;
  17331. ssize_t error_after = -1; // -1 = no error
  17332. explicit MockStream(const std::string &d, ssize_t err = -1)
  17333. : data(d), error_after(err) {}
  17334. bool is_readable() const override { return true; }
  17335. bool wait_readable() const override { return true; }
  17336. bool wait_writable() const override { return true; }
  17337. ssize_t read(char *ptr, size_t size) override {
  17338. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  17339. if (pos >= data.size()) return 0;
  17340. size_t limit =
  17341. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  17342. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  17343. std::memcpy(ptr, data.data() + pos, to_read);
  17344. pos += to_read;
  17345. return static_cast<ssize_t>(to_read);
  17346. }
  17347. ssize_t write(const char *, size_t) override { return -1; }
  17348. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  17349. ip = "127.0.0.1";
  17350. port = 0;
  17351. }
  17352. void get_local_ip_and_port(std::string &ip, int &port) const override {
  17353. ip = "127.0.0.1";
  17354. port = 0;
  17355. }
  17356. socket_t socket() const override { return INVALID_SOCKET; }
  17357. time_t duration() const override { return 0; }
  17358. };
  17359. TEST(StreamHandleTest, Basic) {
  17360. ClientImpl::StreamHandle handle;
  17361. EXPECT_FALSE(handle.is_valid());
  17362. handle.response = detail::make_unique<Response>();
  17363. handle.error = Error::Connection;
  17364. EXPECT_FALSE(handle.is_valid());
  17365. handle.error = Error::Success;
  17366. EXPECT_TRUE(handle.is_valid());
  17367. }
  17368. TEST(BodyReaderTest, Basic) {
  17369. MockStream stream("Hello, World!");
  17370. detail::BodyReader reader;
  17371. reader.stream = &stream;
  17372. reader.content_length = 13;
  17373. char buf[32];
  17374. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  17375. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  17376. EXPECT_TRUE(reader.eof);
  17377. }
  17378. TEST(BodyReaderTest, NoStream) {
  17379. detail::BodyReader reader;
  17380. char buf[32];
  17381. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17382. EXPECT_EQ(Error::Connection, reader.last_error);
  17383. }
  17384. TEST(BodyReaderTest, Error) {
  17385. MockStream stream("Hello, World!", 5);
  17386. detail::BodyReader reader;
  17387. reader.stream = &stream;
  17388. reader.content_length = 13;
  17389. char buf[32];
  17390. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  17391. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  17392. EXPECT_EQ(Error::Read, reader.last_error);
  17393. }
  17394. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  17395. // Mock-based StreamHandle tests relying on private internals are removed.
  17396. class OpenStreamTest : public ::testing::Test {
  17397. protected:
  17398. void SetUp() override {
  17399. svr_.Get("/hello", [](const Request &, Response &res) {
  17400. res.set_content("Hello World!", "text/plain");
  17401. });
  17402. svr_.Get("/large", [](const Request &, Response &res) {
  17403. res.set_content(std::string(10000, 'X'), "text/plain");
  17404. });
  17405. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  17406. res.set_content("Hello World!", "image/jpeg");
  17407. res.set_header("Content-Encoding", "UTF-8");
  17408. });
  17409. svr_.Get("/chunked", [](const Request &, Response &res) {
  17410. res.set_chunked_content_provider("text/plain",
  17411. [](size_t offset, DataSink &sink) {
  17412. if (offset < 15) {
  17413. sink.write("chunk", 5);
  17414. return true;
  17415. }
  17416. sink.done();
  17417. return true;
  17418. });
  17419. });
  17420. svr_.Get("/compressible", [](const Request &, Response &res) {
  17421. res.set_chunked_content_provider("text/plain", [](size_t offset,
  17422. DataSink &sink) {
  17423. if (offset < 100 * 1024) {
  17424. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  17425. sink.write(chunk.data(), chunk.size());
  17426. return true;
  17427. }
  17428. sink.done();
  17429. return true;
  17430. });
  17431. });
  17432. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  17433. [](const Request & /*req*/, Response &res) {
  17434. auto i = new int(0);
  17435. res.set_header("Trailer", "Content-Length, X-Allowed");
  17436. res.set_chunked_content_provider(
  17437. "text/plain",
  17438. [i](size_t /*offset*/, DataSink &sink) {
  17439. switch (*i) {
  17440. case 0: sink.os << "123"; break;
  17441. case 1: sink.os << "456"; break;
  17442. case 2: sink.os << "789"; break;
  17443. case 3: {
  17444. sink.done_with_trailer(
  17445. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  17446. } break;
  17447. }
  17448. (*i)++;
  17449. return true;
  17450. },
  17451. [i](bool success) {
  17452. EXPECT_TRUE(success);
  17453. delete i;
  17454. });
  17455. });
  17456. // Echo headers endpoint for header-related tests
  17457. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  17458. std::string body;
  17459. for (const auto &h : req.headers) {
  17460. body.append(h.first);
  17461. body.push_back(':');
  17462. body.append(h.second);
  17463. body.push_back('\n');
  17464. }
  17465. res.set_content(body, "text/plain");
  17466. });
  17467. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  17468. std::string body;
  17469. for (const auto &h : req.headers) {
  17470. body.append(h.first);
  17471. body.push_back(':');
  17472. body.append(h.second);
  17473. body.push_back('\n');
  17474. }
  17475. res.set_content(body, "text/plain");
  17476. });
  17477. port_ = svr_.bind_to_any_port("127.0.0.1");
  17478. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17479. svr_.wait_until_ready();
  17480. }
  17481. void TearDown() override {
  17482. svr_.stop();
  17483. if (thread_.joinable()) thread_.join();
  17484. }
  17485. Server svr_;
  17486. std::thread thread_;
  17487. int port_ = 0;
  17488. };
  17489. TEST_F(OpenStreamTest, Basic) {
  17490. Client cli("127.0.0.1", port_);
  17491. auto handle = cli.open_stream("GET", "/hello");
  17492. EXPECT_TRUE(handle.is_valid());
  17493. EXPECT_EQ("Hello World!", read_all(handle));
  17494. }
  17495. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  17496. Client cli("127.0.0.1", port_);
  17497. auto handle = cli.open_stream("GET", "/unknown-encoding");
  17498. ASSERT_TRUE(handle.is_valid());
  17499. EXPECT_EQ("Hello World!", read_all(handle));
  17500. }
  17501. TEST_F(OpenStreamTest, SmallBuffer) {
  17502. Client cli("127.0.0.1", port_);
  17503. auto handle = cli.open_stream("GET", "/hello");
  17504. std::string result;
  17505. char buf[4];
  17506. ssize_t n;
  17507. while ((n = handle.read(buf, sizeof(buf))) > 0)
  17508. result.append(buf, static_cast<size_t>(n));
  17509. EXPECT_EQ("Hello World!", result);
  17510. }
  17511. TEST_F(OpenStreamTest, DefaultHeaders) {
  17512. Client cli("127.0.0.1", port_);
  17513. // open_stream GET should include Host, User-Agent and Accept-Encoding
  17514. {
  17515. auto handle = cli.open_stream("GET", "/echo-headers");
  17516. ASSERT_TRUE(handle.is_valid());
  17517. auto body = read_all(handle);
  17518. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  17519. std::string::npos);
  17520. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  17521. std::string::npos);
  17522. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  17523. }
  17524. // open_stream POST with body and no explicit content_type should NOT add
  17525. // text/plain Content-Type (behavior differs from non-streaming path), but
  17526. // should include Content-Length
  17527. {
  17528. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  17529. ASSERT_TRUE(handle.is_valid());
  17530. auto body = read_all(handle);
  17531. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  17532. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  17533. }
  17534. // open_stream POST with explicit Content-Type should preserve it
  17535. {
  17536. auto handle = cli.open_stream("POST", "/echo-headers", {},
  17537. {{"Content-Type", "application/custom"}},
  17538. "{}", "application/custom");
  17539. ASSERT_TRUE(handle.is_valid());
  17540. auto body = read_all(handle);
  17541. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  17542. }
  17543. // User-specified User-Agent must not be overwritten for stream API
  17544. {
  17545. auto handle = cli.open_stream("GET", "/echo-headers", {},
  17546. {{"User-Agent", "MyAgent/1.2"}});
  17547. ASSERT_TRUE(handle.is_valid());
  17548. auto body = read_all(handle);
  17549. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  17550. }
  17551. }
  17552. TEST_F(OpenStreamTest, Large) {
  17553. Client cli("127.0.0.1", port_);
  17554. auto handle = cli.open_stream("GET", "/large");
  17555. EXPECT_EQ(10000u, read_all(handle).size());
  17556. }
  17557. TEST_F(OpenStreamTest, ConnectionError) {
  17558. Client cli("127.0.0.1", 9999);
  17559. auto handle = cli.open_stream("GET", "/hello");
  17560. EXPECT_FALSE(handle.is_valid());
  17561. }
  17562. TEST_F(OpenStreamTest, Chunked) {
  17563. Client cli("127.0.0.1", port_);
  17564. auto handle = cli.open_stream("GET", "/chunked");
  17565. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17566. "Transfer-Encoding") == "chunked");
  17567. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17568. }
  17569. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17570. Client cli("127.0.0.1", port_);
  17571. auto handle =
  17572. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17573. ASSERT_TRUE(handle.is_valid());
  17574. // Consume body to allow trailers to be received/parsed
  17575. auto body = read_all(handle);
  17576. // Explicitly parse trailers (ensure trailers are available for assertion)
  17577. handle.parse_trailers_if_needed();
  17578. EXPECT_EQ(std::string("123456789"), body);
  17579. // The response should include a Trailer header declaring both names
  17580. ASSERT_TRUE(handle.response);
  17581. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17582. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17583. handle.response->get_header_value("Trailer"));
  17584. // Prohibited trailer must not be present
  17585. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17586. // Allowed trailer should be present
  17587. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17588. EXPECT_EQ(std::string("yes"),
  17589. handle.response->get_trailer_value("X-Allowed"));
  17590. // Verify trailers are NOT present as regular headers
  17591. EXPECT_EQ(std::string(""),
  17592. handle.response->get_header_value("Content-Length"));
  17593. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17594. }
  17595. static std::thread serve_single_response(std::promise<int> &port_promise,
  17596. const std::string &response) {
  17597. return std::thread([&port_promise, response] {
  17598. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17599. default_socket_options(srv);
  17600. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17601. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17602. sockaddr_in addr{};
  17603. addr.sin_family = AF_INET;
  17604. addr.sin_port = htons(0); // Let OS assign a free port
  17605. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17606. int opt = 1;
  17607. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17608. #ifdef _WIN32
  17609. reinterpret_cast<const char *>(&opt),
  17610. #else
  17611. &opt,
  17612. #endif
  17613. sizeof(opt));
  17614. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17615. ::listen(srv, 1) != 0) {
  17616. port_promise.set_value(-1);
  17617. detail::close_socket(srv);
  17618. return;
  17619. }
  17620. socklen_t addr_len = sizeof(addr);
  17621. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17622. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17623. sockaddr_in cli_addr{};
  17624. socklen_t cli_len = sizeof(cli_addr);
  17625. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17626. if (cli != INVALID_SOCKET) {
  17627. // Read the complete HTTP request (until the blank line that terminates
  17628. // headers) before sending the response. If the server closes the socket
  17629. // while the client's request data is still unread in the kernel receive
  17630. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17631. // connection on both sides: it discards the client's receive buffer
  17632. // (which already holds our response) and causes any in-progress write on
  17633. // the client to fail with ECONNRESET. Reading all request data first
  17634. // ensures close() emits a graceful FIN.
  17635. {
  17636. char rbuf[256];
  17637. std::string req;
  17638. while (req.find("\r\n\r\n") == std::string::npos) {
  17639. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17640. if (n <= 0) { break; }
  17641. req.append(rbuf, static_cast<size_t>(n));
  17642. }
  17643. }
  17644. ::send(cli,
  17645. #ifdef _WIN32
  17646. static_cast<const char *>(response.c_str()),
  17647. static_cast<int>(response.size()),
  17648. #else
  17649. response.c_str(), response.size(),
  17650. #endif
  17651. 0);
  17652. detail::close_socket(cli);
  17653. }
  17654. detail::close_socket(srv);
  17655. });
  17656. }
  17657. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17658. #ifndef _WIN32
  17659. signal(SIGPIPE, SIG_IGN);
  17660. #endif
  17661. std::promise<int> port_promise;
  17662. auto port_future = port_promise.get_future();
  17663. auto server_thread =
  17664. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17665. "Content-Type: text/plain\r\n"
  17666. "Content-Length: not-a-number\r\n"
  17667. "Connection: close\r\n"
  17668. "\r\n"
  17669. "hello");
  17670. auto port = port_future.get();
  17671. ASSERT_GT(port, 0);
  17672. Client cli("127.0.0.1", port);
  17673. auto handle = cli.open_stream("GET", "/");
  17674. EXPECT_FALSE(handle.is_valid());
  17675. server_thread.join();
  17676. }
  17677. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17678. #ifndef _WIN32
  17679. signal(SIGPIPE, SIG_IGN);
  17680. #endif
  17681. std::promise<int> port_promise;
  17682. auto port_future = port_promise.get_future();
  17683. auto server_thread = serve_single_response(
  17684. port_promise, "HTTP/1.1 200 OK\r\n"
  17685. "Content-Type: text/plain\r\n"
  17686. "Content-Length: 99999999999999999999999999\r\n"
  17687. "Connection: close\r\n"
  17688. "\r\n"
  17689. "hello");
  17690. auto port = port_future.get();
  17691. ASSERT_GT(port, 0);
  17692. // Historically std::stoull would throw std::out_of_range here and crash
  17693. // the process, then parsing silently clamped to a bogus framing length and
  17694. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17695. // so the stream fails to open, matching the not-a-number case above. The
  17696. // process still must NOT terminate.
  17697. Client cli("127.0.0.1", port);
  17698. auto handle = cli.open_stream("GET", "/");
  17699. EXPECT_FALSE(handle.is_valid());
  17700. server_thread.join();
  17701. }
  17702. // Serves `response` to the single request `fn` makes with a fresh client.
  17703. template <typename Fn>
  17704. static void with_single_response(const std::string &response, Fn fn) {
  17705. #ifndef _WIN32
  17706. signal(SIGPIPE, SIG_IGN);
  17707. #endif
  17708. std::promise<int> port_promise;
  17709. auto port_future = port_promise.get_future();
  17710. auto server_thread = serve_single_response(port_promise, response);
  17711. auto se = detail::scope_exit([&] { server_thread.join(); });
  17712. auto port = port_future.get();
  17713. ASSERT_GT(port, 0);
  17714. Client cli("127.0.0.1", port);
  17715. fn(cli);
  17716. }
  17717. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17718. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17719. // the chunked coding and drop Content-Length, so a front-end that trusts
  17720. // Content-Length would disagree about where the body ends (response
  17721. // smuggling). The client must reject such a response.
  17722. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17723. for (const char *te : {"chunked", "gzip, chunked"}) {
  17724. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17725. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17726. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17727. "5\r\nhello\r\n0\r\n\r\n";
  17728. with_single_response(response, [&](Client &cli) {
  17729. auto res = cli.Get("/");
  17730. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17731. EXPECT_EQ(Error::Read, res.error()) << te;
  17732. });
  17733. with_single_response(response, [&](Client &cli) {
  17734. auto handle = cli.open_stream("GET", "/");
  17735. EXPECT_FALSE(handle.is_valid()) << te;
  17736. EXPECT_EQ(Error::Read, handle.error) << te;
  17737. });
  17738. }
  17739. }
  17740. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17741. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17742. // closing the connection (unlike a request, which must be rejected).
  17743. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17744. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17745. "Transfer-Encoding: chunked\r\n"
  17746. "Connection: close\r\n"
  17747. "\r\n"
  17748. "5\r\nhello\r\n0\r\n\r\n",
  17749. "HTTP/1.1 200 OK\r\n"
  17750. "Transfer-Encoding: gzip\r\n"
  17751. "Connection: close\r\n"
  17752. "\r\n"
  17753. "hello"}) {
  17754. with_single_response(response, [&](Client &cli) {
  17755. auto res = cli.Get("/");
  17756. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17757. EXPECT_EQ("hello", res->body);
  17758. });
  17759. with_single_response(response, [&](Client &cli) {
  17760. auto handle = cli.open_stream("GET", "/");
  17761. ASSERT_TRUE(handle.is_valid()) << response;
  17762. EXPECT_EQ("hello", read_all(handle));
  17763. });
  17764. }
  17765. }
  17766. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17767. // framing headers describe nothing to read and must not be rejected.
  17768. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17769. const std::string framing = "Content-Length: 5\r\n"
  17770. "Transfer-Encoding: chunked\r\n"
  17771. "Connection: close\r\n"
  17772. "\r\n";
  17773. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17774. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17775. });
  17776. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17777. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17778. });
  17779. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17780. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17781. with_single_response(response, [&](Client &cli) {
  17782. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17783. });
  17784. with_single_response(response, [&](Client &cli) {
  17785. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17786. });
  17787. }
  17788. }
  17789. // A payload max length of 0 means no limit, however the body is framed.
  17790. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  17791. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17792. "Transfer-Encoding: chunked\r\n"
  17793. "\r\n"
  17794. "5\r\nhello\r\n0\r\n\r\n",
  17795. "HTTP/1.1 200 OK\r\n"
  17796. "Connection: close\r\n"
  17797. "\r\n"
  17798. "hello"}) {
  17799. with_single_response(response, [&](Client &cli) {
  17800. cli.set_payload_max_length(0);
  17801. auto res = cli.Get("/");
  17802. ASSERT_TRUE(res) << response;
  17803. EXPECT_EQ("hello", res->body) << response;
  17804. });
  17805. }
  17806. }
  17807. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  17808. Server svr;
  17809. svr.set_payload_max_length(0);
  17810. svr.Post("/echo", [](const Request &req, Response &res) {
  17811. res.set_content(req.body, "text/plain");
  17812. });
  17813. auto port = svr.bind_to_any_port(HOST);
  17814. thread t = thread([&] { svr.listen_after_bind(); });
  17815. auto se = detail::scope_exit([&] {
  17816. svr.stop();
  17817. t.join();
  17818. ASSERT_FALSE(svr.is_running());
  17819. });
  17820. svr.wait_until_ready();
  17821. Client cli(HOST, port);
  17822. auto res = cli.Post(
  17823. "/echo",
  17824. [](size_t /*offset*/, DataSink &sink) {
  17825. sink.write("hello", 5);
  17826. sink.done();
  17827. return true;
  17828. },
  17829. "text/plain");
  17830. ASSERT_TRUE(res);
  17831. EXPECT_EQ(StatusCode::OK_200, res->status);
  17832. EXPECT_EQ("hello", res->body);
  17833. }
  17834. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17835. TEST_F(OpenStreamTest, Gzip) {
  17836. Client cli("127.0.0.1", port_);
  17837. auto handle = cli.open_stream("GET", "/compressible", {},
  17838. {{"Accept-Encoding", "gzip"}});
  17839. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17840. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17841. }
  17842. #endif
  17843. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17844. TEST_F(OpenStreamTest, Brotli) {
  17845. Client cli("127.0.0.1", port_);
  17846. auto handle =
  17847. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17848. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17849. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17850. }
  17851. #endif
  17852. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17853. TEST_F(OpenStreamTest, Zstd) {
  17854. Client cli("127.0.0.1", port_);
  17855. auto handle = cli.open_stream("GET", "/compressible", {},
  17856. {{"Accept-Encoding", "zstd"}});
  17857. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17858. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17859. }
  17860. #endif
  17861. #ifdef CPPHTTPLIB_SSL_ENABLED
  17862. class SSLOpenStreamTest : public ::testing::Test {
  17863. protected:
  17864. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17865. void SetUp() override {
  17866. svr_.Get("/hello", [](const Request &, Response &res) {
  17867. res.set_content("Hello SSL World!", "text/plain");
  17868. });
  17869. svr_.Get("/chunked", [](const Request &, Response &res) {
  17870. res.set_chunked_content_provider("text/plain",
  17871. [](size_t offset, DataSink &sink) {
  17872. if (offset < 15) {
  17873. sink.write("chunk", 5);
  17874. return true;
  17875. }
  17876. sink.done();
  17877. return true;
  17878. });
  17879. });
  17880. svr_.Post("/echo", [](const Request &req, Response &res) {
  17881. res.set_content(req.body, req.get_header_value("Content-Type"));
  17882. });
  17883. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17884. std::string body = req.body;
  17885. res.set_chunked_content_provider(
  17886. "text/plain", [body](size_t offset, DataSink &sink) {
  17887. if (offset < body.size()) {
  17888. sink.write(body.data() + offset, body.size() - offset);
  17889. }
  17890. sink.done();
  17891. return true;
  17892. });
  17893. });
  17894. port_ = svr_.bind_to_any_port("127.0.0.1");
  17895. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17896. svr_.wait_until_ready();
  17897. }
  17898. void TearDown() override {
  17899. svr_.stop();
  17900. if (thread_.joinable()) thread_.join();
  17901. }
  17902. SSLServer svr_;
  17903. std::thread thread_;
  17904. int port_ = 0;
  17905. };
  17906. TEST_F(SSLOpenStreamTest, Basic) {
  17907. SSLClient cli("127.0.0.1", port_);
  17908. cli.enable_server_certificate_verification(false);
  17909. auto handle = cli.open_stream("GET", "/hello");
  17910. ASSERT_TRUE(handle.is_valid());
  17911. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17912. }
  17913. TEST_F(SSLOpenStreamTest, Chunked) {
  17914. SSLClient cli("127.0.0.1", port_);
  17915. cli.enable_server_certificate_verification(false);
  17916. auto handle = cli.open_stream("GET", "/chunked");
  17917. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17918. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17919. "Transfer-Encoding") == "chunked");
  17920. auto body = read_all(handle);
  17921. EXPECT_EQ("chunkchunkchunk", body);
  17922. }
  17923. TEST_F(SSLOpenStreamTest, Post) {
  17924. SSLClient cli("127.0.0.1", port_);
  17925. cli.enable_server_certificate_verification(false);
  17926. auto handle =
  17927. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17928. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17929. EXPECT_EQ(200, handle.response->status);
  17930. auto body = read_all(handle);
  17931. EXPECT_EQ("Hello SSL POST", body);
  17932. }
  17933. TEST_F(SSLOpenStreamTest, PostChunked) {
  17934. SSLClient cli("127.0.0.1", port_);
  17935. cli.enable_server_certificate_verification(false);
  17936. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17937. "Chunked SSL Data", "text/plain");
  17938. ASSERT_TRUE(handle.is_valid());
  17939. EXPECT_EQ(200, handle.response->status);
  17940. auto body = read_all(handle);
  17941. EXPECT_EQ("Chunked SSL Data", body);
  17942. }
  17943. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17944. // Content-Length is terminated by the server closing the connection. When the
  17945. // SSL peer sends a close_notify after the body, the client must treat it as a
  17946. // clean EOF and return a successful response rather than an error.
  17947. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17948. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17949. ASSERT_TRUE(svr.is_valid());
  17950. svr.set_keep_alive_max_count(1);
  17951. const std::string expected_body = "Hello from connection-close response!";
  17952. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17953. res.set_content_provider("text/plain",
  17954. [&](size_t offset, DataSink &sink) -> bool {
  17955. if (offset < expected_body.size()) {
  17956. sink.write(expected_body.data() + offset,
  17957. expected_body.size() - offset);
  17958. }
  17959. sink.done();
  17960. return true;
  17961. });
  17962. });
  17963. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17964. auto se = detail::scope_exit([&] {
  17965. svr.stop();
  17966. listen_thread.join();
  17967. ASSERT_FALSE(svr.is_running());
  17968. });
  17969. svr.wait_until_ready();
  17970. SSLClient cli(HOST, PORT);
  17971. cli.enable_server_certificate_verification(false);
  17972. auto res = cli.Get("/no-content-length");
  17973. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17974. EXPECT_EQ(StatusCode::OK_200, res->status);
  17975. EXPECT_EQ(expected_body, res->body);
  17976. }
  17977. #endif // CPPHTTPLIB_SSL_ENABLED
  17978. //==============================================================================
  17979. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17980. // results for various scenarios.
  17981. //==============================================================================
  17982. TEST(ParityTest, GetVsOpenStream) {
  17983. Server svr;
  17984. const std::string path = "/parity";
  17985. const std::string content = "Parity test content: hello world";
  17986. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17987. res.set_content(content, "text/plain");
  17988. });
  17989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17990. auto se = detail::scope_exit([&] {
  17991. svr.stop();
  17992. t.join();
  17993. ASSERT_FALSE(svr.is_running());
  17994. });
  17995. svr.wait_until_ready();
  17996. Client cli(HOST, PORT);
  17997. // Non-stream path
  17998. auto r1 = cli.Get(path);
  17999. ASSERT_TRUE(r1);
  18000. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18001. // Stream path
  18002. auto h = cli.open_stream("GET", path);
  18003. ASSERT_TRUE(h.is_valid());
  18004. EXPECT_EQ(r1->body, read_all(h));
  18005. }
  18006. // Helper to compress data with provided compressor type T
  18007. template <typename Compressor>
  18008. static std::string compress_payload_for_parity(const std::string &in) {
  18009. std::string out;
  18010. Compressor compressor;
  18011. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18012. [&](const char *data, size_t n) {
  18013. out.append(data, n);
  18014. return true;
  18015. });
  18016. EXPECT_TRUE(ok);
  18017. return out;
  18018. }
  18019. // Helper function for compression parity tests
  18020. template <typename Compressor>
  18021. static void test_compression_parity(const std::string &original,
  18022. const std::string &path,
  18023. const std::string &encoding) {
  18024. const std::string compressed =
  18025. compress_payload_for_parity<Compressor>(original);
  18026. Server svr;
  18027. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18028. res.set_content(compressed, "application/octet-stream");
  18029. res.set_header("Content-Encoding", encoding);
  18030. });
  18031. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18032. auto se = detail::scope_exit([&] {
  18033. svr.stop();
  18034. t.join();
  18035. ASSERT_FALSE(svr.is_running());
  18036. });
  18037. svr.wait_until_ready();
  18038. Client cli(HOST, PORT);
  18039. // Non-streaming
  18040. {
  18041. auto res = cli.Get(path);
  18042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18043. EXPECT_EQ(StatusCode::OK_200, res->status);
  18044. EXPECT_EQ(original, res->body);
  18045. }
  18046. // Streaming
  18047. {
  18048. auto h = cli.open_stream("GET", path);
  18049. ASSERT_TRUE(h.is_valid());
  18050. EXPECT_EQ(original, read_all(h));
  18051. }
  18052. }
  18053. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18054. TEST(ParityTest, Gzip) {
  18055. test_compression_parity<detail::gzip_compressor>(
  18056. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18057. }
  18058. #endif
  18059. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18060. TEST(ParityTest, Brotli) {
  18061. test_compression_parity<detail::brotli_compressor>(
  18062. "Hello, brotli parity test payload", "/parity-br", "br");
  18063. }
  18064. #endif
  18065. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18066. TEST(ParityTest, Zstd) {
  18067. test_compression_parity<detail::zstd_compressor>(
  18068. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18069. }
  18070. #endif
  18071. //==============================================================================
  18072. // New Stream API Tests
  18073. //==============================================================================
  18074. inline std::string read_body(httplib::stream::Result &result) {
  18075. std::string body;
  18076. while (result.next()) {
  18077. body.append(result.data(), result.size());
  18078. }
  18079. return body;
  18080. }
  18081. TEST(ClientConnectionTest, Basic) {
  18082. httplib::ClientConnection conn;
  18083. EXPECT_FALSE(conn.is_open());
  18084. conn.sock = 1;
  18085. EXPECT_TRUE(conn.is_open());
  18086. httplib::ClientConnection conn2(std::move(conn));
  18087. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18088. conn2.sock = INVALID_SOCKET;
  18089. }
  18090. // Unified test server for all stream::* tests
  18091. class StreamApiTest : public ::testing::Test {
  18092. protected:
  18093. void SetUp() override {
  18094. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18095. res.set_content("Hello World!", "text/plain");
  18096. });
  18097. svr_.Get("/echo-params",
  18098. [](const httplib::Request &req, httplib::Response &res) {
  18099. std::string r;
  18100. for (const auto &p : req.params) {
  18101. if (!r.empty()) r += "&";
  18102. r += p.first + "=" + p.second;
  18103. }
  18104. res.set_content(r, "text/plain");
  18105. });
  18106. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18107. res.set_content(req.body, req.get_header_value("Content-Type"));
  18108. });
  18109. svr_.Post("/echo-headers",
  18110. [](const httplib::Request &req, httplib::Response &res) {
  18111. std::string r;
  18112. for (const auto &h : req.headers)
  18113. r += h.first + ": " + h.second + "\n";
  18114. res.set_content(r, "text/plain");
  18115. });
  18116. svr_.Post("/echo-params",
  18117. [](const httplib::Request &req, httplib::Response &res) {
  18118. std::string r = "params:";
  18119. for (const auto &p : req.params)
  18120. r += p.first + "=" + p.second + ";";
  18121. res.set_content(r + " body:" + req.body, "text/plain");
  18122. });
  18123. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18124. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18125. });
  18126. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18127. res.set_content("PUT:" + req.body, "text/plain");
  18128. });
  18129. svr_.Patch("/echo",
  18130. [](const httplib::Request &req, httplib::Response &res) {
  18131. res.set_content("PATCH:" + req.body, "text/plain");
  18132. });
  18133. svr_.Delete(
  18134. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18135. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18136. "text/plain");
  18137. });
  18138. svr_.Get("/head-test",
  18139. [](const httplib::Request &, httplib::Response &res) {
  18140. res.set_content("body for HEAD", "text/plain");
  18141. });
  18142. svr_.Options("/options",
  18143. [](const httplib::Request &, httplib::Response &res) {
  18144. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18145. });
  18146. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18147. svr_.wait_until_ready();
  18148. }
  18149. void TearDown() override {
  18150. svr_.stop();
  18151. if (thread_.joinable()) thread_.join();
  18152. }
  18153. httplib::Server svr_;
  18154. std::thread thread_;
  18155. };
  18156. // stream::Get tests
  18157. TEST_F(StreamApiTest, GetBasic) {
  18158. httplib::Client cli(HOST, PORT);
  18159. auto result = httplib::stream::Get(cli, "/hello");
  18160. ASSERT_TRUE(result.is_valid());
  18161. EXPECT_EQ(200, result.status());
  18162. EXPECT_EQ("Hello World!", read_body(result));
  18163. }
  18164. TEST_F(StreamApiTest, GetWithParams) {
  18165. httplib::Client cli(HOST, PORT);
  18166. httplib::Params params{{"foo", "bar"}};
  18167. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18168. ASSERT_TRUE(result.is_valid());
  18169. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18170. }
  18171. TEST_F(StreamApiTest, GetConnectionError) {
  18172. httplib::Client cli(HOST, 9999);
  18173. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18174. }
  18175. TEST_F(StreamApiTest, Get404) {
  18176. httplib::Client cli(HOST, PORT);
  18177. auto result = httplib::stream::Get(cli, "/nonexistent");
  18178. EXPECT_TRUE(result.is_valid());
  18179. EXPECT_EQ(404, result.status());
  18180. }
  18181. // stream::Post tests
  18182. TEST_F(StreamApiTest, PostBasic) {
  18183. httplib::Client cli(HOST, PORT);
  18184. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18185. "application/json");
  18186. ASSERT_TRUE(result.is_valid());
  18187. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18188. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18189. }
  18190. TEST_F(StreamApiTest, PostWithHeaders) {
  18191. httplib::Client cli(HOST, PORT);
  18192. httplib::Headers headers{{"X-Custom", "value"}};
  18193. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18194. "text/plain");
  18195. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18196. }
  18197. TEST_F(StreamApiTest, PostWithParams) {
  18198. httplib::Client cli(HOST, PORT);
  18199. httplib::Params params{{"k", "v"}};
  18200. auto result =
  18201. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18202. auto body = read_body(result);
  18203. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18204. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18205. }
  18206. TEST_F(StreamApiTest, PostLarge) {
  18207. httplib::Client cli(HOST, PORT);
  18208. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18209. size_t total = 0;
  18210. while (result.next()) {
  18211. total += result.size();
  18212. }
  18213. EXPECT_EQ(100u * 1024u, total);
  18214. }
  18215. // stream::Put/Patch tests
  18216. TEST_F(StreamApiTest, PutAndPatch) {
  18217. httplib::Client cli(HOST, PORT);
  18218. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18219. EXPECT_EQ("PUT:test", read_body(put));
  18220. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18221. EXPECT_EQ("PATCH:test", read_body(patch));
  18222. }
  18223. // stream::Delete tests
  18224. TEST_F(StreamApiTest, Delete) {
  18225. httplib::Client cli(HOST, PORT);
  18226. auto del1 = httplib::stream::Delete(cli, "/resource");
  18227. EXPECT_EQ("Deleted", read_body(del1));
  18228. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18229. EXPECT_EQ("Deleted:data", read_body(del2));
  18230. }
  18231. // stream::Head/Options tests
  18232. TEST_F(StreamApiTest, HeadAndOptions) {
  18233. httplib::Client cli(HOST, PORT);
  18234. auto head = httplib::stream::Head(cli, "/head-test");
  18235. EXPECT_TRUE(head.is_valid());
  18236. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  18237. auto opts = httplib::stream::Options(cli, "/options");
  18238. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  18239. }
  18240. // SSL stream::* tests
  18241. #ifdef CPPHTTPLIB_SSL_ENABLED
  18242. class SSLStreamApiTest : public ::testing::Test {
  18243. protected:
  18244. void SetUp() override {
  18245. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18246. res.set_content("Hello SSL!", "text/plain");
  18247. });
  18248. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18249. res.set_content(req.body, "text/plain");
  18250. });
  18251. port_ = svr_.bind_to_any_port("127.0.0.1");
  18252. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18253. svr_.wait_until_ready();
  18254. }
  18255. void TearDown() override {
  18256. svr_.stop();
  18257. if (thread_.joinable()) thread_.join();
  18258. }
  18259. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  18260. std::thread thread_;
  18261. int port_ = 0;
  18262. };
  18263. TEST_F(SSLStreamApiTest, GetAndPost) {
  18264. httplib::SSLClient cli("127.0.0.1", port_);
  18265. cli.enable_server_certificate_verification(false);
  18266. auto get = httplib::stream::Get(cli, "/hello");
  18267. EXPECT_EQ("Hello SSL!", read_body(get));
  18268. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  18269. EXPECT_EQ("test", read_body(post));
  18270. }
  18271. #endif
  18272. // Tests for Error::Timeout and Error::ConnectionClosed error types
  18273. // These errors are set in SocketStream/SSLSocketStream and propagated through
  18274. // BodyReader
  18275. TEST(ErrorHandlingTest, StreamReadTimeout) {
  18276. // Test that read timeout during streaming is detected
  18277. // Use a large content-length response where server delays mid-stream
  18278. Server svr;
  18279. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18280. // Send a large response with delay in the middle
  18281. res.set_content_provider(
  18282. 1000, // content_length
  18283. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  18284. if (offset < 100) {
  18285. // Send first 100 bytes immediately
  18286. std::string data(100, 'A');
  18287. sink.write(data.c_str(), data.size());
  18288. return true;
  18289. }
  18290. // Then delay longer than client timeout
  18291. std::this_thread::sleep_for(std::chrono::seconds(3));
  18292. std::string data(900, 'B');
  18293. sink.write(data.c_str(), data.size());
  18294. return true;
  18295. });
  18296. });
  18297. auto port = 8091;
  18298. std::thread t([&]() { svr.listen("localhost", port); });
  18299. svr.wait_until_ready();
  18300. Client cli("localhost", port);
  18301. cli.set_read_timeout(1, 0); // 1 second timeout
  18302. auto handle = cli.open_stream("GET", "/slow-stream");
  18303. ASSERT_TRUE(handle.is_valid());
  18304. char buf[256];
  18305. ssize_t total = 0;
  18306. ssize_t n;
  18307. bool got_error = false;
  18308. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18309. total += n;
  18310. }
  18311. if (n < 0) {
  18312. got_error = true;
  18313. // Should be timeout or read error
  18314. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18315. handle.get_read_error() == Error::Read)
  18316. << "Actual error: " << to_string(handle.get_read_error());
  18317. }
  18318. // Either we got an error, or we got less data than expected
  18319. EXPECT_TRUE(got_error || total < 1000)
  18320. << "Expected timeout but got all " << total << " bytes";
  18321. svr.stop();
  18322. t.join();
  18323. }
  18324. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  18325. // Test connection closed detection via BodyReader
  18326. Server svr;
  18327. std::atomic<bool> close_now{false};
  18328. svr.Get("/will-close", [&](const Request &, Response &res) {
  18329. res.set_content_provider(
  18330. 10000, // Large content_length that we won't fully send
  18331. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18332. if (offset < 100) {
  18333. std::string data(100, 'X');
  18334. sink.write(data.c_str(), data.size());
  18335. return true;
  18336. }
  18337. // Wait for signal then abort
  18338. while (!close_now) {
  18339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18340. }
  18341. return false; // Abort - server will close connection
  18342. });
  18343. });
  18344. auto port = 8092;
  18345. std::thread t([&]() { svr.listen("localhost", port); });
  18346. svr.wait_until_ready();
  18347. Client cli("localhost", port);
  18348. auto handle = cli.open_stream("GET", "/will-close");
  18349. ASSERT_TRUE(handle.is_valid());
  18350. char buf[256];
  18351. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18352. EXPECT_GT(n, 0) << "First read should succeed";
  18353. // Signal server to close
  18354. close_now = true;
  18355. // Keep reading until error or EOF
  18356. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18357. // Keep reading
  18358. }
  18359. // Should get an error since content_length wasn't satisfied
  18360. if (n < 0) {
  18361. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18362. handle.get_read_error() == Error::Read)
  18363. << "Actual error: " << to_string(handle.get_read_error());
  18364. }
  18365. svr.stop();
  18366. t.join();
  18367. }
  18368. #ifdef CPPHTTPLIB_SSL_ENABLED
  18369. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  18370. // Test that read timeout during SSL streaming is detected
  18371. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18372. svr.Get("/slow-stream", [](const Request &, Response &res) {
  18373. res.set_content_provider(
  18374. 1000, "text/plain",
  18375. [](size_t offset, size_t /*length*/, DataSink &sink) {
  18376. if (offset < 100) {
  18377. std::string data(100, 'A');
  18378. sink.write(data.c_str(), data.size());
  18379. return true;
  18380. }
  18381. std::this_thread::sleep_for(std::chrono::seconds(3));
  18382. std::string data(900, 'B');
  18383. sink.write(data.c_str(), data.size());
  18384. return true;
  18385. });
  18386. });
  18387. auto port = 8093;
  18388. std::thread t([&]() { svr.listen("localhost", port); });
  18389. svr.wait_until_ready();
  18390. SSLClient cli("localhost", port);
  18391. cli.enable_server_certificate_verification(false);
  18392. cli.set_read_timeout(1, 0); // 1 second timeout
  18393. auto handle = cli.open_stream("GET", "/slow-stream");
  18394. ASSERT_TRUE(handle.is_valid());
  18395. char buf[256];
  18396. ssize_t total = 0;
  18397. ssize_t n;
  18398. bool got_error = false;
  18399. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18400. total += n;
  18401. }
  18402. if (n < 0) {
  18403. got_error = true;
  18404. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  18405. handle.get_read_error() == Error::Read)
  18406. << "Actual error: " << to_string(handle.get_read_error());
  18407. }
  18408. EXPECT_TRUE(got_error || total < 1000)
  18409. << "Expected timeout but got all " << total << " bytes";
  18410. svr.stop();
  18411. t.join();
  18412. }
  18413. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  18414. // Test SSL connection closed detection
  18415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18416. std::atomic<bool> close_now{false};
  18417. svr.Get("/will-close", [&](const Request &, Response &res) {
  18418. res.set_content_provider(
  18419. 10000, "text/plain",
  18420. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  18421. if (offset < 100) {
  18422. std::string data(100, 'X');
  18423. sink.write(data.c_str(), data.size());
  18424. return true;
  18425. }
  18426. while (!close_now) {
  18427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18428. }
  18429. return false;
  18430. });
  18431. });
  18432. auto port = 8094;
  18433. std::thread t([&]() { svr.listen("localhost", port); });
  18434. svr.wait_until_ready();
  18435. SSLClient cli("localhost", port);
  18436. cli.enable_server_certificate_verification(false);
  18437. auto handle = cli.open_stream("GET", "/will-close");
  18438. ASSERT_TRUE(handle.is_valid());
  18439. char buf[256];
  18440. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  18441. EXPECT_GT(n, 0);
  18442. // Signal server to close
  18443. close_now = true;
  18444. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18445. // Keep reading
  18446. }
  18447. if (n < 0) {
  18448. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  18449. handle.get_read_error() == Error::Read)
  18450. << "Actual error: " << to_string(handle.get_read_error());
  18451. }
  18452. svr.stop();
  18453. t.join();
  18454. }
  18455. #endif
  18456. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  18457. using namespace httplib;
  18458. // Create a test file
  18459. const char *fname = "etag_testfile.txt";
  18460. const char *content = "etag-content";
  18461. {
  18462. std::ofstream ofs(fname);
  18463. ofs << content;
  18464. ASSERT_TRUE(ofs.good());
  18465. }
  18466. Server svr;
  18467. svr.set_mount_point("/static", ".");
  18468. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18469. svr.wait_until_ready();
  18470. Client cli(HOST, PORT);
  18471. // First request: should get 200 with ETag header
  18472. auto res1 = cli.Get("/static/etag_testfile.txt");
  18473. ASSERT_TRUE(res1);
  18474. ASSERT_EQ(200, res1->status);
  18475. ASSERT_TRUE(res1->has_header("ETag"));
  18476. std::string etag = res1->get_header_value("ETag");
  18477. EXPECT_FALSE(etag.empty());
  18478. // Verify ETag format: W/"hex-hex"
  18479. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  18480. EXPECT_EQ('W', etag[0]);
  18481. EXPECT_EQ('/', etag[1]);
  18482. EXPECT_EQ('"', etag[2]);
  18483. EXPECT_EQ('"', etag.back());
  18484. // Exact match: expect 304 Not Modified
  18485. Headers h2 = {{"If-None-Match", etag}};
  18486. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  18487. ASSERT_TRUE(res2);
  18488. EXPECT_EQ(304, res2->status);
  18489. // Wildcard match: expect 304 Not Modified
  18490. Headers h3 = {{"If-None-Match", "*"}};
  18491. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  18492. ASSERT_TRUE(res3);
  18493. EXPECT_EQ(304, res3->status);
  18494. // Non-matching ETag: expect 200
  18495. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  18496. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  18497. ASSERT_TRUE(res4);
  18498. EXPECT_EQ(200, res4->status);
  18499. // Multiple ETags with one matching: expect 304
  18500. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  18501. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  18502. ASSERT_TRUE(res5);
  18503. EXPECT_EQ(304, res5->status);
  18504. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  18505. // that equivalent to the single comma-separated list above, so the match on
  18506. // the second line must still be found.
  18507. Headers h6;
  18508. h6.emplace("If-None-Match", "W/\"other\"");
  18509. h6.emplace("If-None-Match", etag);
  18510. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  18511. ASSERT_TRUE(res6);
  18512. EXPECT_EQ(304, res6->status);
  18513. svr.stop();
  18514. t.join();
  18515. std::remove(fname);
  18516. }
  18517. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  18518. using namespace httplib;
  18519. Server svr;
  18520. svr.set_mount_point("/static", ".");
  18521. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18522. svr.wait_until_ready();
  18523. Client cli(HOST, PORT);
  18524. // Send If-None-Match: * to a non-existent file
  18525. Headers h = {{"If-None-Match", "*"}};
  18526. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  18527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18528. EXPECT_EQ(404, res->status);
  18529. svr.stop();
  18530. t.join();
  18531. }
  18532. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  18533. using namespace httplib;
  18534. // Create a test file
  18535. const char *fname = "etag_boundary_testfile.txt";
  18536. const char *content = "boundary-test";
  18537. {
  18538. std::ofstream ofs(fname);
  18539. ofs << content;
  18540. ASSERT_TRUE(ofs.good());
  18541. }
  18542. Server svr;
  18543. svr.set_mount_point("/static", ".");
  18544. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  18545. svr.wait_until_ready();
  18546. Client cli(HOST, PORT);
  18547. // Get the actual ETag
  18548. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  18549. ASSERT_TRUE(res1);
  18550. ASSERT_EQ(200, res1->status);
  18551. ASSERT_TRUE(res1->has_header("ETag"));
  18552. std::string etag = res1->get_header_value("ETag");
  18553. // Test 1: Very long ETag value (longer than actual ETag)
  18554. // Should NOT match and return 200 (not trigger out-of-bounds read)
  18555. Headers h1 = {{"If-None-Match", "W/"
  18556. "\"very-long-etag-value-that-is-much-longer-"
  18557. "than-the-actual-etag-value\""}};
  18558. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  18559. ASSERT_TRUE(res2);
  18560. EXPECT_EQ(200, res2->status); // Should not match
  18561. // Test 2: Long string followed by wildcard
  18562. // Should match on "*" and return 304 (without out-of-bounds read on the long
  18563. // string)
  18564. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  18565. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  18566. ASSERT_TRUE(res3);
  18567. EXPECT_EQ(304, res3->status); // Should match on "*"
  18568. // Test 3: Wildcard followed by long string
  18569. // Should match on "*" immediately and return 304
  18570. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  18571. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  18572. ASSERT_TRUE(res4);
  18573. EXPECT_EQ(304, res4->status); // Should match on "*"
  18574. // Test 4: Multiple long non-matching values
  18575. // Should NOT match and return 200 (test that all comparisons are safe)
  18576. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  18577. "W/\"second-long-non-matching-value\", "
  18578. "W/\"third-long-non-matching-value\""}};
  18579. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  18580. ASSERT_TRUE(res5);
  18581. EXPECT_EQ(200, res5->status); // Should not match
  18582. // Test 5: Single character that is not "*" (edge case)
  18583. Headers h5 = {{"If-None-Match", "X"}};
  18584. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  18585. ASSERT_TRUE(res6);
  18586. EXPECT_EQ(200, res6->status); // Should not match
  18587. svr.stop();
  18588. t.join();
  18589. std::remove(fname);
  18590. }
  18591. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  18592. using namespace httplib;
  18593. // Create a test file
  18594. const char *fname = "ims_testfile.txt";
  18595. const char *content = "if-modified-since-test";
  18596. {
  18597. std::ofstream ofs(fname);
  18598. ofs << content;
  18599. ASSERT_TRUE(ofs.good());
  18600. }
  18601. Server svr;
  18602. svr.set_mount_point("/static", ".");
  18603. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18604. svr.wait_until_ready();
  18605. Client cli(HOST, PORT);
  18606. // First request: should get 200 with Last-Modified header
  18607. auto res1 = cli.Get("/static/ims_testfile.txt");
  18608. ASSERT_TRUE(res1);
  18609. ASSERT_EQ(200, res1->status);
  18610. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18611. std::string last_modified = res1->get_header_value("Last-Modified");
  18612. EXPECT_FALSE(last_modified.empty());
  18613. // If-Modified-Since with same time: expect 304
  18614. Headers h2 = {{"If-Modified-Since", last_modified}};
  18615. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18616. ASSERT_TRUE(res2);
  18617. EXPECT_EQ(304, res2->status);
  18618. // If-Modified-Since with future time: expect 304
  18619. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18620. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18621. ASSERT_TRUE(res3);
  18622. EXPECT_EQ(304, res3->status);
  18623. // If-Modified-Since with past time: expect 200
  18624. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18625. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18626. ASSERT_TRUE(res4);
  18627. EXPECT_EQ(200, res4->status);
  18628. // If-None-Match takes precedence over If-Modified-Since
  18629. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18630. ASSERT_TRUE(res1->has_header("ETag"));
  18631. std::string etag = res1->get_header_value("ETag");
  18632. Headers h5 = {{"If-None-Match", etag},
  18633. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18634. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18635. ASSERT_TRUE(res5);
  18636. EXPECT_EQ(304, res5->status);
  18637. svr.stop();
  18638. t.join();
  18639. std::remove(fname);
  18640. }
  18641. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18642. using namespace httplib;
  18643. Server svr;
  18644. // Endpoint that returns compressible content
  18645. svr.Get("/compressible", [](const Request &, Response &res) {
  18646. // Return a large enough body to trigger compression
  18647. std::string body(1000, 'a');
  18648. res.set_content(body, "text/plain");
  18649. });
  18650. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18651. svr.wait_until_ready();
  18652. Client cli(HOST, PORT);
  18653. // Request with gzip support: should get Vary header when compressed
  18654. cli.set_compress(true);
  18655. auto res1 = cli.Get("/compressible");
  18656. ASSERT_TRUE(res1);
  18657. EXPECT_EQ(200, res1->status);
  18658. // If Content-Encoding is set, Vary should also be set
  18659. if (res1->has_header("Content-Encoding")) {
  18660. EXPECT_TRUE(res1->has_header("Vary"));
  18661. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18662. }
  18663. // Request without Accept-Encoding header: should not have compression
  18664. Headers h_no_compress;
  18665. auto res2 = cli.Get("/compressible", h_no_compress);
  18666. ASSERT_TRUE(res2);
  18667. EXPECT_EQ(200, res2->status);
  18668. // Verify Vary header is present when compression is applied
  18669. // (the exact behavior depends on server configuration)
  18670. svr.stop();
  18671. t.join();
  18672. }
  18673. TEST(ETagTest, IfRangeWithETag) {
  18674. using namespace httplib;
  18675. // Create a test file with known content
  18676. const char *fname = "if_range_testfile.txt";
  18677. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18678. {
  18679. std::ofstream ofs(fname);
  18680. ofs << content;
  18681. ASSERT_TRUE(ofs.good());
  18682. }
  18683. Server svr;
  18684. svr.set_mount_point("/static", ".");
  18685. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18686. svr.wait_until_ready();
  18687. Client cli(HOST, PORT);
  18688. // First request: get ETag
  18689. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18690. ASSERT_TRUE(res1);
  18691. ASSERT_EQ(200, res1->status);
  18692. ASSERT_TRUE(res1->has_header("ETag"));
  18693. std::string etag = res1->get_header_value("ETag");
  18694. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18695. // Since our server generates weak ETags (W/"..."), If-Range with our
  18696. // ETag should NOT result in partial content - it should return full content.
  18697. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18698. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18699. ASSERT_TRUE(res2);
  18700. // Weak ETag in If-Range -> full content (200), not partial (206)
  18701. EXPECT_EQ(200, res2->status);
  18702. EXPECT_EQ(content, res2->body);
  18703. EXPECT_FALSE(res2->has_header("Content-Range"));
  18704. // Range request with non-matching If-Range (ETag): should get 200 (full
  18705. // content)
  18706. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18707. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18708. ASSERT_TRUE(res3);
  18709. EXPECT_EQ(200, res3->status);
  18710. EXPECT_EQ(content, res3->body);
  18711. EXPECT_FALSE(res3->has_header("Content-Range"));
  18712. // Range request with strong ETag (hypothetical - our server doesn't generate
  18713. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18714. // should return full content)
  18715. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18716. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18717. ASSERT_TRUE(res4);
  18718. EXPECT_EQ(200, res4->status);
  18719. EXPECT_EQ(content, res4->body);
  18720. EXPECT_FALSE(res4->has_header("Content-Range"));
  18721. svr.stop();
  18722. t.join();
  18723. std::remove(fname);
  18724. }
  18725. TEST(ETagTest, IfRangeWithDate) {
  18726. using namespace httplib;
  18727. // Create a test file
  18728. const char *fname = "if_range_date_testfile.txt";
  18729. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18730. {
  18731. std::ofstream ofs(fname);
  18732. ofs << content;
  18733. ASSERT_TRUE(ofs.good());
  18734. }
  18735. Server svr;
  18736. svr.set_mount_point("/static", ".");
  18737. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18738. svr.wait_until_ready();
  18739. Client cli(HOST, PORT);
  18740. // First request: get Last-Modified
  18741. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18742. ASSERT_TRUE(res1);
  18743. ASSERT_EQ(200, res1->status);
  18744. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18745. std::string last_modified = res1->get_header_value("Last-Modified");
  18746. // Range request with matching If-Range (date): should get 206
  18747. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18748. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18749. ASSERT_TRUE(res2);
  18750. EXPECT_EQ(206, res2->status);
  18751. EXPECT_EQ("FGHIJ", res2->body);
  18752. // Range request with old If-Range date: should get 200 (full content)
  18753. Headers h3 = {{"Range", "bytes=5-9"},
  18754. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18755. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18756. ASSERT_TRUE(res3);
  18757. EXPECT_EQ(200, res3->status);
  18758. EXPECT_EQ(content, res3->body);
  18759. // Range request with future If-Range date: should get 206
  18760. Headers h4 = {{"Range", "bytes=0-4"},
  18761. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18762. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18763. ASSERT_TRUE(res4);
  18764. EXPECT_EQ(206, res4->status);
  18765. EXPECT_EQ("ABCDE", res4->body);
  18766. svr.stop();
  18767. t.join();
  18768. std::remove(fname);
  18769. }
  18770. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18771. using namespace httplib;
  18772. const char *fname = "etag_malformed.txt";
  18773. const char *content = "malformed-etag";
  18774. {
  18775. std::ofstream ofs(fname);
  18776. ofs << content;
  18777. ASSERT_TRUE(ofs.good());
  18778. }
  18779. Server svr;
  18780. svr.set_mount_point("/static", ".");
  18781. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18782. svr.wait_until_ready();
  18783. Client cli(HOST, PORT);
  18784. // baseline: should get 200 and an ETag
  18785. auto res1 = cli.Get("/static/etag_malformed.txt");
  18786. ASSERT_TRUE(res1);
  18787. ASSERT_EQ(200, res1->status);
  18788. ASSERT_TRUE(res1->has_header("ETag"));
  18789. // Malformed ETag value (missing quotes) should be treated as non-matching
  18790. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18791. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18792. ASSERT_TRUE(res_bad);
  18793. EXPECT_EQ(200, res_bad->status);
  18794. // Whitespace-only header value should be considered invalid / non-matching
  18795. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18796. "Host: localhost\r\n"
  18797. "If-None-Match: \r\n"
  18798. "Connection: close\r\n"
  18799. "\r\n";
  18800. std::string out;
  18801. ASSERT_TRUE(send_request(5, raw_req, &out));
  18802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18803. svr.stop();
  18804. t.join();
  18805. std::remove(fname);
  18806. }
  18807. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18808. using namespace httplib;
  18809. const char *fname = "ims_invalid_format.txt";
  18810. const char *content = "ims-bad-format";
  18811. {
  18812. std::ofstream ofs(fname);
  18813. ofs << content;
  18814. ASSERT_TRUE(ofs.good());
  18815. }
  18816. Server svr;
  18817. svr.set_mount_point("/static", ".");
  18818. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18819. svr.wait_until_ready();
  18820. Client cli(HOST, PORT);
  18821. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18822. ASSERT_TRUE(res1);
  18823. ASSERT_EQ(200, res1->status);
  18824. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18825. // If-Modified-Since with invalid format should not result in 304
  18826. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18827. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18828. ASSERT_TRUE(res_bad);
  18829. EXPECT_EQ(200, res_bad->status);
  18830. // If-Range with invalid date format should be treated as mismatch -> full
  18831. // content (200)
  18832. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18833. {"If-Range", "invalid-date"}};
  18834. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18835. ASSERT_TRUE(res_ifrange);
  18836. EXPECT_EQ(200, res_ifrange->status);
  18837. svr.stop();
  18838. t.join();
  18839. std::remove(fname);
  18840. }
  18841. TEST(ETagTest, IfRangeWithMalformedETag) {
  18842. using namespace httplib;
  18843. const char *fname = "ifrange_malformed.txt";
  18844. const std::string content = "0123456789";
  18845. {
  18846. std::ofstream ofs(fname);
  18847. ofs << content;
  18848. ASSERT_TRUE(ofs.good());
  18849. }
  18850. Server svr;
  18851. svr.set_mount_point("/static", ".");
  18852. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18853. svr.wait_until_ready();
  18854. Client cli(HOST, PORT);
  18855. // First request: get ETag
  18856. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18857. ASSERT_TRUE(res1);
  18858. ASSERT_EQ(200, res1->status);
  18859. ASSERT_TRUE(res1->has_header("ETag"));
  18860. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18861. // full content (200)
  18862. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18863. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18864. ASSERT_TRUE(res2);
  18865. EXPECT_EQ(200, res2->status);
  18866. EXPECT_EQ(content, res2->body);
  18867. svr.stop();
  18868. t.join();
  18869. std::remove(fname);
  18870. }
  18871. TEST(ETagTest, ExtremeLargeDateValues) {
  18872. using namespace httplib;
  18873. const char *fname = "ims_extreme_date.txt";
  18874. const char *content = "ims-extreme-date";
  18875. {
  18876. std::ofstream ofs(fname);
  18877. ofs << content;
  18878. ASSERT_TRUE(ofs.good());
  18879. }
  18880. Server svr;
  18881. svr.set_mount_point("/static", ".");
  18882. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18883. svr.wait_until_ready();
  18884. Client cli(HOST, PORT);
  18885. auto res1 = cli.Get(std::string("/static/") + fname);
  18886. ASSERT_TRUE(res1);
  18887. ASSERT_EQ(200, res1->status);
  18888. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18889. // Extremely large year that may overflow date parsing routines.
  18890. Headers h_large_date = {
  18891. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18892. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18893. ASSERT_TRUE(res_bad);
  18894. // Expect server to treat this as invalid/mismatch and return full content
  18895. EXPECT_EQ(200, res_bad->status);
  18896. // If-Range with extremely large date should be treated as mismatch -> full
  18897. // content (200)
  18898. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18899. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18900. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18901. ASSERT_TRUE(res_ifrange);
  18902. EXPECT_EQ(200, res_ifrange->status);
  18903. svr.stop();
  18904. t.join();
  18905. std::remove(fname);
  18906. }
  18907. TEST(ETagTest, NegativeFileModificationTime) {
  18908. using namespace httplib;
  18909. const char *fname = "ims_negative_mtime.txt";
  18910. const std::string content = "negative-mtime";
  18911. {
  18912. std::ofstream ofs(fname);
  18913. ofs << content;
  18914. ASSERT_TRUE(ofs.good());
  18915. }
  18916. // Try to set file mtime to a negative value. This may fail on some
  18917. // platforms/filesystems; if it fails, the test will still verify server
  18918. // behaves safely by performing a regular conditional request.
  18919. #if defined(__APPLE__) || defined(__linux__)
  18920. bool set_negative = false;
  18921. do {
  18922. struct timeval times[2];
  18923. // access time: now
  18924. times[0].tv_sec = time(nullptr);
  18925. times[0].tv_usec = 0;
  18926. // modification time: negative (e.g., -1)
  18927. times[1].tv_sec = -1;
  18928. times[1].tv_usec = 0;
  18929. if (utimes(fname, times) == 0) { set_negative = true; }
  18930. } while (0);
  18931. #else
  18932. bool set_negative = false;
  18933. #endif
  18934. Server svr;
  18935. svr.set_mount_point("/static", ".");
  18936. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18937. svr.wait_until_ready();
  18938. Client cli(HOST, PORT);
  18939. auto res1 = cli.Get(std::string("/static/") + fname);
  18940. ASSERT_TRUE(res1);
  18941. ASSERT_EQ(200, res1->status);
  18942. bool has_last_modified = res1->has_header("Last-Modified");
  18943. std::string last_modified;
  18944. if (has_last_modified) {
  18945. last_modified = res1->get_header_value("Last-Modified");
  18946. }
  18947. if (set_negative) {
  18948. // If we successfully set a negative mtime, ensure server returns a
  18949. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18950. // with an old date and ensure server handles it without crash.
  18951. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18952. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18953. ASSERT_TRUE(res2);
  18954. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18955. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18956. } else {
  18957. // Could not set negative mtime on this platform; fall back to verifying
  18958. // that normal invalid/malformed dates are treated safely (non-304).
  18959. Headers h_bad_date = {
  18960. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18961. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18962. ASSERT_TRUE(res_bad);
  18963. EXPECT_EQ(200, res_bad->status);
  18964. }
  18965. svr.stop();
  18966. t.join();
  18967. std::remove(fname);
  18968. }
  18969. //==============================================================================
  18970. // Integration Tests with Server
  18971. //==============================================================================
  18972. class SSEIntegrationTest : public ::testing::Test {
  18973. protected:
  18974. void SetUp() override {
  18975. stop_server_.store(false);
  18976. events_.clear();
  18977. server_ = httplib::detail::make_unique<Server>();
  18978. setup_server();
  18979. start_server();
  18980. }
  18981. void TearDown() override {
  18982. stop_server_.store(true);
  18983. event_cv_.notify_all();
  18984. server_->stop();
  18985. if (server_thread_.joinable()) { server_thread_.join(); }
  18986. }
  18987. void setup_server() {
  18988. // Simple SSE endpoint
  18989. server_->Get("/events", [this](const Request &req, Response &res) {
  18990. auto last_id = req.get_header_value("Last-Event-ID");
  18991. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18992. res.set_chunked_content_provider(
  18993. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18994. std::unique_lock<std::mutex> lock(event_mutex_);
  18995. if (event_cv_.wait_for(
  18996. lock, std::chrono::milliseconds(200), [this] {
  18997. return !events_.empty() || stop_server_.load();
  18998. })) {
  18999. if (stop_server_.load()) { return false; }
  19000. if (!events_.empty()) {
  19001. std::string event = events_.front();
  19002. events_.erase(events_.begin());
  19003. sink.write(event.data(), event.size());
  19004. return true;
  19005. }
  19006. }
  19007. return !stop_server_.load();
  19008. });
  19009. });
  19010. // Endpoint that returns error
  19011. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19012. res.status = 500;
  19013. res.set_content("Internal Server Error", "text/plain");
  19014. });
  19015. // Endpoint for custom event types
  19016. server_->Get("/custom-events", [](const Request &, Response &res) {
  19017. res.set_chunked_content_provider(
  19018. "text/event-stream", [](size_t offset, DataSink &sink) {
  19019. if (offset == 0) {
  19020. std::string event = "event: update\ndata: updated\n\n"
  19021. "event: delete\ndata: deleted\n\n";
  19022. sink.write(event.data(), event.size());
  19023. }
  19024. return false; // End stream after sending
  19025. });
  19026. });
  19027. }
  19028. void start_server() {
  19029. port_ = server_->bind_to_any_port(HOST);
  19030. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19031. // Wait for server to start
  19032. while (!server_->is_running()) {
  19033. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19034. }
  19035. }
  19036. int get_port() const { return port_; }
  19037. void send_event(const std::string &event) {
  19038. std::lock_guard<std::mutex> lock(event_mutex_);
  19039. events_.push_back(event);
  19040. event_cv_.notify_all();
  19041. }
  19042. std::unique_ptr<Server> server_;
  19043. std::thread server_thread_;
  19044. std::mutex event_mutex_;
  19045. std::condition_variable event_cv_;
  19046. std::vector<std::string> events_;
  19047. std::atomic<bool> stop_server_{false};
  19048. std::string last_received_event_id_;
  19049. int port_ = 0;
  19050. };
  19051. //==============================================================================
  19052. // SSE Parsing Tests
  19053. //==============================================================================
  19054. class SSEParsingTest : public SSEIntegrationTest {
  19055. protected:
  19056. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19057. // A trailing sentinel event tells when the whole stream has been parsed.
  19058. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19059. auto body = stream + "event: end\ndata: end\n\n";
  19060. server_->Get("/parse", [body](const Request &, Response &res) {
  19061. res.set_content(body, "text/event-stream");
  19062. });
  19063. return collect("/parse");
  19064. }
  19065. // Runs SSEClient against path until an "end" event arrives and returns the
  19066. // messages dispatched before it
  19067. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19068. Client client(HOST, get_port());
  19069. sse::SSEClient sse(client, path);
  19070. std::mutex mutex;
  19071. std::condition_variable cv;
  19072. std::vector<sse::SSEMessage> messages;
  19073. auto done = false;
  19074. sse.on_message([&](const sse::SSEMessage &msg) {
  19075. std::lock_guard<std::mutex> lock(mutex);
  19076. // Ignore a replay from a reconnect that races with stop()
  19077. if (!done) { messages.push_back(msg); }
  19078. });
  19079. sse.on_event("end", [&](const sse::SSEMessage &) {
  19080. std::lock_guard<std::mutex> lock(mutex);
  19081. done = true;
  19082. cv.notify_all();
  19083. });
  19084. sse.set_reconnect_interval(100);
  19085. sse.start_async();
  19086. {
  19087. std::unique_lock<std::mutex> lock(mutex);
  19088. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19089. }
  19090. sse.stop();
  19091. EXPECT_TRUE(done);
  19092. return messages;
  19093. }
  19094. };
  19095. TEST_F(SSEParsingTest, SingleLineData) {
  19096. auto msgs = parse("data: hello\n\n");
  19097. ASSERT_EQ(msgs.size(), 1u);
  19098. EXPECT_EQ(msgs[0].data, "hello");
  19099. EXPECT_EQ(msgs[0].event, "message");
  19100. }
  19101. TEST_F(SSEParsingTest, MultiLineData) {
  19102. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19103. ASSERT_EQ(msgs.size(), 1u);
  19104. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19105. }
  19106. TEST_F(SSEParsingTest, CustomEventType) {
  19107. auto msgs = parse("event: update\ndata: payload\n\n");
  19108. ASSERT_EQ(msgs.size(), 1u);
  19109. EXPECT_EQ(msgs[0].event, "update");
  19110. EXPECT_EQ(msgs[0].data, "payload");
  19111. }
  19112. TEST_F(SSEParsingTest, EventIdHandling) {
  19113. auto msgs = parse("id: 12345\ndata: test\n\n");
  19114. ASSERT_EQ(msgs.size(), 1u);
  19115. EXPECT_EQ(msgs[0].id, "12345");
  19116. }
  19117. TEST_F(SSEParsingTest, EmptyEventId) {
  19118. auto msgs = parse("id:\ndata: test\n\n");
  19119. ASSERT_EQ(msgs.size(), 1u);
  19120. EXPECT_EQ(msgs[0].id, "");
  19121. }
  19122. TEST_F(SSEParsingTest, CommentsIgnored) {
  19123. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19124. ASSERT_EQ(msgs.size(), 1u);
  19125. EXPECT_EQ(msgs[0].data, "hello");
  19126. EXPECT_EQ(msgs[0].event, "message");
  19127. }
  19128. TEST_F(SSEParsingTest, ColonInValue) {
  19129. auto msgs = parse("data: hello:world:test\n\n");
  19130. ASSERT_EQ(msgs.size(), 1u);
  19131. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19132. }
  19133. TEST_F(SSEParsingTest, FieldNameOnly) {
  19134. // A line without a colon is a field name with an empty value
  19135. auto msgs = parse("data\n\n");
  19136. ASSERT_EQ(msgs.size(), 1u);
  19137. EXPECT_EQ(msgs[0].data, "");
  19138. }
  19139. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19140. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19141. ASSERT_EQ(msgs.size(), 1u);
  19142. EXPECT_EQ(msgs[0].event, "update");
  19143. EXPECT_EQ(msgs[0].data, "hello");
  19144. }
  19145. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19146. auto msgs = parse("data\r\n\r\n");
  19147. ASSERT_EQ(msgs.size(), 1u);
  19148. EXPECT_EQ(msgs[0].data, "");
  19149. }
  19150. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19151. auto msgs = parse("event: update\rdata: hello\r\r");
  19152. ASSERT_EQ(msgs.size(), 1u);
  19153. EXPECT_EQ(msgs[0].event, "update");
  19154. EXPECT_EQ(msgs[0].data, "hello");
  19155. }
  19156. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19157. // Chunk boundaries fall inside every \r\n and right before the first one
  19158. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19159. "\n\r", "\nevent: end\ndata: end\n\n"};
  19160. server_->Get("/split", [chunks](const Request &, Response &res) {
  19161. auto i = std::make_shared<size_t>(0);
  19162. res.set_chunked_content_provider(
  19163. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19164. if (*i == chunks.size()) {
  19165. sink.done();
  19166. } else {
  19167. sink.write(chunks[*i].data(), chunks[*i].size());
  19168. (*i)++;
  19169. }
  19170. return true;
  19171. });
  19172. });
  19173. auto msgs = collect("/split");
  19174. ASSERT_EQ(msgs.size(), 1u);
  19175. EXPECT_EQ(msgs[0].event, "update");
  19176. EXPECT_EQ(msgs[0].data, "hello");
  19177. }
  19178. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19179. // Only a BOM at the start of the stream is ignored
  19180. auto msgs = parse("\xEF\xBB\xBF"
  19181. "data: first\n\n"
  19182. "\xEF\xBB\xBF"
  19183. "data: second\n\n");
  19184. ASSERT_EQ(msgs.size(), 1u);
  19185. EXPECT_EQ(msgs[0].data, "first");
  19186. }
  19187. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19188. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19189. ASSERT_EQ(msgs.size(), 1u);
  19190. EXPECT_EQ(msgs[0].data, "hello");
  19191. EXPECT_EQ(msgs[0].event, "message");
  19192. }
  19193. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19194. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19195. ASSERT_EQ(msgs.size(), 2u);
  19196. EXPECT_EQ(msgs[0].data, "hello");
  19197. EXPECT_EQ(msgs[1].data, "hello");
  19198. }
  19199. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19200. // An event without data is not dispatched, and its type must not leak
  19201. // into the next event
  19202. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19203. ASSERT_EQ(msgs.size(), 1u);
  19204. EXPECT_EQ(msgs[0].event, "message");
  19205. EXPECT_EQ(msgs[0].data, "hello");
  19206. }
  19207. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19208. // The first connection sends only an id; the second echoes back the
  19209. // Last-Event-ID it was reconnected with
  19210. std::atomic<int> connection_count{0};
  19211. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19212. if (connection_count++ == 0) {
  19213. res.set_content("id: 42\n\n", "text/event-stream");
  19214. } else {
  19215. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19216. "\n\nevent: end\ndata: end\n\n",
  19217. "text/event-stream");
  19218. }
  19219. });
  19220. auto msgs = collect("/id-only");
  19221. ASSERT_EQ(msgs.size(), 1u);
  19222. EXPECT_EQ(msgs[0].data, "42");
  19223. }
  19224. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19225. // The first connection sets an id and then clears it with an empty one; the
  19226. // second reports whether it was reconnected with a Last-Event-ID
  19227. std::atomic<int> connection_count{0};
  19228. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19229. if (connection_count++ == 0) {
  19230. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  19231. "text/event-stream");
  19232. } else {
  19233. res.set_content(
  19234. std::string("data: ") +
  19235. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  19236. "\n\nevent: end\ndata: end\n\n",
  19237. "text/event-stream");
  19238. }
  19239. });
  19240. auto msgs = collect("/id-clear");
  19241. ASSERT_EQ(msgs.size(), 3u);
  19242. EXPECT_EQ(msgs[0].id, "1");
  19243. EXPECT_EQ(msgs[1].id, "");
  19244. EXPECT_EQ(msgs[2].data, "not sent");
  19245. }
  19246. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  19247. // The first connection sets an id and then sends ids that cannot be carried
  19248. // in a header; the second echoes back the Last-Event-ID it was reconnected
  19249. // with
  19250. std::atomic<int> connection_count{0};
  19251. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  19252. if (connection_count++ == 0) {
  19253. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  19254. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  19255. "text/event-stream");
  19256. } else {
  19257. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19258. "\n\nevent: end\ndata: end\n\n",
  19259. "text/event-stream");
  19260. }
  19261. });
  19262. auto msgs = collect("/id-unsendable");
  19263. ASSERT_EQ(msgs.size(), 1u);
  19264. EXPECT_EQ(msgs[0].data, "42");
  19265. }
  19266. TEST_F(SSEParsingTest, CompleteEventParsing) {
  19267. auto msgs = parse("event: notification\nid: evt-42\n"
  19268. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  19269. ASSERT_EQ(msgs.size(), 1u);
  19270. EXPECT_EQ(msgs[0].event, "notification");
  19271. EXPECT_EQ(msgs[0].id, "evt-42");
  19272. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  19273. }
  19274. TEST(SSEMessageTest, Clear) {
  19275. sse::SSEMessage msg;
  19276. msg.event = "custom";
  19277. msg.data = "some data";
  19278. msg.id = "123";
  19279. msg.clear();
  19280. EXPECT_EQ(msg.event, "message");
  19281. EXPECT_EQ(msg.data, "");
  19282. EXPECT_EQ(msg.id, "");
  19283. }
  19284. //==============================================================================
  19285. // SSE Integration Tests
  19286. //==============================================================================
  19287. // Test: Successful connection and on_open callback
  19288. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  19289. // Add a simple endpoint that sends one event and closes
  19290. server_->Get("/simple-event", [](const Request &, Response &res) {
  19291. res.set_chunked_content_provider(
  19292. "text/event-stream", [](size_t offset, DataSink &sink) {
  19293. if (offset == 0) {
  19294. std::string event = "data: hello\n\n";
  19295. sink.write(event.data(), event.size());
  19296. }
  19297. return false; // Close stream after sending
  19298. });
  19299. });
  19300. Client client("localhost", get_port());
  19301. sse::SSEClient sse(client, "/simple-event");
  19302. std::atomic<bool> open_called{false};
  19303. std::atomic<bool> message_received{false};
  19304. sse.on_open([&open_called]() { open_called.store(true); });
  19305. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  19306. if (msg.data == "hello") { message_received.store(true); }
  19307. });
  19308. sse.set_reconnect_interval(100);
  19309. sse.set_max_reconnect_attempts(1);
  19310. // Start async
  19311. sse.start_async();
  19312. // Wait for message to be processed
  19313. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19314. sse.stop();
  19315. EXPECT_TRUE(open_called.load());
  19316. EXPECT_TRUE(message_received.load());
  19317. }
  19318. // Test: on_message callback
  19319. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  19320. // Endpoint that sends multiple events then closes
  19321. server_->Get("/multi-event", [](const Request &, Response &res) {
  19322. res.set_chunked_content_provider(
  19323. "text/event-stream", [](size_t offset, DataSink &sink) {
  19324. if (offset == 0) {
  19325. std::string events = "data: message1\n\ndata: message2\n\n";
  19326. sink.write(events.data(), events.size());
  19327. }
  19328. return false;
  19329. });
  19330. });
  19331. Client client("localhost", get_port());
  19332. sse::SSEClient sse(client, "/multi-event");
  19333. std::vector<std::string> received_messages;
  19334. std::mutex messages_mutex;
  19335. sse.on_message([&](const sse::SSEMessage &msg) {
  19336. std::lock_guard<std::mutex> lock(messages_mutex);
  19337. received_messages.push_back(msg.data);
  19338. });
  19339. sse.set_reconnect_interval(100);
  19340. sse.set_max_reconnect_attempts(1);
  19341. sse.start_async();
  19342. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19343. sse.stop();
  19344. std::lock_guard<std::mutex> lock(messages_mutex);
  19345. EXPECT_GE(received_messages.size(), 2u);
  19346. if (received_messages.size() >= 2) {
  19347. EXPECT_EQ(received_messages[0], "message1");
  19348. EXPECT_EQ(received_messages[1], "message2");
  19349. }
  19350. }
  19351. // Test: on_event for specific types
  19352. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  19353. Client client("localhost", get_port());
  19354. sse::SSEClient sse(client, "/custom-events");
  19355. std::atomic<bool> update_received{false};
  19356. std::atomic<bool> delete_received{false};
  19357. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  19358. if (msg.data == "updated") { update_received.store(true); }
  19359. });
  19360. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  19361. if (msg.data == "deleted") { delete_received.store(true); }
  19362. });
  19363. sse.set_max_reconnect_attempts(1);
  19364. sse.start_async();
  19365. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  19366. sse.stop();
  19367. EXPECT_TRUE(update_received.load());
  19368. EXPECT_TRUE(delete_received.load());
  19369. }
  19370. // Test: on_error callback on connection failure
  19371. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  19372. // Connect to a non-existent port
  19373. Client client("localhost", 59999);
  19374. sse::SSEClient sse(client, "/events");
  19375. std::atomic<bool> error_called{false};
  19376. Error received_error = Error::Success;
  19377. sse.on_error([&](Error err) {
  19378. error_called.store(true);
  19379. received_error = err;
  19380. });
  19381. sse.set_reconnect_interval(50);
  19382. sse.set_max_reconnect_attempts(1);
  19383. sse.start_async();
  19384. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19385. sse.stop();
  19386. EXPECT_TRUE(error_called.load());
  19387. EXPECT_NE(received_error, Error::Success);
  19388. }
  19389. // Test: Last-Event-ID header sent on reconnect
  19390. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  19391. // Endpoint that sends event with ID
  19392. server_->Get("/event-with-id", [](const Request &, Response &res) {
  19393. res.set_chunked_content_provider(
  19394. "text/event-stream", [](size_t offset, DataSink &sink) {
  19395. if (offset == 0) {
  19396. std::string event = "id: evt-123\ndata: test\n\n";
  19397. sink.write(event.data(), event.size());
  19398. }
  19399. return false;
  19400. });
  19401. });
  19402. Client client("localhost", get_port());
  19403. sse::SSEClient sse(client, "/event-with-id");
  19404. std::atomic<bool> id_received{false};
  19405. sse.on_message([&](const sse::SSEMessage &msg) {
  19406. if (!msg.id.empty()) { id_received.store(true); }
  19407. });
  19408. sse.set_reconnect_interval(100);
  19409. sse.set_max_reconnect_attempts(1);
  19410. sse.start_async();
  19411. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19412. sse.stop();
  19413. EXPECT_TRUE(id_received.load());
  19414. EXPECT_EQ(sse.last_event_id(), "evt-123");
  19415. }
  19416. // Test: Manual stop
  19417. TEST_F(SSEIntegrationTest, ManualStop) {
  19418. // Endpoint that sends one event and stays open briefly
  19419. std::atomic<bool> handler_running{true};
  19420. server_->Get("/stay-open", [&handler_running](const Request &,
  19421. Response &res) {
  19422. res.set_chunked_content_provider(
  19423. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  19424. if (offset == 0) {
  19425. std::string event = "data: connected\n\n";
  19426. sink.write(event.data(), event.size());
  19427. }
  19428. // Keep connection open while handler_running is true
  19429. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  19430. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19431. }
  19432. return false;
  19433. });
  19434. });
  19435. Client client("localhost", get_port());
  19436. sse::SSEClient sse(client, "/stay-open");
  19437. std::atomic<bool> connected{false};
  19438. sse.on_open([&connected]() { connected.store(true); });
  19439. sse.set_reconnect_interval(100);
  19440. sse.set_max_reconnect_attempts(1);
  19441. sse.start_async();
  19442. // Wait for connection to establish
  19443. for (int i = 0; i < 20 && !connected.load(); ++i) {
  19444. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  19445. }
  19446. EXPECT_TRUE(connected.load());
  19447. EXPECT_TRUE(sse.is_connected());
  19448. // Signal handler to stop
  19449. handler_running.store(false);
  19450. // Stop SSE client
  19451. sse.stop();
  19452. EXPECT_FALSE(sse.is_connected());
  19453. }
  19454. // Test: SSEClient with custom headers
  19455. TEST_F(SSEIntegrationTest, CustomHeaders) {
  19456. // Setup a server endpoint that checks for custom header
  19457. std::atomic<bool> header_received{false};
  19458. server_->Get("/header-check", [&](const Request &req, Response &res) {
  19459. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  19460. header_received.store(true);
  19461. }
  19462. res.set_chunked_content_provider("text/event-stream",
  19463. [](size_t, DataSink &) { return false; });
  19464. });
  19465. Client client("localhost", get_port());
  19466. Headers headers = {{"X-Custom-Header", "custom-value"}};
  19467. sse::SSEClient sse(client, "/header-check", headers);
  19468. sse.set_max_reconnect_attempts(1);
  19469. sse.start_async();
  19470. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  19471. sse.stop();
  19472. EXPECT_TRUE(header_received.load());
  19473. }
  19474. // Test: Reconnect interval configuration
  19475. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  19476. Client client("localhost", get_port());
  19477. sse::SSEClient sse(client, "/events");
  19478. auto &result = sse.set_reconnect_interval(500);
  19479. // Builder pattern should return reference to self
  19480. EXPECT_EQ(&result, &sse);
  19481. }
  19482. // Test: Max reconnect attempts
  19483. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  19484. // Connect to non-existent port to force reconnects
  19485. Client client("localhost", 59998);
  19486. sse::SSEClient sse(client, "/events");
  19487. std::atomic<int> error_count{0};
  19488. sse.on_error([&](Error) { error_count.fetch_add(1); });
  19489. sse.set_reconnect_interval(50);
  19490. sse.set_max_reconnect_attempts(2);
  19491. auto start = std::chrono::steady_clock::now();
  19492. sse.start(); // Blocking call
  19493. auto end = std::chrono::steady_clock::now();
  19494. // Should have stopped after 2 failed attempts
  19495. EXPECT_GE(error_count.load(), 2);
  19496. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  19497. auto duration =
  19498. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  19499. #ifdef _WIN32
  19500. // Windows is much slower for socket connection failures
  19501. EXPECT_LT(duration.count(), 7000);
  19502. #else
  19503. EXPECT_LT(duration.count(), 1000);
  19504. #endif
  19505. }
  19506. // Test: Multi-line data in integration
  19507. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  19508. // Endpoint with multi-line data
  19509. server_->Get("/multiline-data", [](const Request &, Response &res) {
  19510. res.set_chunked_content_provider(
  19511. "text/event-stream", [](size_t offset, DataSink &sink) {
  19512. if (offset == 0) {
  19513. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  19514. sink.write(event.data(), event.size());
  19515. }
  19516. return false;
  19517. });
  19518. });
  19519. Client client("localhost", get_port());
  19520. sse::SSEClient sse(client, "/multiline-data");
  19521. std::string received_data;
  19522. std::mutex data_mutex;
  19523. sse.on_message([&](const sse::SSEMessage &msg) {
  19524. std::lock_guard<std::mutex> lock(data_mutex);
  19525. received_data = msg.data;
  19526. });
  19527. sse.set_reconnect_interval(100);
  19528. sse.set_max_reconnect_attempts(1);
  19529. sse.start_async();
  19530. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19531. sse.stop();
  19532. std::lock_guard<std::mutex> lock(data_mutex);
  19533. EXPECT_EQ(received_data, "line1\nline2\nline3");
  19534. }
  19535. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  19536. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  19537. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  19538. DataSink &sink) {
  19539. if (offset == 0) {
  19540. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  19541. sink.write(events.data(), events.size());
  19542. }
  19543. return false;
  19544. });
  19545. });
  19546. Client client("localhost", get_port());
  19547. sse::SSEClient sse(client, "/empty-data-lines");
  19548. std::mutex mutex;
  19549. std::condition_variable cv;
  19550. std::vector<std::string> received;
  19551. sse.on_message([&](const sse::SSEMessage &msg) {
  19552. std::lock_guard<std::mutex> lock(mutex);
  19553. received.push_back(msg.data);
  19554. cv.notify_all();
  19555. });
  19556. sse.set_max_reconnect_attempts(1);
  19557. sse.start_async();
  19558. {
  19559. std::unique_lock<std::mutex> lock(mutex);
  19560. cv.wait_for(lock, std::chrono::seconds(2),
  19561. [&] { return received.size() >= 3; });
  19562. }
  19563. sse.stop();
  19564. ASSERT_GE(received.size(), 3u);
  19565. EXPECT_EQ(received[0], "");
  19566. EXPECT_EQ(received[1], "\nhello");
  19567. EXPECT_EQ(received[2], "");
  19568. }
  19569. // Test: Auto-reconnect after server disconnection
  19570. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  19571. std::atomic<int> connection_count{0};
  19572. std::atomic<int> message_count{0};
  19573. // Endpoint that sends one event and closes, forcing reconnect
  19574. server_->Get("/reconnect-test",
  19575. [&connection_count](const Request &, Response &res) {
  19576. connection_count.fetch_add(1);
  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 connection after sending
  19584. });
  19585. });
  19586. Client client("localhost", get_port());
  19587. sse::SSEClient sse(client, "/reconnect-test");
  19588. sse.on_message([&message_count](const sse::SSEMessage &) {
  19589. message_count.fetch_add(1);
  19590. });
  19591. sse.set_reconnect_interval(100);
  19592. sse.set_max_reconnect_attempts(3);
  19593. sse.start_async();
  19594. // Wait long enough for multiple reconnects
  19595. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19596. sse.stop();
  19597. // Should have connected multiple times (initial + reconnects)
  19598. EXPECT_GE(connection_count.load(), 2);
  19599. // Should have received messages from multiple connections
  19600. EXPECT_GE(message_count.load(), 2);
  19601. }
  19602. // Test: A retry field that is not all ASCII digits is ignored
  19603. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  19604. std::atomic<int> connection_count{0};
  19605. server_->Get("/bad-retry",
  19606. [&connection_count](const Request &, Response &res) {
  19607. connection_count.fetch_add(1);
  19608. res.set_chunked_content_provider(
  19609. "text/event-stream", [](size_t offset, DataSink &sink) {
  19610. if (offset == 0) {
  19611. std::string event = "retry: -1\ndata: hello\n\n";
  19612. sink.write(event.data(), event.size());
  19613. }
  19614. return false;
  19615. });
  19616. });
  19617. Client client("localhost", get_port());
  19618. sse::SSEClient sse(client, "/bad-retry");
  19619. sse.set_reconnect_interval(10000);
  19620. sse.start_async();
  19621. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19622. sse.stop();
  19623. EXPECT_EQ(connection_count.load(), 1);
  19624. }
  19625. // Test: A retry field of all ASCII digits sets the reconnection time
  19626. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  19627. std::atomic<int> connection_count{0};
  19628. server_->Get("/zero-retry",
  19629. [&connection_count](const Request &, Response &res) {
  19630. connection_count.fetch_add(1);
  19631. res.set_chunked_content_provider(
  19632. "text/event-stream", [](size_t offset, DataSink &sink) {
  19633. if (offset == 0) {
  19634. std::string event = "retry: 0\ndata: hello\n\n";
  19635. sink.write(event.data(), event.size());
  19636. }
  19637. return false;
  19638. });
  19639. });
  19640. Client client("localhost", get_port());
  19641. sse::SSEClient sse(client, "/zero-retry");
  19642. sse.set_reconnect_interval(10000);
  19643. sse.start_async();
  19644. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19645. sse.stop();
  19646. // The server-supplied interval is applied, but never below 100ms, so
  19647. // "retry: 0" does not cause a busy reconnect loop
  19648. EXPECT_GE(connection_count.load(), 2);
  19649. EXPECT_LE(connection_count.load(), 10);
  19650. }
  19651. // Test: Last-Event-ID sent on reconnect
  19652. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  19653. std::atomic<int> connection_count{0};
  19654. std::vector<std::string> received_last_event_ids;
  19655. std::mutex id_mutex;
  19656. // Endpoint that checks Last-Event-ID header and sends event with ID
  19657. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  19658. int conn = connection_count.fetch_add(1);
  19659. // Capture the Last-Event-ID header from each connection
  19660. {
  19661. std::lock_guard<std::mutex> lock(id_mutex);
  19662. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  19663. }
  19664. res.set_chunked_content_provider(
  19665. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  19666. if (offset == 0) {
  19667. std::string event =
  19668. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  19669. sink.write(event.data(), event.size());
  19670. }
  19671. return false;
  19672. });
  19673. });
  19674. Client client("localhost", get_port());
  19675. sse::SSEClient sse(client, "/reconnect-with-id");
  19676. sse.set_reconnect_interval(100);
  19677. sse.set_max_reconnect_attempts(3);
  19678. sse.start_async();
  19679. // Wait for at least 2 connections
  19680. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  19681. sse.stop();
  19682. // Verify behavior
  19683. std::lock_guard<std::mutex> lock(id_mutex);
  19684. EXPECT_GE(received_last_event_ids.size(), 2u);
  19685. // First connection should have no Last-Event-ID
  19686. if (!received_last_event_ids.empty()) {
  19687. EXPECT_EQ(received_last_event_ids[0], "");
  19688. }
  19689. // Second connection should have Last-Event-ID from first connection
  19690. if (received_last_event_ids.size() >= 2) {
  19691. EXPECT_EQ(received_last_event_ids[1], "event-0");
  19692. }
  19693. }
  19694. // Test: set_headers updates headers used on reconnect
  19695. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  19696. std::vector<std::string> received_tokens;
  19697. std::mutex token_mutex;
  19698. // Endpoint that captures Authorization header
  19699. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  19700. {
  19701. std::lock_guard<std::mutex> lock(token_mutex);
  19702. received_tokens.push_back(req.get_header_value("Authorization"));
  19703. }
  19704. res.set_chunked_content_provider(
  19705. "text/event-stream", [](size_t offset, DataSink &sink) {
  19706. if (offset == 0) {
  19707. std::string event = "data: hello\n\n";
  19708. sink.write(event.data(), event.size());
  19709. }
  19710. return false; // Close connection to trigger reconnect
  19711. });
  19712. });
  19713. Client client("localhost", get_port());
  19714. Headers headers = {{"Authorization", "Bearer old-token"}};
  19715. sse::SSEClient sse(client, "/auth-check", headers);
  19716. // Update headers on each successful connection
  19717. sse.on_open(
  19718. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  19719. sse.set_reconnect_interval(100);
  19720. sse.set_max_reconnect_attempts(3);
  19721. sse.start_async();
  19722. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19723. sse.stop();
  19724. std::lock_guard<std::mutex> lock(token_mutex);
  19725. ASSERT_GE(received_tokens.size(), 2u);
  19726. // First connection uses original header
  19727. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  19728. // Second connection uses updated header from set_headers
  19729. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  19730. }
  19731. // Test: 401 allows reconnection (so on_error can refresh headers)
  19732. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  19733. std::atomic<int> connection_count{0};
  19734. // Endpoint: returns 401 on first attempt, 200 on second
  19735. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  19736. int conn = connection_count.fetch_add(1);
  19737. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19738. res.status = StatusCode::Unauthorized_401;
  19739. res.set_content("Unauthorized", "text/plain");
  19740. return;
  19741. }
  19742. res.set_chunked_content_provider(
  19743. "text/event-stream", [](size_t offset, DataSink &sink) {
  19744. if (offset == 0) {
  19745. std::string event = "data: authenticated\n\n";
  19746. sink.write(event.data(), event.size());
  19747. }
  19748. return false;
  19749. });
  19750. });
  19751. Client client("localhost", get_port());
  19752. Headers headers = {{"Authorization", "Bearer expired"}};
  19753. sse::SSEClient sse(client, "/auth-retry", headers);
  19754. std::atomic<bool> message_received{false};
  19755. // Refresh token on error
  19756. sse.on_error(
  19757. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19758. sse.on_message([&](const sse::SSEMessage &msg) {
  19759. if (msg.data == "authenticated") { message_received.store(true); }
  19760. });
  19761. sse.set_reconnect_interval(100);
  19762. sse.set_max_reconnect_attempts(3);
  19763. sse.start_async();
  19764. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19765. sse.stop();
  19766. // Should have reconnected after 401 and succeeded with new token
  19767. EXPECT_GE(connection_count.load(), 2);
  19768. EXPECT_TRUE(message_received.load());
  19769. }
  19770. TEST(Issue2318Test, EmptyHostString) {
  19771. {
  19772. httplib::Client cli_empty("", PORT);
  19773. auto res = cli_empty.Get("/");
  19774. ASSERT_FALSE(res);
  19775. EXPECT_EQ(httplib::Error::Connection, res.error());
  19776. }
  19777. {
  19778. httplib::Client cli(" ", PORT);
  19779. auto res = cli.Get("/");
  19780. ASSERT_FALSE(res);
  19781. EXPECT_EQ(httplib::Error::Connection, res.error());
  19782. }
  19783. }
  19784. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19785. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19786. Server svr;
  19787. // Set a small payload limit (1KB)
  19788. svr.set_payload_max_length(1024);
  19789. svr.Post("/test", [&](const Request &req, Response &res) {
  19790. res.set_content("Body size: " + std::to_string(req.body.size()),
  19791. "text/plain");
  19792. });
  19793. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19794. auto se = detail::scope_exit([&] {
  19795. svr.stop();
  19796. listen_thread.join();
  19797. });
  19798. svr.wait_until_ready();
  19799. // Create data that compresses well but exceeds limit when decompressed
  19800. // 8KB of repeated null bytes compresses to a very small size
  19801. std::string original_data(8 * 1024, '\0');
  19802. // Compress the data using gzip
  19803. std::string compressed_data;
  19804. detail::gzip_compressor compressor;
  19805. compressor.compress(original_data.data(), original_data.size(), true,
  19806. [&](const char *data, size_t size) {
  19807. compressed_data.append(data, size);
  19808. return true;
  19809. });
  19810. // Verify compression worked (compressed should be much smaller)
  19811. ASSERT_LT(compressed_data.size(), original_data.size());
  19812. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19813. // Send compressed data with Content-Encoding: gzip
  19814. Client cli(HOST, PORT);
  19815. Headers headers = {{"Content-Encoding", "gzip"}};
  19816. auto res =
  19817. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19818. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19820. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19821. }
  19822. #endif
  19823. // ============================================================================
  19824. // OpenSSL-Specific Tests
  19825. // ============================================================================
  19826. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19827. X509 *readCertificate(const std::string &strFileName) {
  19828. std::ifstream inStream(strFileName);
  19829. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19830. std::istreambuf_iterator<char>());
  19831. if (strCertPEM.empty()) return (nullptr);
  19832. BIO *pbCert = BIO_new(BIO_s_mem());
  19833. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19834. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19835. BIO_free(pbCert);
  19836. return (pCert);
  19837. }
  19838. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19839. std::ifstream inStream(strFileName);
  19840. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19841. std::istreambuf_iterator<char>());
  19842. if (strPrivateKeyPEM.empty()) return (nullptr);
  19843. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19844. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19845. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19846. BIO_free(pbPrivKey);
  19847. return (pPrivateKey);
  19848. }
  19849. TEST(BindServerTest, UpdateCerts) {
  19850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19851. int port = svr.bind_to_any_port("0.0.0.0");
  19852. ASSERT_TRUE(svr.is_valid());
  19853. ASSERT_TRUE(port > 0);
  19854. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19855. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19856. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19857. ASSERT_TRUE(cert != nullptr);
  19858. ASSERT_TRUE(ca_cert != nullptr);
  19859. ASSERT_TRUE(key != nullptr);
  19860. X509_STORE *cert_store = X509_STORE_new();
  19861. X509_STORE_add_cert(cert_store, ca_cert);
  19862. // svr.update_certs(cert, key, cert_store); // deprecated
  19863. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19864. CLIENT_CA_CERT_FILE);
  19865. ASSERT_TRUE(svr.is_valid());
  19866. svr.stop();
  19867. X509_STORE_free(cert_store);
  19868. X509_free(cert);
  19869. X509_free(ca_cert);
  19870. EVP_PKEY_free(key);
  19871. }
  19872. // Test that update_certs() updates client CA list correctly
  19873. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19874. // Start with file-based constructor
  19875. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19876. ASSERT_TRUE(svr.is_valid());
  19877. // Initially no client CA list should be set
  19878. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19879. ASSERT_TRUE(ssl_ctx != nullptr);
  19880. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19881. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19882. EXPECT_EQ(0, count_before);
  19883. // Now update with client CA (PEM string)
  19884. std::string cert_pem, key_pem, ca_pem;
  19885. read_file(SERVER_CERT_FILE, cert_pem);
  19886. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19887. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19888. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19889. ASSERT_TRUE(svr.is_valid());
  19890. // Now client CA list should be set
  19891. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19892. ASSERT_TRUE(ca_list_after != nullptr);
  19893. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19894. }
  19895. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19896. // Test that the file-path SSLServer constructor properly sets the client CA
  19897. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19899. ASSERT_TRUE(svr.is_valid());
  19900. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19901. ASSERT_TRUE(ssl_ctx != nullptr);
  19902. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19903. ASSERT_TRUE(ca_list != nullptr);
  19904. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19905. }
  19906. #endif
  19907. // ============================================================================
  19908. // MbedTLS-Specific Tests
  19909. // ============================================================================
  19910. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19911. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19912. using namespace httplib::tls;
  19913. // Track if callback was invoked
  19914. bool callback_invoked = false;
  19915. // The callback receives void* ctx which is actually MbedTlsContext*
  19916. // We can access the mbedtls_ssl_config via the context
  19917. auto setup_callback = [&callback_invoked](void *ctx) {
  19918. callback_invoked = true;
  19919. // Cast to MbedTlsContext* to access the ssl config
  19920. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19921. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19922. // Use static variables to hold certificate data (simplified for test)
  19923. static mbedtls_x509_crt own_cert;
  19924. static mbedtls_pk_context own_key;
  19925. static mbedtls_x509_crt ca_chain;
  19926. static bool initialized = false;
  19927. if (!initialized) {
  19928. mbedtls_x509_crt_init(&own_cert);
  19929. mbedtls_pk_init(&own_key);
  19930. mbedtls_x509_crt_init(&ca_chain);
  19931. // Load server certificate
  19932. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19933. return false;
  19934. }
  19935. // Load server private key.
  19936. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19937. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19938. #if MBEDTLS_VERSION_MAJOR == 3
  19939. ,
  19940. mbedtls_ctr_drbg_random, nullptr
  19941. #endif
  19942. ) != 0) {
  19943. return false;
  19944. }
  19945. // Load CA chain for client verification
  19946. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19947. return false;
  19948. }
  19949. initialized = true;
  19950. }
  19951. // Configure the SSL config
  19952. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19953. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19954. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19955. // Set minimum TLS version using mbedTLS native API
  19956. #if MBEDTLS_VERSION_MAJOR >= 3
  19957. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19958. #else
  19959. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19960. MBEDTLS_SSL_MINOR_VERSION_3);
  19961. #endif
  19962. return true;
  19963. };
  19964. SSLServer svr(setup_callback);
  19965. ASSERT_TRUE(svr.is_valid());
  19966. ASSERT_TRUE(callback_invoked);
  19967. svr.Get("/test", [&](const Request &req, Response &res) {
  19968. res.set_content("test", "text/plain");
  19969. auto cert = req.peer_cert();
  19970. ASSERT_TRUE(static_cast<bool>(cert));
  19971. auto common_name = cert.subject_cn();
  19972. EXPECT_EQ("Common Name", common_name);
  19973. });
  19974. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19975. auto se = detail::scope_exit([&] {
  19976. svr.stop();
  19977. t.join();
  19978. ASSERT_FALSE(svr.is_running());
  19979. });
  19980. svr.wait_until_ready();
  19981. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19982. cli.enable_server_certificate_verification(false);
  19983. cli.set_connection_timeout(30);
  19984. auto res = cli.Get("/test");
  19985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19986. ASSERT_EQ(StatusCode::OK_200, res->status);
  19987. }
  19988. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19989. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19990. // keep-alive SSL session, which reads through that config in
  19991. // mbedtls_ssl_close_notify.
  19992. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19994. ASSERT_TRUE(svr.is_valid());
  19995. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19996. res.set_content("test", "text/plain");
  19997. });
  19998. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19999. auto se = detail::scope_exit([&] {
  20000. svr.stop();
  20001. t.join();
  20002. ASSERT_FALSE(svr.is_running());
  20003. });
  20004. svr.wait_until_ready();
  20005. {
  20006. SSLClient cli(HOST, PORT);
  20007. cli.enable_server_certificate_verification(false);
  20008. cli.set_keep_alive(true);
  20009. auto res = cli.Get("/test");
  20010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20011. ASSERT_EQ(StatusCode::OK_200, res->status);
  20012. // cli is destructed here with the keep-alive SSL session still open.
  20013. }
  20014. }
  20015. #endif
  20016. // WebSocket Tests
  20017. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20018. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20019. // defining the meaning of these bits has been negotiated.
  20020. auto make_frame = [](uint8_t first_byte) {
  20021. std::string frame;
  20022. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20023. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20024. frame += "Hello";
  20025. return frame;
  20026. };
  20027. // RSV1 set (0x40)
  20028. {
  20029. detail::BufferStream strm;
  20030. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20031. ws::Opcode opcode;
  20032. std::string payload;
  20033. bool fin;
  20034. EXPECT_EQ(
  20035. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20036. ws::impl::FrameRead::Fail);
  20037. }
  20038. // RSV2 set (0x20)
  20039. {
  20040. detail::BufferStream strm;
  20041. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20042. ws::Opcode opcode;
  20043. std::string payload;
  20044. bool fin;
  20045. EXPECT_EQ(
  20046. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20047. ws::impl::FrameRead::Fail);
  20048. }
  20049. // RSV3 set (0x10)
  20050. {
  20051. detail::BufferStream strm;
  20052. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20053. ws::Opcode opcode;
  20054. std::string payload;
  20055. bool fin;
  20056. EXPECT_EQ(
  20057. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20058. ws::impl::FrameRead::Fail);
  20059. }
  20060. // No RSV bits set - should succeed
  20061. {
  20062. detail::BufferStream strm;
  20063. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20064. ws::Opcode opcode;
  20065. std::string payload;
  20066. bool fin;
  20067. EXPECT_EQ(
  20068. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20069. ws::impl::FrameRead::Ok);
  20070. EXPECT_EQ(ws::Opcode::Text, opcode);
  20071. EXPECT_EQ("Hello", payload);
  20072. EXPECT_TRUE(fin);
  20073. }
  20074. }
  20075. TEST(WebSocketTest, ControlFrameValidation) {
  20076. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20077. // payload length <= 125.
  20078. // Ping with FIN=0 - must be rejected
  20079. {
  20080. detail::BufferStream strm;
  20081. std::string frame;
  20082. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20083. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20084. strm.write(frame.data(), frame.size());
  20085. ws::Opcode opcode;
  20086. std::string payload;
  20087. bool fin;
  20088. EXPECT_EQ(
  20089. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20090. ws::impl::FrameRead::Fail);
  20091. }
  20092. // Close with FIN=0 - must be rejected
  20093. {
  20094. detail::BufferStream strm;
  20095. std::string frame;
  20096. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20097. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20098. strm.write(frame.data(), frame.size());
  20099. ws::Opcode opcode;
  20100. std::string payload;
  20101. bool fin;
  20102. EXPECT_EQ(
  20103. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20104. ws::impl::FrameRead::Fail);
  20105. }
  20106. // Ping with payload_len=126 (extended length) - must be rejected
  20107. {
  20108. detail::BufferStream strm;
  20109. std::string frame;
  20110. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20111. frame += static_cast<char>(126); // payload_len=126 (>125)
  20112. frame += static_cast<char>(0x00); // extended length high byte
  20113. frame += static_cast<char>(126); // extended length low byte
  20114. frame += std::string(126, 'x');
  20115. strm.write(frame.data(), frame.size());
  20116. ws::Opcode opcode;
  20117. std::string payload;
  20118. bool fin;
  20119. EXPECT_EQ(
  20120. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20121. ws::impl::FrameRead::Fail);
  20122. }
  20123. // Ping with FIN=1 and payload_len=125 - should succeed
  20124. {
  20125. detail::BufferStream strm;
  20126. std::string frame;
  20127. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20128. frame += static_cast<char>(125); // payload_len=125
  20129. frame += std::string(125, 'x');
  20130. strm.write(frame.data(), frame.size());
  20131. ws::Opcode opcode;
  20132. std::string payload;
  20133. bool fin;
  20134. EXPECT_EQ(
  20135. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20136. ws::impl::FrameRead::Ok);
  20137. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20138. EXPECT_EQ(125u, payload.size());
  20139. EXPECT_TRUE(fin);
  20140. }
  20141. }
  20142. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20143. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20144. // length MUST be 0.
  20145. // MSB set - must be rejected
  20146. {
  20147. detail::BufferStream strm;
  20148. std::string frame;
  20149. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20150. frame += static_cast<char>(127); // 64-bit extended length
  20151. frame += static_cast<char>(0x80); // MSB set (invalid)
  20152. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20153. strm.write(frame.data(), frame.size());
  20154. ws::Opcode opcode;
  20155. std::string payload;
  20156. bool fin;
  20157. EXPECT_EQ(
  20158. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20159. ws::impl::FrameRead::Fail);
  20160. }
  20161. // MSB clear - should pass length parsing (will be rejected by max_len,
  20162. // but that's a different check; use a small length to verify)
  20163. {
  20164. detail::BufferStream strm;
  20165. std::string frame;
  20166. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20167. frame += static_cast<char>(127); // 64-bit extended length
  20168. frame += std::string(7, '\0'); // high bytes = 0
  20169. frame += static_cast<char>(0x03); // length = 3
  20170. frame += "abc";
  20171. strm.write(frame.data(), frame.size());
  20172. ws::Opcode opcode;
  20173. std::string payload;
  20174. bool fin;
  20175. EXPECT_EQ(
  20176. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20177. ws::impl::FrameRead::Ok);
  20178. EXPECT_EQ(ws::Opcode::Text, opcode);
  20179. EXPECT_EQ("abc", payload);
  20180. }
  20181. }
  20182. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20183. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20184. // Valid UTF-8
  20185. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20186. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20187. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20188. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20189. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20190. // Invalid UTF-8
  20191. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  20192. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  20193. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  20194. EXPECT_FALSE(
  20195. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  20196. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  20197. }
  20198. TEST(WebSocketTest, ConnectAndDisconnect) {
  20199. Server svr;
  20200. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20201. std::string msg;
  20202. while (ws.read(msg)) {}
  20203. });
  20204. auto port = svr.bind_to_any_port(HOST);
  20205. std::thread t([&]() { svr.listen_after_bind(); });
  20206. svr.wait_until_ready();
  20207. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20208. auto res = client.connect();
  20209. ASSERT_TRUE(res);
  20210. EXPECT_EQ(Error::Success, res.error());
  20211. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  20212. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  20213. EXPECT_TRUE(client.is_open());
  20214. client.close();
  20215. EXPECT_FALSE(client.is_open());
  20216. svr.stop();
  20217. t.join();
  20218. }
  20219. TEST(WebSocketTest, ValidURL) {
  20220. ws::WebSocketClient ws1("ws://localhost:8080/path");
  20221. EXPECT_TRUE(ws1.is_valid());
  20222. ws::WebSocketClient ws2("ws://example.com/path");
  20223. EXPECT_TRUE(ws2.is_valid());
  20224. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  20225. EXPECT_TRUE(ws3.is_valid());
  20226. #ifdef CPPHTTPLIB_SSL_ENABLED
  20227. ws::WebSocketClient wss1("wss://example.com/path");
  20228. EXPECT_TRUE(wss1.is_valid());
  20229. ws::WebSocketClient wss2("wss://example.com:443/path");
  20230. EXPECT_TRUE(wss2.is_valid());
  20231. #endif
  20232. }
  20233. TEST(WebSocketTest, InvalidURL) {
  20234. // No scheme
  20235. ws::WebSocketClient ws1("localhost:8080/path");
  20236. EXPECT_FALSE(ws1.is_valid());
  20237. // No path
  20238. ws::WebSocketClient ws2("ws://localhost:8080");
  20239. EXPECT_FALSE(ws2.is_valid());
  20240. // Empty string
  20241. ws::WebSocketClient ws3("");
  20242. EXPECT_FALSE(ws3.is_valid());
  20243. // Missing host
  20244. ws::WebSocketClient ws4("ws://:8080/path");
  20245. EXPECT_FALSE(ws4.is_valid());
  20246. // Port number overflow — should not crash
  20247. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  20248. EXPECT_FALSE(ws5.is_valid());
  20249. // Port out of range
  20250. ws::WebSocketClient ws6("ws://localhost:99999/path");
  20251. EXPECT_FALSE(ws6.is_valid());
  20252. }
  20253. TEST(WebSocketTest, UnsupportedScheme) {
  20254. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  20255. ws::WebSocketClient ws1("http://localhost:8080/path");
  20256. EXPECT_FALSE(ws1.is_valid());
  20257. ws::WebSocketClient ws2("https://localhost:8080/path");
  20258. EXPECT_FALSE(ws2.is_valid());
  20259. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  20260. EXPECT_FALSE(ws3.is_valid());
  20261. #else
  20262. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  20263. std::invalid_argument);
  20264. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  20265. std::invalid_argument);
  20266. #endif
  20267. }
  20268. TEST(WebSocketTest, ConnectWhenInvalid) {
  20269. ws::WebSocketClient ws("not a valid url");
  20270. EXPECT_FALSE(ws.is_valid());
  20271. auto res = ws.connect();
  20272. EXPECT_FALSE(res);
  20273. EXPECT_EQ(Error::Connection, res.error());
  20274. EXPECT_EQ(-1, res.status());
  20275. }
  20276. TEST(WebSocketTest, ConnectRefusedReportsError) {
  20277. // Grab a port that is free, then close it again so nothing listens there
  20278. Server svr;
  20279. auto port = svr.bind_to_any_port(HOST);
  20280. svr.stop();
  20281. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20282. auto res = client.connect();
  20283. ASSERT_FALSE(res);
  20284. EXPECT_EQ(Error::Connection, res.error());
  20285. EXPECT_EQ(-1, res.status());
  20286. }
  20287. TEST(WebSocketTest, DefaultPort) {
  20288. ws::WebSocketClient ws1("ws://example.com/path");
  20289. EXPECT_TRUE(ws1.is_valid());
  20290. // ws:// defaults to port 80 (verified by successful parse)
  20291. #ifdef CPPHTTPLIB_SSL_ENABLED
  20292. ws::WebSocketClient ws2("wss://example.com/path");
  20293. EXPECT_TRUE(ws2.is_valid());
  20294. // wss:// defaults to port 443 (verified by successful parse)
  20295. #endif
  20296. }
  20297. TEST(WebSocketTest, IPv6LiteralAddress) {
  20298. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  20299. EXPECT_TRUE(ws1.is_valid());
  20300. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  20301. EXPECT_TRUE(ws2.is_valid());
  20302. }
  20303. TEST(WebSocketTest, ComplexPath) {
  20304. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  20305. EXPECT_TRUE(ws1.is_valid());
  20306. ws::WebSocketClient ws2("ws://localhost:8080/");
  20307. EXPECT_TRUE(ws2.is_valid());
  20308. }
  20309. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  20310. Server svr;
  20311. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20312. std::string msg;
  20313. while (ws.read(msg)) {}
  20314. });
  20315. auto port = svr.bind_to_any_port(HOST);
  20316. std::thread t([&]() { svr.listen_after_bind(); });
  20317. svr.wait_until_ready();
  20318. auto another_host = "example.com";
  20319. auto wrong_ip = "192.0.2.1";
  20320. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20321. client.set_hostname_addr_map({{another_host, wrong_ip}});
  20322. ASSERT_TRUE(client.connect());
  20323. EXPECT_TRUE(client.is_open());
  20324. client.close();
  20325. svr.stop();
  20326. t.join();
  20327. }
  20328. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  20329. Server svr;
  20330. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20331. std::string msg;
  20332. while (ws.read(msg)) {}
  20333. });
  20334. auto port = svr.bind_to_any_port(HOST);
  20335. std::thread t([&]() { svr.listen_after_bind(); });
  20336. svr.wait_until_ready();
  20337. auto wrong_ip = "192.0.2.1";
  20338. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20339. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  20340. client.set_connection_timeout(1);
  20341. client.set_read_timeout(1);
  20342. client.set_write_timeout(1);
  20343. EXPECT_FALSE(client.connect());
  20344. EXPECT_FALSE(client.is_open());
  20345. svr.stop();
  20346. t.join();
  20347. }
  20348. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  20349. // A mapped value that is not an IP literal must be resolved. HOST resolves
  20350. // from the hosts file, so this test needs no external DNS. "target.invalid"
  20351. // (RFC 6761) is only a map key and the Host header value.
  20352. auto host = "target.invalid";
  20353. Server svr;
  20354. std::string received_host;
  20355. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20356. received_host = req.get_header_value("Host");
  20357. std::string msg;
  20358. while (ws.read(msg)) {}
  20359. });
  20360. auto port = svr.bind_to_any_port(HOST);
  20361. std::thread t([&]() { svr.listen_after_bind(); });
  20362. // ASSERT_* below returns from the test body, which would leave t joinable
  20363. // and make ~thread call std::terminate.
  20364. auto se = detail::scope_exit([&] {
  20365. svr.stop();
  20366. if (t.joinable()) { t.join(); }
  20367. });
  20368. svr.wait_until_ready();
  20369. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  20370. std::to_string(port) + "/ws");
  20371. client.set_hostname_addr_map({{host, HOST}});
  20372. ASSERT_TRUE(client.connect());
  20373. EXPECT_TRUE(client.is_open());
  20374. client.close();
  20375. svr.stop();
  20376. t.join();
  20377. // The mapping only redirects the connection; the identity stays host_.
  20378. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  20379. }
  20380. class WebSocketIntegrationTest : public ::testing::Test {
  20381. protected:
  20382. void SetUp() override {
  20383. server_ = httplib::detail::make_unique<Server>();
  20384. setup_server();
  20385. start_server();
  20386. }
  20387. void TearDown() override {
  20388. server_->stop();
  20389. if (server_thread_.joinable()) { server_thread_.join(); }
  20390. }
  20391. void setup_server() {
  20392. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20393. std::string msg;
  20394. ws::ReadResult ret;
  20395. while ((ret = ws.read(msg))) {
  20396. if (ret == ws::Binary) {
  20397. ws.send(msg.data(), msg.size());
  20398. } else {
  20399. ws.send(msg);
  20400. }
  20401. }
  20402. });
  20403. server_->WebSocket("/ws-echo-string",
  20404. [](const Request &, ws::WebSocket &ws) {
  20405. std::string msg;
  20406. while (ws.read(msg)) {
  20407. ws.send("echo: " + msg);
  20408. }
  20409. });
  20410. server_->WebSocket(
  20411. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  20412. // Echo back request metadata
  20413. ws.send("path:" + req.path);
  20414. ws.send("header:" + req.get_header_value("X-Test-Header"));
  20415. std::string msg;
  20416. while (ws.read(msg)) {}
  20417. });
  20418. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  20419. std::string msg;
  20420. ws.read(msg); // wait for a message
  20421. ws.close();
  20422. });
  20423. server_->WebSocket("/ws-close-status",
  20424. [](const Request &, ws::WebSocket &ws) {
  20425. std::string msg;
  20426. ws.read(msg); // wait for a message
  20427. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  20428. });
  20429. server_->WebSocket(
  20430. "/ws-subprotocol",
  20431. [](const Request &, ws::WebSocket &ws) {
  20432. std::string msg;
  20433. while (ws.read(msg)) {
  20434. ws.send(msg);
  20435. }
  20436. },
  20437. [](const std::vector<std::string> &protocols) -> std::string {
  20438. for (const auto &p : protocols) {
  20439. if (p == "graphql-ws") { return p; }
  20440. }
  20441. return "";
  20442. });
  20443. server_->WebSocket(
  20444. "/ws-subprotocol-unoffered",
  20445. [](const Request &, ws::WebSocket &ws) {
  20446. std::string msg;
  20447. while (ws.read(msg)) {
  20448. ws.send(msg);
  20449. }
  20450. },
  20451. [](const std::vector<std::string> &) -> std::string {
  20452. return "admin";
  20453. });
  20454. }
  20455. void start_server() {
  20456. port_ = server_->bind_to_any_port(HOST);
  20457. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20458. server_->wait_until_ready();
  20459. }
  20460. std::unique_ptr<Server> server_;
  20461. std::thread server_thread_;
  20462. int port_ = 0;
  20463. };
  20464. TEST_F(WebSocketIntegrationTest, TextEcho) {
  20465. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20466. "/ws-echo");
  20467. ASSERT_TRUE(client.connect());
  20468. ASSERT_TRUE(client.is_open());
  20469. ASSERT_TRUE(client.send("Hello WebSocket"));
  20470. std::string msg;
  20471. EXPECT_EQ(ws::Text, client.read(msg));
  20472. EXPECT_EQ("Hello WebSocket", msg);
  20473. client.close();
  20474. }
  20475. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  20476. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20477. "/ws-echo");
  20478. ASSERT_TRUE(client.connect());
  20479. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  20480. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  20481. std::string msg;
  20482. EXPECT_EQ(ws::Binary, client.read(msg));
  20483. EXPECT_EQ(binary_data, msg);
  20484. client.close();
  20485. }
  20486. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  20487. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20488. "/ws-echo");
  20489. ASSERT_TRUE(client.connect());
  20490. for (int i = 0; i < 10; i++) {
  20491. auto text = "message " + std::to_string(i);
  20492. ASSERT_TRUE(client.send(text));
  20493. std::string msg;
  20494. ASSERT_TRUE(client.read(msg));
  20495. EXPECT_EQ(text, msg);
  20496. }
  20497. client.close();
  20498. }
  20499. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  20500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20501. "/ws-close");
  20502. ASSERT_TRUE(client.connect());
  20503. // Send a message to trigger the server to close
  20504. ASSERT_TRUE(client.send("trigger close"));
  20505. // The server will close, so read should return false
  20506. std::string msg;
  20507. EXPECT_FALSE(client.read(msg));
  20508. EXPECT_FALSE(client.is_open());
  20509. }
  20510. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  20511. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20512. "/ws-echo");
  20513. ASSERT_TRUE(client.connect());
  20514. // 128KB message
  20515. std::string large_data(128 * 1024, 'X');
  20516. ASSERT_TRUE(client.send(large_data));
  20517. std::string msg;
  20518. ASSERT_TRUE(client.read(msg));
  20519. EXPECT_EQ(large_data, msg);
  20520. client.close();
  20521. }
  20522. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  20523. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20524. "/ws-echo");
  20525. ASSERT_TRUE(client.connect());
  20526. const int num_threads = 4;
  20527. std::vector<std::thread> threads;
  20528. std::atomic<int> send_count{0};
  20529. for (int t = 0; t < num_threads; t++) {
  20530. threads.emplace_back([&client, &send_count, t]() {
  20531. for (int i = 0; i < 5; i++) {
  20532. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  20533. if (client.send(text)) { send_count++; }
  20534. }
  20535. });
  20536. }
  20537. for (auto &th : threads) {
  20538. th.join();
  20539. }
  20540. int received = 0;
  20541. std::string msg;
  20542. while (received < send_count.load()) {
  20543. if (!client.read(msg)) { break; }
  20544. received++;
  20545. }
  20546. EXPECT_EQ(send_count.load(), received);
  20547. client.close();
  20548. }
  20549. TEST_F(WebSocketIntegrationTest, ReadString) {
  20550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20551. "/ws-echo-string");
  20552. ASSERT_TRUE(client.connect());
  20553. ASSERT_TRUE(client.send("hello"));
  20554. std::string msg;
  20555. ASSERT_TRUE(client.read(msg));
  20556. EXPECT_EQ("echo: hello", msg);
  20557. ASSERT_TRUE(client.send("world"));
  20558. ASSERT_TRUE(client.read(msg));
  20559. EXPECT_EQ("echo: world", msg);
  20560. client.close();
  20561. }
  20562. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  20563. Headers headers = {{"X-Test-Header", "test-value"}};
  20564. ws::WebSocketClient client(
  20565. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  20566. ASSERT_TRUE(client.connect());
  20567. std::string msg;
  20568. ASSERT_TRUE(client.read(msg));
  20569. EXPECT_EQ("path:/ws-request-info", msg);
  20570. ASSERT_TRUE(client.read(msg));
  20571. EXPECT_EQ("header:test-value", msg);
  20572. client.close();
  20573. }
  20574. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  20575. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20576. "/ws-echo");
  20577. client.set_read_timeout(1, 0); // 1 second
  20578. ASSERT_TRUE(client.connect());
  20579. // Don't send anything — server echo handler waits for a message, so read()
  20580. // should time out. The connection survives it: nothing was consumed.
  20581. std::string msg;
  20582. EXPECT_EQ(client.read(msg), ws::Timeout);
  20583. EXPECT_TRUE(client.is_open());
  20584. // And it is still usable afterwards.
  20585. EXPECT_TRUE(client.send("after timeout"));
  20586. EXPECT_EQ(client.read(msg), ws::Text);
  20587. EXPECT_EQ(msg, "after timeout");
  20588. }
  20589. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  20590. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20591. "/ws-echo");
  20592. client.set_read_timeout(1, 0);
  20593. ASSERT_TRUE(client.connect());
  20594. ASSERT_TRUE(client.send("first"));
  20595. std::string msg;
  20596. ASSERT_EQ(client.read(msg), ws::Text);
  20597. ASSERT_EQ(msg, "first");
  20598. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  20599. // not be used with a read timeout: it would reprocess the previous message.
  20600. EXPECT_EQ(client.read(msg), ws::Timeout);
  20601. EXPECT_EQ(msg, "first");
  20602. }
  20603. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  20604. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20605. "/ws-echo");
  20606. ASSERT_TRUE(client.connect());
  20607. // Setting it once the connection is open reaches the live stream, not just
  20608. // the seed for the next connect().
  20609. client.set_read_timeout(1, 0);
  20610. std::string msg;
  20611. EXPECT_EQ(client.read(msg), ws::Timeout);
  20612. EXPECT_TRUE(client.is_open());
  20613. }
  20614. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  20615. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20616. "/ws-echo");
  20617. client.set_read_timeout(5, 0);
  20618. ASSERT_TRUE(client.connect());
  20619. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20620. // The server should reject it and close the connection.
  20621. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  20622. client.send(oversized);
  20623. // The server's read() should have failed due to payload limit,
  20624. // so our read() should return false (connection closed).
  20625. std::string msg;
  20626. EXPECT_FALSE(client.read(msg));
  20627. }
  20628. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  20629. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20630. "/ws-echo");
  20631. client.set_read_timeout(10, 0);
  20632. ASSERT_TRUE(client.connect());
  20633. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  20634. // This should succeed.
  20635. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  20636. ASSERT_TRUE(client.send(at_limit));
  20637. std::string msg;
  20638. ASSERT_TRUE(client.read(msg));
  20639. EXPECT_EQ(at_limit.size(), msg.size());
  20640. client.close();
  20641. }
  20642. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  20643. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20644. "/nonexistent");
  20645. auto res = client.connect();
  20646. EXPECT_FALSE(res);
  20647. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20648. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  20649. EXPECT_FALSE(client.is_open());
  20650. }
  20651. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  20652. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20653. "/ws-echo");
  20654. ASSERT_TRUE(client.connect());
  20655. ASSERT_TRUE(client.send(""));
  20656. std::string msg;
  20657. EXPECT_EQ(ws::Text, client.read(msg));
  20658. EXPECT_EQ("", msg);
  20659. client.close();
  20660. }
  20661. TEST_F(WebSocketIntegrationTest, Reconnect) {
  20662. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20663. "/ws-echo");
  20664. // First connection
  20665. ASSERT_TRUE(client.connect());
  20666. ASSERT_TRUE(client.send("first"));
  20667. std::string msg;
  20668. ASSERT_TRUE(client.read(msg));
  20669. EXPECT_EQ("first", msg);
  20670. client.close();
  20671. EXPECT_FALSE(client.is_open());
  20672. // Reconnect using the same client object
  20673. ASSERT_TRUE(client.connect());
  20674. ASSERT_TRUE(client.is_open());
  20675. ASSERT_TRUE(client.send("second"));
  20676. ASSERT_TRUE(client.read(msg));
  20677. EXPECT_EQ("second", msg);
  20678. client.close();
  20679. }
  20680. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  20681. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20682. "/ws-close-status");
  20683. ASSERT_TRUE(client.connect());
  20684. // Trigger the server to close with GoingAway status
  20685. ASSERT_TRUE(client.send("trigger"));
  20686. // read() should return false after receiving the close frame
  20687. std::string msg;
  20688. EXPECT_FALSE(client.read(msg));
  20689. EXPECT_FALSE(client.is_open());
  20690. }
  20691. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  20692. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20693. "/ws-echo");
  20694. ASSERT_TRUE(client.connect());
  20695. client.close(ws::CloseStatus::GoingAway, "client leaving");
  20696. EXPECT_FALSE(client.is_open());
  20697. }
  20698. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  20699. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  20700. ws::WebSocketClient client(
  20701. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20702. ASSERT_TRUE(client.connect());
  20703. // Server should have selected graphql-ws
  20704. EXPECT_EQ("graphql-ws", client.subprotocol());
  20705. client.close();
  20706. }
  20707. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  20708. Headers headers;
  20709. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  20710. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  20711. ws::WebSocketClient client(
  20712. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20713. ASSERT_TRUE(client.connect());
  20714. // The offer on the second field line counts too, so graphql-ws is selected
  20715. EXPECT_EQ("graphql-ws", client.subprotocol());
  20716. client.close();
  20717. }
  20718. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  20719. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  20720. ws::WebSocketClient client(
  20721. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  20722. ASSERT_TRUE(client.connect());
  20723. // Server should not have selected any subprotocol
  20724. EXPECT_TRUE(client.subprotocol().empty());
  20725. client.close();
  20726. }
  20727. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  20728. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  20729. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20730. "/ws-subprotocol-unoffered",
  20731. headers);
  20732. ASSERT_TRUE(client.connect());
  20733. EXPECT_TRUE(client.subprotocol().empty());
  20734. client.close();
  20735. }
  20736. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  20737. // Connect without requesting any subprotocol
  20738. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20739. "/ws-subprotocol");
  20740. ASSERT_TRUE(client.connect());
  20741. EXPECT_TRUE(client.subprotocol().empty());
  20742. client.close();
  20743. }
  20744. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  20745. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20746. "/ws-echo");
  20747. client.set_tcp_nodelay(true);
  20748. client.set_connection_timeout(3, 0);
  20749. bool socket_options_called = false;
  20750. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  20751. ASSERT_TRUE(client.connect());
  20752. ASSERT_TRUE(client.is_open());
  20753. EXPECT_TRUE(socket_options_called);
  20754. ASSERT_TRUE(client.send("hello"));
  20755. std::string msg;
  20756. auto result = client.read(msg);
  20757. EXPECT_EQ(result, ws::ReadResult::Text);
  20758. EXPECT_EQ(msg, "hello");
  20759. client.close();
  20760. }
  20761. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20762. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20763. "/ws-echo");
  20764. client.set_connection_timeout(std::chrono::seconds(3));
  20765. client.set_write_timeout(std::chrono::seconds(3));
  20766. // A sub-second remainder exercises the seconds/microseconds split.
  20767. client.set_read_timeout(std::chrono::milliseconds(1500));
  20768. ASSERT_TRUE(client.connect());
  20769. auto start = std::chrono::steady_clock::now();
  20770. std::string msg;
  20771. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20772. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20773. std::chrono::steady_clock::now() - start)
  20774. .count();
  20775. // Above 1s so that dropping the microseconds half of the split fails here.
  20776. // Ignoring the setter altogether would not reach this line at all: a client
  20777. // waits forever by default.
  20778. EXPECT_GE(elapsed, 1400);
  20779. EXPECT_LT(elapsed, 30000);
  20780. }
  20781. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20782. Server svr;
  20783. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20784. if (!req.has_header("Authorization")) {
  20785. res.status = StatusCode::Unauthorized_401;
  20786. res.set_content("Unauthorized", "text/plain");
  20787. return Server::HandlerResponse::Handled;
  20788. }
  20789. return Server::HandlerResponse::Unhandled;
  20790. });
  20791. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20792. std::string msg;
  20793. while (ws.read(msg)) {
  20794. ws.send(msg);
  20795. }
  20796. });
  20797. auto port = svr.bind_to_any_port("localhost");
  20798. std::thread t([&]() { svr.listen_after_bind(); });
  20799. svr.wait_until_ready();
  20800. // Without Authorization header - should be rejected before upgrade
  20801. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20802. EXPECT_FALSE(client1.connect());
  20803. // The rejection is framed like any other HTTP response
  20804. {
  20805. Client cli("localhost", port);
  20806. Headers headers = {{"Upgrade", "websocket"},
  20807. {"Connection", "Upgrade"},
  20808. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20809. {"Sec-WebSocket-Version", "13"}};
  20810. auto res = cli.Get("/ws", headers);
  20811. ASSERT_TRUE(res);
  20812. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20813. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20814. EXPECT_EQ("Unauthorized", res->body);
  20815. }
  20816. // With Authorization header - should succeed
  20817. Headers headers = {{"Authorization", "Bearer token123"}};
  20818. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20819. headers);
  20820. ASSERT_TRUE(client2.connect());
  20821. ASSERT_TRUE(client2.send("hello"));
  20822. std::string msg;
  20823. ASSERT_TRUE(client2.read(msg));
  20824. EXPECT_EQ("hello", msg);
  20825. client2.close();
  20826. svr.stop();
  20827. t.join();
  20828. }
  20829. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20830. Server svr;
  20831. std::atomic<int> pre_request_calls{0};
  20832. std::atomic<bool> route_matched{false};
  20833. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20834. pre_request_calls++;
  20835. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20836. if (req.get_header_value("Authorization") != "Bearer token123") {
  20837. res.status = StatusCode::Unauthorized_401;
  20838. res.set_content("Unauthorized", "text/plain");
  20839. return Server::HandlerResponse::Handled;
  20840. }
  20841. return Server::HandlerResponse::Unhandled;
  20842. });
  20843. std::atomic<bool> handler_called{false};
  20844. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20845. handler_called = true;
  20846. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20847. });
  20848. auto port = svr.bind_to_any_port("localhost");
  20849. std::thread t([&]() { svr.listen_after_bind(); });
  20850. svr.wait_until_ready();
  20851. // Without Authorization header - should be rejected before upgrade
  20852. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20853. "/ws/1");
  20854. EXPECT_FALSE(client1.connect());
  20855. EXPECT_FALSE(handler_called);
  20856. EXPECT_EQ(1, pre_request_calls);
  20857. EXPECT_TRUE(route_matched);
  20858. // The rejection is an ordinary HTTP response, not a protocol switch
  20859. {
  20860. Client cli("localhost", port);
  20861. Headers headers = {{"Upgrade", "websocket"},
  20862. {"Connection", "Upgrade"},
  20863. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20864. {"Sec-WebSocket-Version", "13"}};
  20865. auto res = cli.Get("/ws/1", headers);
  20866. ASSERT_TRUE(res);
  20867. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20868. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20869. EXPECT_EQ("Unauthorized", res->body);
  20870. }
  20871. EXPECT_FALSE(handler_called);
  20872. // With Authorization header - should succeed
  20873. Headers headers = {{"Authorization", "Bearer token123"}};
  20874. ws::WebSocketClient client2(
  20875. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20876. ASSERT_TRUE(client2.connect());
  20877. std::string msg;
  20878. ASSERT_TRUE(client2.read(msg));
  20879. EXPECT_EQ("/ws/:id 2", msg);
  20880. EXPECT_TRUE(handler_called);
  20881. client2.close();
  20882. svr.stop();
  20883. t.join();
  20884. }
  20885. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20886. Server svr;
  20887. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20888. // A read timeout is how a handler gets control back. Without it, a handler
  20889. // parked in read() can never write on the connection it is reading.
  20890. ws.set_read_timeout(std::chrono::milliseconds(100));
  20891. std::string msg;
  20892. while (ws.is_open()) {
  20893. auto r = ws.read(msg);
  20894. if (r == httplib::ws::Timeout) {
  20895. ws.send("tick");
  20896. continue;
  20897. }
  20898. if (r == httplib::ws::Fail) { break; }
  20899. ws.send(msg);
  20900. }
  20901. });
  20902. auto port = svr.bind_to_any_port("localhost");
  20903. std::thread t([&]() { svr.listen_after_bind(); });
  20904. svr.wait_until_ready();
  20905. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20906. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20907. ASSERT_TRUE(client.connect());
  20908. // The client sends nothing, so anything it receives came out of the
  20909. // handler's timeout path.
  20910. std::string msg;
  20911. ASSERT_EQ(client.read(msg), ws::Text);
  20912. EXPECT_EQ("tick", msg);
  20913. client.close();
  20914. svr.stop();
  20915. t.join();
  20916. }
  20917. // Stream::read may return fewer bytes than asked for. This is that contract at
  20918. // its worst -- one byte per call -- which is what a frame header straddling a
  20919. // read buffer's boundary looks like to the frame parser.
  20920. class WsByteAtATimeStream : public Stream {
  20921. public:
  20922. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20923. bool is_readable() const override { return true; }
  20924. bool wait_readable() const override { return true; }
  20925. bool wait_writable() const override { return true; }
  20926. ssize_t read(char *ptr, size_t size) override {
  20927. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20928. *ptr = data_[pos_++];
  20929. return 1;
  20930. }
  20931. ssize_t write(const char *, size_t size) override {
  20932. return static_cast<ssize_t>(size);
  20933. }
  20934. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20935. ip = "127.0.0.1";
  20936. port = 0;
  20937. }
  20938. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20939. ip = "127.0.0.1";
  20940. port = 0;
  20941. }
  20942. socket_t socket() const override { return INVALID_SOCKET; }
  20943. time_t duration() const override { return 0; }
  20944. private:
  20945. std::string data_;
  20946. size_t pos_ = 0;
  20947. };
  20948. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20949. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20950. // length and the mask key are all multi-byte fields here. Each used to be
  20951. // read with a single read() call, which fails as soon as one is split.
  20952. std::string body(200, 'x');
  20953. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20954. std::string frame;
  20955. frame += static_cast<char>(0x81); // FIN + Text
  20956. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20957. frame += static_cast<char>(body.size() >> 8);
  20958. frame += static_cast<char>(body.size() & 0xff);
  20959. for (size_t i = 0; i < 4; i++) {
  20960. frame += static_cast<char>(mask[i]);
  20961. }
  20962. for (size_t i = 0; i < body.size(); i++) {
  20963. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20964. }
  20965. WsByteAtATimeStream strm(frame);
  20966. ws::Opcode opcode;
  20967. std::string payload;
  20968. bool fin = false;
  20969. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20970. /*expect_masked=*/true, 1024),
  20971. ws::impl::FrameRead::Ok);
  20972. EXPECT_TRUE(fin);
  20973. EXPECT_EQ(opcode, ws::Opcode::Text);
  20974. EXPECT_EQ(payload, body);
  20975. }
  20976. TEST(WebSocketTest, QueryStringInHandshake) {
  20977. Server svr;
  20978. std::mutex mtx;
  20979. std::string received_target;
  20980. std::string received_token;
  20981. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20982. {
  20983. std::lock_guard<std::mutex> lock(mtx);
  20984. received_target = req.target;
  20985. if (req.has_param("token")) {
  20986. received_token = req.get_param_value("token");
  20987. }
  20988. }
  20989. std::string msg;
  20990. while (ws.read(msg)) {
  20991. ws.send(msg);
  20992. }
  20993. });
  20994. auto port = svr.bind_to_any_port("localhost");
  20995. std::thread t([&]() { svr.listen_after_bind(); });
  20996. svr.wait_until_ready();
  20997. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20998. "/ws?token=ABC&session=123");
  20999. ASSERT_TRUE(client.connect());
  21000. // Round-trip ensures the handler has run and captured the request.
  21001. ASSERT_TRUE(client.send("hello"));
  21002. std::string msg;
  21003. ASSERT_TRUE(client.read(msg));
  21004. EXPECT_EQ("hello", msg);
  21005. client.close();
  21006. {
  21007. std::lock_guard<std::mutex> lock(mtx);
  21008. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21009. EXPECT_EQ("ABC", received_token);
  21010. }
  21011. svr.stop();
  21012. t.join();
  21013. }
  21014. // Run a handshake against a throwaway server and hand the request the server
  21015. // received back to the caller, so tests can assert on the headers the client
  21016. // actually put on the wire.
  21017. static void capture_websocket_handshake_request(
  21018. const Headers &client_headers,
  21019. std::function<void(const Request &, int port)> verify) {
  21020. Server svr;
  21021. std::mutex mtx;
  21022. Request received;
  21023. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21024. {
  21025. std::lock_guard<std::mutex> lock(mtx);
  21026. received = req;
  21027. }
  21028. std::string msg;
  21029. while (ws.read(msg)) {
  21030. ws.send(msg);
  21031. }
  21032. });
  21033. auto port = svr.bind_to_any_port("localhost");
  21034. std::thread t([&]() { svr.listen_after_bind(); });
  21035. auto se = detail::scope_exit([&] {
  21036. svr.stop();
  21037. t.join();
  21038. });
  21039. svr.wait_until_ready();
  21040. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21041. client_headers);
  21042. ASSERT_TRUE(client.connect());
  21043. ASSERT_TRUE(client.send("hello"));
  21044. std::string msg;
  21045. ASSERT_TRUE(client.read(msg));
  21046. client.close();
  21047. {
  21048. std::lock_guard<std::mutex> lock(mtx);
  21049. verify(received, port);
  21050. }
  21051. }
  21052. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21053. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21054. // Non-default port must be present in the Host header. Default ports
  21055. // (80/443) are omitted; that logic is covered by
  21056. // MakeHostAndPortStringTest.
  21057. EXPECT_EQ("localhost:" + std::to_string(port),
  21058. req.get_header_value("Host"));
  21059. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21060. req.get_header_value("User-Agent"));
  21061. EXPECT_FALSE(req.has_header("Accept"));
  21062. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21063. EXPECT_FALSE(req.has_header("Content-Length"));
  21064. });
  21065. }
  21066. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21067. capture_websocket_handshake_request(
  21068. {{"Host", "example.com"},
  21069. {"User-Agent", "custom-agent"},
  21070. {"X-Custom", "value"}},
  21071. [](const Request &req, int) {
  21072. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21073. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21074. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21075. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21076. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21077. });
  21078. }
  21079. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21080. capture_websocket_handshake_request(
  21081. {{"Upgrade", "bogus"},
  21082. {"Connection", "close"},
  21083. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21084. {"Sec-WebSocket-Version", "8"}},
  21085. [](const Request &req, int) {
  21086. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21087. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21088. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21089. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21090. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21091. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21092. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21093. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21094. req.get_header_value("Sec-WebSocket-Key"));
  21095. });
  21096. }
  21097. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21098. // A header the client refuses to send must abort the handshake before any
  21099. // part of it reaches the wire; a lone request line would otherwise sit in
  21100. // the peer's buffer as a truncated request.
  21101. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21102. ASSERT_NE(INVALID_SOCKET, srv);
  21103. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21104. sockaddr_in addr{};
  21105. addr.sin_family = AF_INET;
  21106. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21108. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21109. ASSERT_EQ(0, ::listen(srv, 1));
  21110. sockaddr_in bound{};
  21111. socklen_t bound_len = sizeof(bound);
  21112. ASSERT_EQ(
  21113. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21114. auto port = ntohs(bound.sin_port);
  21115. ssize_t received = -1;
  21116. std::thread t([&] {
  21117. // Bound every blocking call so a regression fails the test with a bad
  21118. // value instead of hanging the suite.
  21119. fd_set rfds;
  21120. FD_ZERO(&rfds);
  21121. FD_SET(srv, &rfds);
  21122. timeval tv{5, 0};
  21123. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21124. 0) {
  21125. return;
  21126. }
  21127. sockaddr_in cli_addr{};
  21128. socklen_t cli_len = sizeof(cli_addr);
  21129. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21130. if (cli == INVALID_SOCKET) { return; }
  21131. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21132. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21133. char buf[4096];
  21134. received = ::recv(cli, buf, sizeof(buf), 0);
  21135. });
  21136. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21137. // connect() has already shut the socket down by the time it returns false,
  21138. // so the peer sees EOF without waiting for the client to be destroyed.
  21139. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21140. {{"X-Bad", "a\r\nInjected: 1"}});
  21141. EXPECT_FALSE(client.connect());
  21142. t.join();
  21143. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21144. EXPECT_EQ(0, received);
  21145. }
  21146. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21147. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  21148. // contains "upgrade" as a substring is a different token and must not
  21149. // start a WebSocket handshake.
  21150. auto make_request = [](const std::vector<std::string> &connection_values) {
  21151. Request req;
  21152. req.method = "GET";
  21153. req.headers.emplace("Upgrade", "websocket");
  21154. for (const auto &value : connection_values) {
  21155. req.headers.emplace("Connection", value);
  21156. }
  21157. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21158. req.headers.emplace("Sec-WebSocket-Version", "13");
  21159. return req;
  21160. };
  21161. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  21162. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  21163. EXPECT_TRUE(
  21164. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  21165. EXPECT_TRUE(
  21166. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  21167. EXPECT_TRUE(
  21168. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  21169. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  21170. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  21171. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  21172. EXPECT_FALSE(
  21173. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  21174. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  21175. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21176. }
  21177. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  21178. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  21179. // asks recipients to match each protocol-name case-insensitively, and RFC
  21180. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  21181. // client naming websocket alongside another protocol, or on a second field
  21182. // line, is offering websocket; a value that merely contains "websocket" as a
  21183. // substring is a different protocol name and is not.
  21184. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  21185. Request req;
  21186. req.method = "GET";
  21187. for (const auto &value : upgrade_values) {
  21188. req.headers.emplace("Upgrade", value);
  21189. }
  21190. req.headers.emplace("Connection", "Upgrade");
  21191. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  21192. req.headers.emplace("Sec-WebSocket-Version", "13");
  21193. return req;
  21194. };
  21195. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  21196. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  21197. EXPECT_TRUE(
  21198. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  21199. EXPECT_TRUE(
  21200. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  21201. EXPECT_TRUE(
  21202. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  21203. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  21204. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  21205. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  21206. EXPECT_FALSE(
  21207. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  21208. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  21209. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  21210. }
  21211. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  21212. Server svr;
  21213. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  21214. auto port = svr.bind_to_any_port("localhost");
  21215. std::thread t([&]() { svr.listen_after_bind(); });
  21216. auto se = detail::scope_exit([&] {
  21217. svr.stop();
  21218. t.join();
  21219. });
  21220. svr.wait_until_ready();
  21221. Headers headers = {{"Upgrade", "websocket"},
  21222. {"Connection", "notupgrade"},
  21223. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21224. {"Sec-WebSocket-Version", "13"}};
  21225. Client cli("localhost", port);
  21226. auto res = cli.Get("/ws", headers);
  21227. // The route exists only as a WebSocket route, so a request that fails the
  21228. // handshake check falls through to ordinary routing.
  21229. ASSERT_TRUE(res);
  21230. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  21231. }
  21232. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  21233. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  21234. // Connection value is the only thing left for the client to reject.
  21235. Server svr;
  21236. svr.Get("/ws", [](const Request &req, Response &res) {
  21237. res.status = StatusCode::SwitchingProtocol_101;
  21238. res.set_header("Upgrade", "websocket");
  21239. res.set_header("Connection", "notupgrade");
  21240. res.set_header("Sec-WebSocket-Accept",
  21241. detail::websocket_accept_key(
  21242. req.get_header_value("Sec-WebSocket-Key")));
  21243. });
  21244. auto port = svr.bind_to_any_port("localhost");
  21245. std::thread t([&]() { svr.listen_after_bind(); });
  21246. auto se = detail::scope_exit([&] {
  21247. svr.stop();
  21248. t.join();
  21249. });
  21250. svr.wait_until_ready();
  21251. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21252. auto res = client.connect();
  21253. EXPECT_FALSE(res);
  21254. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21255. EXPECT_FALSE(client.is_open());
  21256. }
  21257. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  21258. Server svr;
  21259. svr.Get("/ws", [](const Request &req, Response &res) {
  21260. res.status = StatusCode::SwitchingProtocol_101;
  21261. res.set_header("Upgrade", "websocket");
  21262. res.set_header("Connection", "Upgrade");
  21263. res.set_header("Sec-WebSocket-Accept",
  21264. detail::websocket_accept_key(
  21265. req.get_header_value("Sec-WebSocket-Key")));
  21266. res.set_header("Sec-WebSocket-Protocol", "admin");
  21267. });
  21268. auto port = svr.bind_to_any_port("localhost");
  21269. std::thread t([&]() { svr.listen_after_bind(); });
  21270. auto se = detail::scope_exit([&] {
  21271. svr.stop();
  21272. t.join();
  21273. });
  21274. svr.wait_until_ready();
  21275. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  21276. // Server selects a subprotocol the client never offered
  21277. {
  21278. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21279. ws::WebSocketClient client(url, headers);
  21280. auto res = client.connect();
  21281. EXPECT_FALSE(res);
  21282. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21283. EXPECT_FALSE(client.is_open());
  21284. EXPECT_TRUE(client.subprotocol().empty());
  21285. }
  21286. // Client offered none but the server named one anyway
  21287. {
  21288. ws::WebSocketClient client(url);
  21289. auto res = client.connect();
  21290. EXPECT_FALSE(res);
  21291. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21292. EXPECT_FALSE(client.is_open());
  21293. EXPECT_TRUE(client.subprotocol().empty());
  21294. }
  21295. }
  21296. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  21297. // The socket path doubles as the URL host, so it must not contain '/'.
  21298. const char *shard = getenv("GTEST_SHARD_INDEX");
  21299. const std::string sock_path =
  21300. shard ? std::string("httplib-ws-") + shard + ".sock"
  21301. : std::string("httplib-ws.sock");
  21302. std::remove(sock_path.c_str());
  21303. Server svr;
  21304. std::mutex mtx;
  21305. std::string received_host;
  21306. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21307. {
  21308. std::lock_guard<std::mutex> lock(mtx);
  21309. received_host = req.get_header_value("Host");
  21310. }
  21311. std::string msg;
  21312. while (ws.read(msg)) {
  21313. ws.send(msg);
  21314. }
  21315. });
  21316. svr.set_address_family(AF_UNIX);
  21317. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  21318. auto se = detail::scope_exit([&] {
  21319. svr.stop();
  21320. t.join();
  21321. std::remove(sock_path.c_str());
  21322. });
  21323. svr.wait_until_ready();
  21324. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  21325. client.set_address_family(AF_UNIX);
  21326. ASSERT_TRUE(client.connect());
  21327. ASSERT_TRUE(client.send("hello"));
  21328. std::string msg;
  21329. ASSERT_TRUE(client.read(msg));
  21330. client.close();
  21331. {
  21332. std::lock_guard<std::mutex> lock(mtx);
  21333. // There is no host:port for a Unix socket, so the same "localhost"
  21334. // placeholder the HTTP client uses is expected.
  21335. EXPECT_EQ("localhost", received_host);
  21336. }
  21337. }
  21338. // Two threads must never parse WebSocket frames from the same stream.
  21339. // close() used to read the peer's Close reply with its own frame read, so it
  21340. // raced a reader thread that was in the middle of a payload: the payload loop
  21341. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  21342. // so bytes taken by close() were replaced with bytes from further along the
  21343. // stream. The message kept its length and silently changed content.
  21344. //
  21345. // The raw peer below sends a frame header plus part of the payload, waits for
  21346. // the handler to call close(), and only then sends the rest. Whichever thread
  21347. // would win the race for those bytes, the message must arrive intact, because
  21348. // close() must not touch the stream while read() owns it.
  21349. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  21350. #ifndef _WIN32
  21351. signal(SIGPIPE, SIG_IGN);
  21352. #endif
  21353. const size_t payload_len = 120; // fits the 7-bit length field
  21354. const size_t prefix_len = 8;
  21355. const int attempts = 8;
  21356. std::string expected(payload_len, '\0');
  21357. for (size_t i = 0; i < payload_len; i++) {
  21358. expected[i] = static_cast<char>('a' + i % 26);
  21359. }
  21360. std::atomic<bool> peer_stalled{false};
  21361. std::atomic<bool> handler_done{false};
  21362. std::mutex received_mutex;
  21363. std::vector<std::string> received;
  21364. // Bound every wait, so a regression fails the test instead of hanging the
  21365. // suite.
  21366. auto wait_for = [](const std::atomic<bool> &flag) {
  21367. for (int i = 0; i < 500 && !flag; i++) {
  21368. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21369. }
  21370. };
  21371. Server svr;
  21372. svr.set_websocket_ping_interval(0);
  21373. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  21374. std::thread reader([&]() {
  21375. std::string msg;
  21376. while (ws.read(msg)) {
  21377. std::lock_guard<std::mutex> guard(received_mutex);
  21378. received.push_back(msg);
  21379. }
  21380. });
  21381. // Wait until the peer stalls mid-payload, so the reader thread is parked
  21382. // inside read_websocket_frame() when close() runs.
  21383. wait_for(peer_stalled);
  21384. ws.close();
  21385. reader.join();
  21386. handler_done = true;
  21387. });
  21388. auto port = svr.bind_to_any_port("127.0.0.1");
  21389. std::thread t([&]() { svr.listen_after_bind(); });
  21390. auto se = detail::scope_exit([&] {
  21391. svr.stop();
  21392. t.join();
  21393. });
  21394. svr.wait_until_ready();
  21395. auto send_bytes = [](socket_t s, const std::string &data) {
  21396. #ifdef _WIN32
  21397. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  21398. #else
  21399. auto n = ::send(s, data.data(), data.size(), 0);
  21400. #endif
  21401. return n == static_cast<decltype(n)>(data.size());
  21402. };
  21403. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  21404. // Every length used here fits the 7-bit length field.
  21405. auto masked_header = [](uint8_t first_byte, size_t len) {
  21406. std::string h;
  21407. h += static_cast<char>(first_byte);
  21408. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  21409. h.append(4, '\0'); // mask key
  21410. return h;
  21411. };
  21412. for (int attempt = 0; attempt < attempts; attempt++) {
  21413. peer_stalled = false;
  21414. handler_done = false;
  21415. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  21416. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  21417. auto se_sock = detail::scope_exit([&] {
  21418. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  21419. });
  21420. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21421. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21422. sockaddr_in addr{};
  21423. addr.sin_family = AF_INET;
  21424. addr.sin_port = htons(static_cast<uint16_t>(port));
  21425. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21426. ASSERT_EQ(
  21427. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  21428. << "attempt " << attempt;
  21429. ASSERT_TRUE(send_bytes(sock,
  21430. "GET /ws HTTP/1.1\r\n"
  21431. "Host: 127.0.0.1\r\n"
  21432. "Upgrade: websocket\r\n"
  21433. "Connection: Upgrade\r\n"
  21434. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  21435. "Sec-WebSocket-Version: 13\r\n"
  21436. "\r\n"))
  21437. << "attempt " << attempt;
  21438. std::string response;
  21439. while (response.find("\r\n\r\n") == std::string::npos) {
  21440. char buf[512];
  21441. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  21442. if (n <= 0) { break; }
  21443. response.append(buf, static_cast<size_t>(n));
  21444. }
  21445. ASSERT_NE(std::string::npos, response.find(" 101 "))
  21446. << "attempt " << attempt;
  21447. // Send the header of a Binary message but only the first prefix_len bytes
  21448. // of its payload, leaving the reader thread stalled inside the payload.
  21449. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  21450. expected.substr(0, prefix_len)))
  21451. << "attempt " << attempt;
  21452. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21453. peer_stalled = true;
  21454. // Let close() send its Close frame and park in its own read before the
  21455. // rest of the payload arrives, so both threads are waiting for it.
  21456. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21457. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  21458. close_frame += static_cast<char>(0x03); // status 1000
  21459. close_frame += static_cast<char>(0xE8);
  21460. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  21461. << "attempt " << attempt;
  21462. // Closing the peer releases the reader thread even on the buggy path,
  21463. // where it waits for bytes another thread already consumed.
  21464. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  21465. detail::close_socket(sock);
  21466. sock = INVALID_SOCKET;
  21467. wait_for(handler_done);
  21468. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  21469. }
  21470. std::lock_guard<std::mutex> guard(received_mutex);
  21471. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  21472. << "a message in flight when close() ran was dropped";
  21473. for (size_t i = 0; i < received.size(); i++) {
  21474. EXPECT_EQ(expected, received[i]) << "message " << i;
  21475. }
  21476. }
  21477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  21478. class WebSocketSSLIntegrationTest : public ::testing::Test {
  21479. protected:
  21480. void SetUp() override {
  21481. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  21482. SERVER_PRIVATE_KEY_FILE);
  21483. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21484. std::string msg;
  21485. ws::ReadResult ret;
  21486. while ((ret = ws.read(msg))) {
  21487. if (ret == ws::Binary) {
  21488. ws.send(msg.data(), msg.size());
  21489. } else {
  21490. ws.send(msg);
  21491. }
  21492. }
  21493. });
  21494. port_ = server_->bind_to_any_port(HOST);
  21495. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21496. server_->wait_until_ready();
  21497. }
  21498. void TearDown() override {
  21499. server_->stop();
  21500. if (server_thread_.joinable()) { server_thread_.join(); }
  21501. }
  21502. std::unique_ptr<SSLServer> server_;
  21503. std::thread server_thread_;
  21504. int port_ = 0;
  21505. };
  21506. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  21507. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21508. "/ws-echo");
  21509. client.enable_server_certificate_verification(false);
  21510. ASSERT_TRUE(client.connect());
  21511. ASSERT_TRUE(client.is_open());
  21512. ASSERT_TRUE(client.send("Hello WSS"));
  21513. std::string msg;
  21514. EXPECT_EQ(ws::Text, client.read(msg));
  21515. EXPECT_EQ("Hello WSS", msg);
  21516. client.close();
  21517. }
  21518. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  21519. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  21520. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  21521. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  21522. // client (without calling close() first) is the only path that runs
  21523. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  21524. // bug exactly.
  21525. //
  21526. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  21527. // when linked against an instrumented libssl; run under Valgrind to catch it
  21528. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  21529. // suite (the freed session otherwise stalls on the close handshake) — this test
  21530. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  21531. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  21532. {
  21533. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21534. "/ws-echo");
  21535. client.enable_server_certificate_verification(false);
  21536. client.set_read_timeout(2, 0);
  21537. client.set_write_timeout(2, 0);
  21538. ASSERT_TRUE(client.connect());
  21539. ASSERT_TRUE(client.is_open());
  21540. ASSERT_TRUE(client.send("still open"));
  21541. // Intentionally do NOT call client.close(): leaving scope runs
  21542. // shutdown_and_close() with the WebSocket still open, which must send the
  21543. // close frame while the TLS session is still alive.
  21544. }
  21545. }
  21546. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  21547. // shutdown_and_close() at the start of connect(), reproducing the same
  21548. // use-after-free within the test body rather than at scope exit. The second
  21549. // connect must succeed and echo, proving the close handshake ran over a live
  21550. // session. See the note above about memory-tool requirements.
  21551. TEST_F(WebSocketSSLIntegrationTest,
  21552. ReconnectWhileOpenSendsCloseOverLiveSession) {
  21553. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  21554. "/ws-echo");
  21555. client.enable_server_certificate_verification(false);
  21556. client.set_read_timeout(2, 0);
  21557. client.set_write_timeout(2, 0);
  21558. ASSERT_TRUE(client.connect());
  21559. ASSERT_TRUE(client.is_open());
  21560. ASSERT_TRUE(client.send("still open"));
  21561. // Reconnect without closing first: connect() calls shutdown_and_close() on
  21562. // the still-open connection, which must not touch a freed TLS session.
  21563. ASSERT_TRUE(client.connect());
  21564. ASSERT_TRUE(client.is_open());
  21565. ASSERT_TRUE(client.send("after reconnect"));
  21566. std::string msg;
  21567. EXPECT_EQ(ws::Text, client.read(msg));
  21568. EXPECT_EQ("after reconnect", msg);
  21569. client.close();
  21570. }
  21571. #endif
  21572. #ifdef CPPHTTPLIB_SSL_ENABLED
  21573. class WebSocketSSLCATest : public ::testing::Test {
  21574. protected:
  21575. void SetUp() override {
  21576. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  21577. SERVER_PRIVATE_KEY_FILE);
  21578. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21579. std::string msg;
  21580. while (ws.read(msg)) {
  21581. ws.send(msg);
  21582. }
  21583. });
  21584. port_ = server_->bind_to_any_port("127.0.0.1");
  21585. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21586. server_->wait_until_ready();
  21587. }
  21588. void TearDown() override {
  21589. server_->stop();
  21590. if (server_thread_.joinable()) { server_thread_.join(); }
  21591. }
  21592. std::string url() const {
  21593. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  21594. }
  21595. std::unique_ptr<SSLServer> server_;
  21596. std::thread server_thread_;
  21597. int port_ = 0;
  21598. };
  21599. // A custom CA loaded as PEM verifies the server with full certificate
  21600. // verification enabled
  21601. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  21602. ws::WebSocketClient client(url());
  21603. std::string cert;
  21604. read_file(SERVER_CERT2_FILE, cert);
  21605. client.load_ca_cert_store(cert.c_str(), cert.size());
  21606. ASSERT_TRUE(client.connect());
  21607. ASSERT_TRUE(client.send("hello"));
  21608. std::string msg;
  21609. EXPECT_EQ(ws::Text, client.read(msg));
  21610. EXPECT_EQ("hello", msg);
  21611. client.close();
  21612. }
  21613. // A custom CA that does not cover the server must fail verification (the
  21614. // custom CA is exclusive; system certs are not loaded alongside it)
  21615. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  21616. ws::WebSocketClient client(url());
  21617. std::string cert;
  21618. read_file(CLIENT_CA_CERT_FILE, cert);
  21619. client.load_ca_cert_store(cert.c_str(), cert.size());
  21620. auto res = client.connect();
  21621. ASSERT_FALSE(res);
  21622. EXPECT_EQ(Error::SSLServerVerification, res.error());
  21623. EXPECT_EQ(-1, res.status());
  21624. EXPECT_NE(0u, res.ssl_backend_error());
  21625. }
  21626. // The same CA as a file path rather than PEM in memory
  21627. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  21628. ws::WebSocketClient client(url());
  21629. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21630. ASSERT_TRUE(client.connect());
  21631. ASSERT_TRUE(client.send("hello"));
  21632. std::string msg;
  21633. EXPECT_EQ(ws::Text, client.read(msg));
  21634. EXPECT_EQ("hello", msg);
  21635. client.close();
  21636. }
  21637. // ...and a CA file that does not cover the server still fails, so it is the
  21638. // path above that decides the outcome
  21639. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  21640. ws::WebSocketClient client(url());
  21641. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21642. ASSERT_FALSE(client.connect());
  21643. }
  21644. // Regression test: reconnecting with a native custom CA store used to reuse
  21645. // a store handle the previous TLS context had already freed (use-after-free
  21646. // under the OpenSSL backend). The context now lives as long as the client.
  21647. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  21648. ws::WebSocketClient client(url());
  21649. std::string cert;
  21650. read_file(SERVER_CERT2_FILE, cert);
  21651. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  21652. ASSERT_TRUE(client.connect());
  21653. client.close();
  21654. ASSERT_TRUE(client.connect());
  21655. ASSERT_TRUE(client.send("again"));
  21656. std::string msg;
  21657. EXPECT_EQ(ws::Text, client.read(msg));
  21658. EXPECT_EQ("again", msg);
  21659. client.close();
  21660. }
  21661. // Regression test: a certificate with a trusted chain but no identity match
  21662. // for the server IP must be rejected. The Mbed TLS backend used to skip
  21663. // verification entirely for IP hosts, so this connection succeeded there.
  21664. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  21665. // chain verification while the identity check must still fail.
  21666. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  21667. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21668. ASSERT_TRUE(svr.is_valid());
  21669. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21670. std::string msg;
  21671. while (ws.read(msg)) {
  21672. ws.send(msg);
  21673. }
  21674. });
  21675. auto port = svr.bind_to_any_port("127.0.0.1");
  21676. auto t = std::thread([&]() { svr.listen_after_bind(); });
  21677. auto se = detail::scope_exit([&] {
  21678. svr.stop();
  21679. t.join();
  21680. });
  21681. svr.wait_until_ready();
  21682. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  21683. "/echo");
  21684. std::string cert;
  21685. read_file(SERVER_CERT_FILE, cert);
  21686. client.load_ca_cert_store(cert.c_str(), cert.size());
  21687. ASSERT_FALSE(client.connect());
  21688. }
  21689. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  21690. // SNI, so nothing binds the host name to the TLS session. These bind the
  21691. // server to "localhost" instead, the only shape that exercises the SNI and
  21692. // hostname-verification path with certificate verification left enabled.
  21693. class WebSocketSSLDnsHostTest : public ::testing::Test {
  21694. protected:
  21695. void Start(const char *cert_file) {
  21696. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  21697. SERVER_PRIVATE_KEY_FILE);
  21698. ASSERT_TRUE(server_->is_valid());
  21699. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  21700. std::string msg;
  21701. while (ws.read(msg)) {
  21702. ws.send(msg);
  21703. }
  21704. });
  21705. port_ = server_->bind_to_any_port("localhost");
  21706. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21707. server_->wait_until_ready();
  21708. }
  21709. void TearDown() override {
  21710. if (server_) { server_->stop(); }
  21711. if (server_thread_.joinable()) { server_thread_.join(); }
  21712. }
  21713. std::string url() const {
  21714. return "wss://localhost:" + std::to_string(port_) + "/echo";
  21715. }
  21716. std::unique_ptr<SSLServer> server_;
  21717. std::thread server_thread_;
  21718. int port_ = 0;
  21719. };
  21720. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  21721. // out and the connection is usable
  21722. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  21723. Start(SERVER_CERT2_FILE);
  21724. ws::WebSocketClient client(url());
  21725. client.set_ca_cert_path(SERVER_CERT2_FILE);
  21726. ASSERT_TRUE(client.connect());
  21727. ASSERT_TRUE(client.send("hello"));
  21728. std::string msg;
  21729. EXPECT_EQ(ws::Text, client.read(msg));
  21730. EXPECT_EQ("hello", msg);
  21731. client.close();
  21732. }
  21733. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  21734. // while the identity check must still reject "localhost"
  21735. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  21736. Start(SERVER_CERT_FILE);
  21737. ws::WebSocketClient client(url());
  21738. client.set_ca_cert_path(SERVER_CERT_FILE);
  21739. auto res = client.connect();
  21740. ASSERT_FALSE(res);
  21741. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  21742. EXPECT_EQ(-1, res.status());
  21743. }
  21744. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  21745. // disabled: the chain is still checked, only the identity check is skipped
  21746. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  21747. Start(SERVER_CERT_FILE);
  21748. ws::WebSocketClient client(url());
  21749. client.set_ca_cert_path(SERVER_CERT_FILE);
  21750. client.enable_server_hostname_verification(false);
  21751. ASSERT_TRUE(client.connect());
  21752. ASSERT_TRUE(client.send("hello"));
  21753. std::string msg;
  21754. EXPECT_EQ(ws::Text, client.read(msg));
  21755. EXPECT_EQ("hello", msg);
  21756. client.close();
  21757. }
  21758. // A CA that did not sign the server certificate fails the chain, even though
  21759. // the name would match
  21760. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  21761. Start(SERVER_CERT2_FILE);
  21762. ws::WebSocketClient client(url());
  21763. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  21764. ASSERT_FALSE(client.connect());
  21765. }
  21766. // With verification disabled, neither the chain nor the name is checked
  21767. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  21768. Start(SERVER_CERT_FILE);
  21769. ws::WebSocketClient client(url());
  21770. client.enable_server_certificate_verification(false);
  21771. ASSERT_TRUE(client.connect());
  21772. ASSERT_TRUE(client.send("hello"));
  21773. std::string msg;
  21774. EXPECT_EQ(ws::Text, client.read(msg));
  21775. EXPECT_EQ("hello", msg);
  21776. client.close();
  21777. }
  21778. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  21779. protected:
  21780. void SetUp() override {
  21781. server_ = httplib::detail::make_unique<SSLServer>(
  21782. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  21783. ASSERT_TRUE(server_->is_valid());
  21784. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21785. std::string msg;
  21786. while (ws.read(msg)) {
  21787. ws.send(msg);
  21788. }
  21789. });
  21790. port_ = server_->bind_to_any_port("localhost");
  21791. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21792. server_->wait_until_ready();
  21793. }
  21794. void TearDown() override {
  21795. server_->stop();
  21796. if (server_thread_.joinable()) { server_thread_.join(); }
  21797. }
  21798. std::string url() const {
  21799. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21800. }
  21801. void ConnectWithClientCert(const std::string &client_cert_file,
  21802. const std::string &client_private_key_file,
  21803. const char *private_key_password) {
  21804. std::string cert_pem, key_pem;
  21805. read_file(client_cert_file, cert_pem);
  21806. read_file(client_private_key_file, key_pem);
  21807. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21808. key_pem.c_str(), key_pem.size(),
  21809. private_key_password};
  21810. ws::WebSocketClient client(url(), pem);
  21811. ASSERT_TRUE(client.is_valid());
  21812. client.enable_server_certificate_verification(false);
  21813. ASSERT_TRUE(client.connect());
  21814. ASSERT_TRUE(client.send("hello"));
  21815. std::string msg;
  21816. EXPECT_EQ(ws::Text, client.read(msg));
  21817. EXPECT_EQ("hello", msg);
  21818. client.close();
  21819. }
  21820. std::unique_ptr<SSLServer> server_;
  21821. std::thread server_thread_;
  21822. int port_ = 0;
  21823. };
  21824. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21825. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21826. }
  21827. // Control for the tests above: the fixture's server really does require a
  21828. // client certificate, so it is the PEM the constructor installed that decides
  21829. // the outcome.
  21830. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21831. ws::WebSocketClient client(url());
  21832. ASSERT_TRUE(client.is_valid());
  21833. client.enable_server_certificate_verification(false);
  21834. EXPECT_FALSE(client.connect());
  21835. }
  21836. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21837. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21838. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21839. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21840. }
  21841. #endif
  21842. #if !defined(_WIN32)
  21843. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21844. auto secret_dir = std::string("./symlink_test_secret");
  21845. auto served_dir = std::string("./symlink_test_served");
  21846. auto secret_file = secret_dir + "/secret.txt";
  21847. auto symlink_path = served_dir + "/escape";
  21848. // Setup: create directories and files
  21849. mkdir(secret_dir.c_str(), 0755);
  21850. mkdir(served_dir.c_str(), 0755);
  21851. {
  21852. std::ofstream ofs(secret_file);
  21853. ofs << "SECRET_DATA";
  21854. }
  21855. // Create symlink using absolute path so it resolves correctly
  21856. #ifdef PATH_MAX
  21857. char abs_secret[PATH_MAX];
  21858. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21859. #else
  21860. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21861. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21862. ASSERT_NE(nullptr, abs_secret);
  21863. #endif
  21864. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21865. auto se = detail::scope_exit([&] {
  21866. unlink(symlink_path.c_str());
  21867. unlink(secret_file.c_str());
  21868. rmdir(served_dir.c_str());
  21869. rmdir(secret_dir.c_str());
  21870. });
  21871. Server svr;
  21872. svr.set_mount_point("/", served_dir);
  21873. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21874. auto se2 = detail::scope_exit([&] {
  21875. svr.stop();
  21876. listen_thread.join();
  21877. });
  21878. svr.wait_until_ready();
  21879. Client cli("localhost", PORT);
  21880. // Symlink pointing outside base dir should be blocked
  21881. auto res = cli.Get("/escape/secret.txt");
  21882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21883. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21884. }
  21885. #endif
  21886. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  21887. // "GET /smuggled" request), reads the first response, and only then sends the
  21888. // embedded request as the body. Returns how many times /smuggled ran.
  21889. //
  21890. // The body is sent AFTER receiving the first response (as in the original
  21891. // PoC) so that the stream_line_reader cannot buffer it together with the
  21892. // headers of the first request.
  21893. static int count_smuggled_requests(const std::string &outer_head,
  21894. std::string &first_response) {
  21895. Server svr;
  21896. svr.set_mount_point("/", "./www");
  21897. std::atomic<int> smuggled_count(0);
  21898. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21899. smuggled_count++;
  21900. res.set_content("oops", "text/plain");
  21901. });
  21902. svr.Post("/post", [&](const Request &req, Response &res) {
  21903. res.set_content(req.body, "text/plain");
  21904. });
  21905. auto port = svr.bind_to_any_port("localhost");
  21906. thread t = thread([&] { svr.listen_after_bind(); });
  21907. auto se = detail::scope_exit([&] {
  21908. svr.stop();
  21909. t.join();
  21910. });
  21911. svr.wait_until_ready();
  21912. auto error = Error::Success;
  21913. auto sock = detail::create_client_socket(
  21914. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21915. /*connection_timeout_sec=*/2, 0,
  21916. /*read_timeout_sec=*/2, 0,
  21917. /*write_timeout_sec=*/2, 0, std::string(), error);
  21918. EXPECT_NE(INVALID_SOCKET, sock);
  21919. if (sock == INVALID_SOCKET) { return -1; }
  21920. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21921. // The "smuggled" request will be sent as the body of the outer request
  21922. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21923. "Host: localhost\r\n"
  21924. "Connection: close\r\n"
  21925. "\r\n";
  21926. auto head = outer_head;
  21927. auto len = std::to_string(smuggled.size());
  21928. for (auto pos = head.find("{len}"); pos != std::string::npos;
  21929. pos = head.find("{len}", pos + len.size())) {
  21930. head.replace(pos, 5, len);
  21931. }
  21932. // Step 1: Send only the outer request headers (no body yet)
  21933. auto sent = send(sock, head.data(), head.size(), 0);
  21934. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  21935. // Step 2: Read the first response
  21936. char buf[4096];
  21937. for (;;) {
  21938. auto n = recv(sock, buf, sizeof(buf), 0);
  21939. if (n <= 0) break;
  21940. first_response.append(buf, static_cast<size_t>(n));
  21941. // Stop once we have a complete response (headers + body)
  21942. auto hdr_end = first_response.find("\r\n\r\n");
  21943. if (hdr_end != std::string::npos) {
  21944. // Check for Content-Length to know when the body is complete
  21945. auto cl_pos = first_response.find("Content-Length:");
  21946. if (cl_pos != std::string::npos) {
  21947. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21948. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21949. auto cl = std::stoul(
  21950. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21951. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21952. } else {
  21953. break; // No Content-Length, assume headers-only response
  21954. }
  21955. }
  21956. }
  21957. // Step 3: Now send the body, which looks like a new HTTP request. On a
  21958. // vulnerable server the keep-alive loop reads this as a second request. The
  21959. // server may already have closed the connection, so the result is ignored.
  21960. send(sock, smuggled.data(), smuggled.size(), 0);
  21961. // Half-close so that a server which drained the body sees EOF and closes,
  21962. // instead of the read below waiting for the read timeout.
  21963. #ifdef _WIN32
  21964. ::shutdown(sock, SD_SEND);
  21965. #else
  21966. ::shutdown(sock, SHUT_WR);
  21967. #endif
  21968. // Step 4: Read until the server closes the connection
  21969. for (;;) {
  21970. auto n = recv(sock, buf, sizeof(buf), 0);
  21971. if (n <= 0) break;
  21972. }
  21973. return smuggled_count.load();
  21974. }
  21975. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21976. // A GET request with Content-Length to a static file handler must have its
  21977. // body drained before the keep-alive connection is reused. Otherwise the
  21978. // unread body bytes are interpreted as the next HTTP request.
  21979. std::string first_response;
  21980. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  21981. "Host: localhost\r\n"
  21982. "Content-Length: {len}\r\n"
  21983. "\r\n",
  21984. first_response));
  21985. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  21986. }
  21987. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  21988. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  21989. // be answered with 400 and the connection closed. Treating it as "no body"
  21990. // leaves the body to be parsed as the next request.
  21991. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  21992. const char *targets[] = {
  21993. "GET /file", // handler that never reads the body
  21994. "GET /not-found", // no handler matches (404)
  21995. "POST /post", // handler that reads the body
  21996. };
  21997. for (auto target : targets) {
  21998. for (auto value : values) {
  21999. std::string first_response;
  22000. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22001. " HTTP/1.1\r\n"
  22002. "Host: localhost\r\n"
  22003. "Content-Length: " +
  22004. value + "\r\n\r\n",
  22005. first_response))
  22006. << target << " with Content-Length: " << value;
  22007. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22008. << target << " with Content-Length: " << value;
  22009. }
  22010. }
  22011. }
  22012. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22013. // A 400 for an unparseable request line leaves the rest of the message
  22014. // unread, so the connection must be closed rather than reused.
  22015. std::string first_response;
  22016. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22017. "Host: localhost\r\n"
  22018. "Content-Length: {len}\r\n"
  22019. "\r\n",
  22020. first_response));
  22021. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22022. }
  22023. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22024. // Same as above for a header block that fails to parse.
  22025. std::string first_response;
  22026. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22027. "Host: localhost\r\n"
  22028. "Bad Header\r\n"
  22029. "Content-Length: {len}\r\n"
  22030. "\r\n",
  22031. first_response));
  22032. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22033. }
  22034. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22035. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22036. // server must not read another request on that connection, even when the
  22037. // request had no body to drain.
  22038. std::string first_response;
  22039. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22040. "Host: localhost\r\n"
  22041. "\r\n",
  22042. first_response));
  22043. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22044. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22045. }
  22046. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  22047. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  22048. // must be rejected with 400 Bad Request.
  22049. Server svr;
  22050. svr.Post("/test", [&](const Request &, Response &res) {
  22051. res.set_content("ok", "text/plain");
  22052. });
  22053. thread t = thread([&] { svr.listen(HOST, PORT); });
  22054. auto se = detail::scope_exit([&] {
  22055. svr.stop();
  22056. t.join();
  22057. ASSERT_FALSE(svr.is_running());
  22058. });
  22059. svr.wait_until_ready();
  22060. // Exact "chunked"
  22061. {
  22062. auto req = "POST /test HTTP/1.1\r\n"
  22063. "Host: localhost\r\n"
  22064. "Content-Length: 5\r\n"
  22065. "Transfer-Encoding: chunked\r\n"
  22066. "Connection: close\r\n"
  22067. "\r\n"
  22068. "hello";
  22069. std::string response;
  22070. ASSERT_TRUE(send_request(1, req, &response));
  22071. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22072. response.substr(0, response.find("\r\n")));
  22073. }
  22074. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  22075. {
  22076. auto req = "POST /test HTTP/1.1\r\n"
  22077. "Host: localhost\r\n"
  22078. "Content-Length: 5\r\n"
  22079. "Transfer-Encoding: gzip, chunked\r\n"
  22080. "Connection: close\r\n"
  22081. "\r\n"
  22082. "hello";
  22083. std::string response;
  22084. ASSERT_TRUE(send_request(1, req, &response));
  22085. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22086. response.substr(0, response.find("\r\n")));
  22087. }
  22088. }
  22089. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  22090. Server svr;
  22091. svr.Post("/test", [&](const Request &, Response &res) {
  22092. res.set_content("ok", "text/plain");
  22093. });
  22094. thread t = thread([&] { svr.listen(HOST, PORT); });
  22095. auto se = detail::scope_exit([&] {
  22096. svr.stop();
  22097. t.join();
  22098. ASSERT_FALSE(svr.is_running());
  22099. });
  22100. svr.wait_until_ready();
  22101. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  22102. // length cannot be determined, so the server must answer 400 and close
  22103. // rather than treat the request as bodyless and leave the body in the
  22104. // socket for the next request to pick up.
  22105. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  22106. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  22107. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  22108. std::string response;
  22109. ASSERT_TRUE(send_request(1, req, &response));
  22110. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22111. response.substr(0, response.find("\r\n")))
  22112. << transfer_encoding;
  22113. }
  22114. // RFC 9110 5.3: the codings may also be split across several
  22115. // Transfer-Encoding lines, which combine in the order they were received.
  22116. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  22117. // just like the single-line "chunked, gzip" above.
  22118. {
  22119. auto req = "POST /test HTTP/1.1\r\n"
  22120. "Host: localhost\r\n"
  22121. "Transfer-Encoding: chunked\r\n"
  22122. "Transfer-Encoding: gzip\r\n"
  22123. "\r\n"
  22124. "0\r\n\r\n";
  22125. std::string response;
  22126. ASSERT_TRUE(send_request(1, req, &response));
  22127. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  22128. response.substr(0, response.find("\r\n")));
  22129. }
  22130. // A sequence ending in chunked stays valid.
  22131. auto req = "POST /test HTTP/1.1\r\n"
  22132. "Host: localhost\r\n"
  22133. "Transfer-Encoding: gzip, chunked\r\n"
  22134. "Connection: close\r\n"
  22135. "\r\n"
  22136. "0\r\n\r\n";
  22137. std::string response;
  22138. ASSERT_TRUE(send_request(1, req, &response));
  22139. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  22140. // ...including when it is spread over several lines.
  22141. auto split_req = "POST /test HTTP/1.1\r\n"
  22142. "Host: localhost\r\n"
  22143. "Transfer-Encoding: gzip\r\n"
  22144. "Transfer-Encoding: chunked\r\n"
  22145. "Connection: close\r\n"
  22146. "\r\n"
  22147. "0\r\n\r\n";
  22148. std::string split_response;
  22149. ASSERT_TRUE(send_request(1, split_req, &split_response));
  22150. EXPECT_EQ("HTTP/1.1 200 OK",
  22151. split_response.substr(0, split_response.find("\r\n")));
  22152. }
  22153. // Regression for issue #2450: a DELETE without Content-Length on a
  22154. // keep-alive connection must not let the post-response drain consume the
  22155. // next request's bytes.
  22156. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  22157. Server svr;
  22158. std::atomic<int> delete_count(0);
  22159. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  22160. delete_count++;
  22161. res.status = StatusCode::NoContent_204;
  22162. });
  22163. auto port = svr.bind_to_any_port(HOST);
  22164. thread t = thread([&] { svr.listen_after_bind(); });
  22165. auto se = detail::scope_exit([&] {
  22166. svr.stop();
  22167. t.join();
  22168. });
  22169. svr.wait_until_ready();
  22170. auto error = Error::Success;
  22171. auto sock = detail::create_client_socket(
  22172. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22173. /*connection_timeout_sec=*/2, 0,
  22174. /*read_timeout_sec=*/2, 0,
  22175. /*write_timeout_sec=*/2, 0, std::string(), error);
  22176. ASSERT_NE(INVALID_SOCKET, sock);
  22177. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22178. auto send_request_and_read_response = [&](const std::string &req,
  22179. std::string &out) -> bool {
  22180. auto sent = send(sock, req.data(), req.size(), 0);
  22181. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  22182. char buf[4096];
  22183. for (;;) {
  22184. auto n = recv(sock, buf, sizeof(buf), 0);
  22185. if (n <= 0) { return !out.empty(); }
  22186. out.append(buf, static_cast<size_t>(n));
  22187. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  22188. }
  22189. };
  22190. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  22191. "Host: localhost\r\n"
  22192. "\r\n";
  22193. std::string resp1;
  22194. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  22195. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  22196. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  22197. "Host: localhost\r\n"
  22198. "Connection: close\r\n"
  22199. "\r\n";
  22200. std::string resp2;
  22201. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  22202. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  22203. EXPECT_EQ(2, delete_count.load());
  22204. }
  22205. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  22206. Server svr;
  22207. svr.Post("/ingest", [&](const Request &, Response &res,
  22208. const ContentReader &content_reader) {
  22209. auto consumed = content_reader([](const char *, size_t) { return false; });
  22210. EXPECT_FALSE(consumed);
  22211. res.status = StatusCode::Conflict_409;
  22212. res.set_header("Connection", "close");
  22213. });
  22214. auto port = svr.bind_to_any_port(HOST);
  22215. thread t = thread([&] { svr.listen_after_bind(); });
  22216. auto se = detail::scope_exit([&] {
  22217. svr.stop();
  22218. t.join();
  22219. });
  22220. svr.wait_until_ready();
  22221. auto error = Error::Success;
  22222. auto sock = detail::create_client_socket(
  22223. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  22224. /*connection_timeout_sec=*/2, 0,
  22225. /*read_timeout_sec=*/1, 0,
  22226. /*write_timeout_sec=*/2, 0, std::string(), error);
  22227. ASSERT_NE(INVALID_SOCKET, sock);
  22228. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22229. std::string request = "POST /ingest HTTP/1.1\r\n"
  22230. "Host: localhost\r\n"
  22231. "Transfer-Encoding: chunked\r\n"
  22232. "\r\n"
  22233. "4\r\n"
  22234. "data\r\n";
  22235. auto sent = send(sock, request.data(), request.size(), 0);
  22236. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  22237. std::string response;
  22238. ssize_t received = 0;
  22239. do {
  22240. char buf[4096];
  22241. received = recv(sock, buf, sizeof(buf), 0);
  22242. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  22243. } while (received > 0);
  22244. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  22245. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  22246. EXPECT_EQ(0, received);
  22247. }
  22248. namespace no_proxy_test {
  22249. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  22250. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  22251. // calling listen().
  22252. class ScopedServer {
  22253. public:
  22254. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  22255. ~ScopedServer() {
  22256. svr_.stop();
  22257. if (th_.joinable()) { th_.join(); }
  22258. }
  22259. Server &svr() { return svr_; }
  22260. int port() const { return port_; }
  22261. void listen() {
  22262. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22263. svr_.wait_until_ready();
  22264. }
  22265. private:
  22266. Server svr_;
  22267. std::thread th_;
  22268. int port_ = 0;
  22269. };
  22270. class ProxyAndTargetServers {
  22271. public:
  22272. ProxyAndTargetServers() {
  22273. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  22274. proxy_hits_++;
  22275. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22276. res.set_content("via-proxy", "text/plain");
  22277. });
  22278. target_.Get(".*", [this](const Request &req, Response &res) {
  22279. target_hits_++;
  22280. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  22281. res.set_content("direct", "text/plain");
  22282. });
  22283. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  22284. target_port_ = target_.bind_to_any_port("127.0.0.1");
  22285. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  22286. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  22287. proxy_mock_.wait_until_ready();
  22288. target_.wait_until_ready();
  22289. }
  22290. ~ProxyAndTargetServers() {
  22291. proxy_mock_.stop();
  22292. target_.stop();
  22293. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  22294. if (target_thread_.joinable()) { target_thread_.join(); }
  22295. }
  22296. Server &proxy_mock() { return proxy_mock_; }
  22297. Server &target() { return target_; }
  22298. int proxy_port() const { return proxy_port_; }
  22299. int target_port() const { return target_port_; }
  22300. int proxy_hits() const { return proxy_hits_.load(); }
  22301. int target_hits() const { return target_hits_.load(); }
  22302. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  22303. void reset_counters() {
  22304. proxy_hits_ = 0;
  22305. target_hits_ = 0;
  22306. last_had_proxy_authz_ = false;
  22307. }
  22308. private:
  22309. Server proxy_mock_;
  22310. Server target_;
  22311. std::thread proxy_thread_;
  22312. std::thread target_thread_;
  22313. int proxy_port_ = 0;
  22314. int target_port_ = 0;
  22315. std::atomic<int> proxy_hits_{0};
  22316. std::atomic<int> target_hits_{0};
  22317. std::atomic<bool> last_had_proxy_authz_{false};
  22318. };
  22319. inline std::unique_ptr<Client> make_client(const std::string &host,
  22320. ProxyAndTargetServers &s) {
  22321. auto cli = detail::make_unique<Client>(host, s.target_port());
  22322. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  22323. cli->set_proxy("127.0.0.1", s.proxy_port());
  22324. return cli;
  22325. }
  22326. } // namespace no_proxy_test
  22327. using no_proxy_test::make_client;
  22328. using no_proxy_test::ProxyAndTargetServers;
  22329. TEST(NoProxyTest, ExactHostnameBypasses) {
  22330. ProxyAndTargetServers s;
  22331. auto cli = make_client("example.com", s);
  22332. cli->set_no_proxy({"example.com"});
  22333. auto res = cli->Get("/");
  22334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22335. EXPECT_EQ(0, s.proxy_hits());
  22336. EXPECT_EQ(1, s.target_hits());
  22337. }
  22338. TEST(NoProxyTest, SubdomainBypasses) {
  22339. ProxyAndTargetServers s;
  22340. auto cli = make_client("foo.example.com", s);
  22341. cli->set_no_proxy({"example.com"});
  22342. auto res = cli->Get("/");
  22343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22344. EXPECT_EQ(0, s.proxy_hits());
  22345. EXPECT_EQ(1, s.target_hits());
  22346. }
  22347. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  22348. // Regression guard: "evilexample.com" must not be considered a subdomain
  22349. // of "example.com". Without the dot-boundary rule, a naive endsWith
  22350. // check would let traffic bypass the proxy and leak credentials direct
  22351. // to the attacker host.
  22352. ProxyAndTargetServers s;
  22353. auto cli = make_client("evilexample.com", s);
  22354. cli->set_no_proxy({"example.com"});
  22355. auto res = cli->Get("/");
  22356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22357. EXPECT_GE(s.proxy_hits(), 1);
  22358. EXPECT_EQ(0, s.target_hits());
  22359. }
  22360. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  22361. ProxyAndTargetServers s;
  22362. auto cli = make_client("example.com.evil.com", s);
  22363. cli->set_no_proxy({"example.com"});
  22364. auto res = cli->Get("/");
  22365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22366. EXPECT_GE(s.proxy_hits(), 1);
  22367. EXPECT_EQ(0, s.target_hits());
  22368. }
  22369. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  22370. ProxyAndTargetServers s;
  22371. auto cli = make_client("example.com", s);
  22372. cli->set_no_proxy({".example.com"});
  22373. auto res = cli->Get("/");
  22374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22375. EXPECT_EQ(0, s.proxy_hits());
  22376. EXPECT_EQ(1, s.target_hits());
  22377. }
  22378. TEST(NoProxyTest, CaseInsensitiveHostname) {
  22379. ProxyAndTargetServers s;
  22380. auto cli = make_client("Example.COM", s);
  22381. cli->set_no_proxy({"EXAMPLE.com"});
  22382. auto res = cli->Get("/");
  22383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22384. EXPECT_EQ(0, s.proxy_hits());
  22385. EXPECT_EQ(1, s.target_hits());
  22386. }
  22387. TEST(NoProxyTest, TrailingDotIsNormalized) {
  22388. ProxyAndTargetServers s;
  22389. auto cli = make_client("example.com.", s);
  22390. cli->set_no_proxy({"example.com"});
  22391. auto res = cli->Get("/");
  22392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22393. EXPECT_EQ(0, s.proxy_hits());
  22394. EXPECT_EQ(1, s.target_hits());
  22395. }
  22396. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  22397. // Trailing dots must be normalized on BOTH sides — host and entry.
  22398. // An implementation that only strips the host-side trailing dot would
  22399. // fail to match host "example.com" against entry "example.com." because
  22400. // a literal substring search would compare 11 chars against 12.
  22401. ProxyAndTargetServers s;
  22402. auto cli = make_client("example.com", s);
  22403. cli->set_no_proxy({"example.com."});
  22404. auto res = cli->Get("/");
  22405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22406. EXPECT_EQ(0, s.proxy_hits());
  22407. EXPECT_EQ(1, s.target_hits());
  22408. }
  22409. TEST(NoProxyTest, WildcardBypassesEverything) {
  22410. ProxyAndTargetServers s;
  22411. auto cli = make_client("anything.invalid.test", s);
  22412. cli->set_no_proxy({"*"});
  22413. auto res = cli->Get("/");
  22414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22415. EXPECT_EQ(0, s.proxy_hits());
  22416. EXPECT_EQ(1, s.target_hits());
  22417. }
  22418. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  22419. ProxyAndTargetServers s;
  22420. Client cli("127.0.0.1", s.target_port());
  22421. cli.set_proxy("127.0.0.1", s.proxy_port());
  22422. cli.set_no_proxy({"127.0.0.1"});
  22423. auto res = cli.Get("/");
  22424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22425. EXPECT_EQ(0, s.proxy_hits());
  22426. EXPECT_EQ(1, s.target_hits());
  22427. }
  22428. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  22429. ProxyAndTargetServers s;
  22430. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  22431. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  22432. cli.set_proxy("127.0.0.1", s.proxy_port());
  22433. cli.set_no_proxy({"::1"});
  22434. auto res = cli.Get("/");
  22435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22436. EXPECT_EQ(0, s.proxy_hits());
  22437. EXPECT_EQ(1, s.target_hits());
  22438. }
  22439. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  22440. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  22441. // must still be recognized as IPv6 for CIDR matching. Implementations
  22442. // that detect IPv6 only when the host begins with '[' would parse the
  22443. // host as a hostname and miss the match.
  22444. ProxyAndTargetServers s;
  22445. Client cli("fe80::1", s.target_port());
  22446. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22447. cli.set_proxy("127.0.0.1", s.proxy_port());
  22448. cli.set_no_proxy({"fe80::/10"});
  22449. auto res = cli.Get("/");
  22450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22451. EXPECT_EQ(0, s.proxy_hits());
  22452. EXPECT_EQ(1, s.target_hits());
  22453. }
  22454. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  22455. ProxyAndTargetServers s;
  22456. Client cli("::1", s.target_port());
  22457. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  22458. cli.set_proxy("127.0.0.1", s.proxy_port());
  22459. cli.set_no_proxy({"[::1]"});
  22460. auto res = cli.Get("/");
  22461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22462. EXPECT_EQ(0, s.proxy_hits());
  22463. EXPECT_EQ(1, s.target_hits());
  22464. }
  22465. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  22466. ProxyAndTargetServers s;
  22467. Client cli("fe80::1", s.target_port());
  22468. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  22469. cli.set_proxy("127.0.0.1", s.proxy_port());
  22470. cli.set_no_proxy({"[fe80::]/10"});
  22471. auto res = cli.Get("/");
  22472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22473. EXPECT_EQ(0, s.proxy_hits());
  22474. EXPECT_EQ(1, s.target_hits());
  22475. }
  22476. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  22477. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  22478. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  22479. // tricks via address-family conversion.
  22480. ProxyAndTargetServers s;
  22481. Client cli("::ffff:127.0.0.1", s.target_port());
  22482. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  22483. cli.set_proxy("127.0.0.1", s.proxy_port());
  22484. cli.set_no_proxy({"127.0.0.1"});
  22485. auto res = cli.Get("/");
  22486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22487. EXPECT_GE(s.proxy_hits(), 1);
  22488. EXPECT_EQ(0, s.target_hits());
  22489. }
  22490. TEST(NoProxyTest, IPv4CidrMatch) {
  22491. ProxyAndTargetServers s;
  22492. Client cli("127.0.0.1", s.target_port());
  22493. cli.set_proxy("127.0.0.1", s.proxy_port());
  22494. cli.set_no_proxy({"127.0.0.0/8"});
  22495. auto res = cli.Get("/");
  22496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22497. EXPECT_EQ(0, s.proxy_hits());
  22498. EXPECT_EQ(1, s.target_hits());
  22499. }
  22500. TEST(NoProxyTest, IPv4CidrNonMatch) {
  22501. ProxyAndTargetServers s;
  22502. Client cli("127.0.0.1", s.target_port());
  22503. cli.set_proxy("127.0.0.1", s.proxy_port());
  22504. cli.set_no_proxy({"10.0.0.0/8"});
  22505. auto res = cli.Get("/");
  22506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22507. EXPECT_GE(s.proxy_hits(), 1);
  22508. EXPECT_EQ(0, s.target_hits());
  22509. }
  22510. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  22511. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  22512. // IPv4 target matches.
  22513. ProxyAndTargetServers s;
  22514. Client cli("127.0.0.1", s.target_port());
  22515. cli.set_proxy("127.0.0.1", s.proxy_port());
  22516. cli.set_no_proxy({"0.0.0.0/0"});
  22517. auto res = cli.Get("/");
  22518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22519. EXPECT_EQ(0, s.proxy_hits());
  22520. EXPECT_EQ(1, s.target_hits());
  22521. }
  22522. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  22523. ProxyAndTargetServers s;
  22524. Client cli("127.0.0.1", s.target_port());
  22525. cli.set_proxy("127.0.0.1", s.proxy_port());
  22526. cli.set_no_proxy({"127.0.0.1"});
  22527. auto res = cli.Get("/");
  22528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22529. EXPECT_EQ(0, s.proxy_hits());
  22530. EXPECT_EQ(1, s.target_hits());
  22531. }
  22532. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  22533. ProxyAndTargetServers s;
  22534. Client cli("127.0.0.1", s.target_port());
  22535. cli.set_proxy("127.0.0.1", s.proxy_port());
  22536. cli.set_no_proxy({"127.0.0.0/33"});
  22537. auto res = cli.Get("/");
  22538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22539. EXPECT_GE(s.proxy_hits(), 1);
  22540. EXPECT_EQ(0, s.target_hits());
  22541. }
  22542. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  22543. // Empty prefix after the slash must be rejected, not silently treated as /32.
  22544. ProxyAndTargetServers s;
  22545. Client cli("127.0.0.1", s.target_port());
  22546. cli.set_proxy("127.0.0.1", s.proxy_port());
  22547. cli.set_no_proxy({"127.0.0.1/"});
  22548. auto res = cli.Get("/");
  22549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22550. EXPECT_GE(s.proxy_hits(), 1);
  22551. EXPECT_EQ(0, s.target_hits());
  22552. }
  22553. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  22554. ProxyAndTargetServers s;
  22555. auto cli = make_client("internal.corp", s);
  22556. cli->set_proxy_basic_auth("u", "p");
  22557. cli->set_no_proxy({"internal.corp"});
  22558. auto res = cli->Get("/");
  22559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22560. EXPECT_EQ(1, s.target_hits());
  22561. EXPECT_EQ(0, s.proxy_hits());
  22562. EXPECT_FALSE(s.last_had_proxy_authz())
  22563. << "Proxy-Authorization must not be sent direct to the target";
  22564. }
  22565. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  22566. ProxyAndTargetServers s;
  22567. auto cli = make_client("public.example", s);
  22568. cli->set_proxy_basic_auth("u", "p");
  22569. cli->set_no_proxy({"internal.corp"}); // does not match
  22570. auto res = cli->Get("/");
  22571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22572. EXPECT_GE(s.proxy_hits(), 1);
  22573. EXPECT_TRUE(s.last_had_proxy_authz());
  22574. }
  22575. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  22576. ProxyAndTargetServers s;
  22577. auto cli = make_client("anything.test", s);
  22578. auto res = cli->Get("/");
  22579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22580. EXPECT_GE(s.proxy_hits(), 1);
  22581. EXPECT_EQ(0, s.target_hits());
  22582. }
  22583. TEST(NoProxyTest, PortSpecificEntryRejected) {
  22584. ProxyAndTargetServers s;
  22585. auto cli = make_client("example.com", s);
  22586. cli->set_no_proxy({"example.com:8080"});
  22587. auto res = cli->Get("/");
  22588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22589. EXPECT_GE(s.proxy_hits(), 1);
  22590. EXPECT_EQ(0, s.target_hits());
  22591. }
  22592. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  22593. ProxyAndTargetServers s;
  22594. auto cli = make_client("anything.test", s);
  22595. cli->set_no_proxy({"", " ", "\t"});
  22596. auto res = cli->Get("/");
  22597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22598. EXPECT_GE(s.proxy_hits(), 1);
  22599. EXPECT_EQ(0, s.target_hits());
  22600. }
  22601. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  22602. // An entry with leading/trailing whitespace must still match — env-style
  22603. // values are commonly pasted with stray spaces and an implementation
  22604. // that feeds the raw token directly to inet_pton would fail to match
  22605. // valid CIDRs because of the spaces.
  22606. ProxyAndTargetServers s;
  22607. Client cli("127.0.0.1", s.target_port());
  22608. cli.set_proxy("127.0.0.1", s.proxy_port());
  22609. cli.set_no_proxy({" 127.0.0.0/8 "});
  22610. auto res = cli.Get("/");
  22611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22612. EXPECT_EQ(0, s.proxy_hits());
  22613. EXPECT_EQ(1, s.target_hits());
  22614. }
  22615. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  22616. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  22617. // go direct and must NOT carry Proxy-Authorization.
  22618. std::atomic<int> proxy_hits{0};
  22619. std::atomic<int> target_hits{0};
  22620. std::atomic<bool> target_saw_authz{false};
  22621. no_proxy_test::ScopedServer proxy_mock, target;
  22622. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22623. proxy_hits++;
  22624. res.status = 302;
  22625. res.set_header("Location", "http://127.0.0.1:" +
  22626. std::to_string(target.port()) + "/landed");
  22627. });
  22628. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22629. target_hits++;
  22630. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  22631. res.set_content("direct", "text/plain");
  22632. });
  22633. proxy_mock.listen();
  22634. target.listen();
  22635. Client cli("public.example", target.port());
  22636. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22637. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22638. cli.set_proxy_basic_auth("u", "p");
  22639. cli.set_no_proxy({"127.0.0.1"});
  22640. cli.set_follow_location(true);
  22641. auto res = cli.Get("/redir");
  22642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22643. EXPECT_GE(proxy_hits.load(), 1);
  22644. EXPECT_GE(target_hits.load(), 1);
  22645. EXPECT_FALSE(target_saw_authz.load());
  22646. }
  22647. #ifdef CPPHTTPLIB_SSL_ENABLED
  22648. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  22649. // Direct origin replying 407 must not trigger the digest retry; otherwise
  22650. // proxy creds would be sent to the (possibly hostile) origin.
  22651. std::atomic<int> target_hits{0};
  22652. std::atomic<bool> target_saw_proxy_authz{false};
  22653. no_proxy_test::ScopedServer target;
  22654. target.svr().Get(".*", [&](const Request &req, Response &res) {
  22655. target_hits++;
  22656. if (req.has_header("Proxy-Authorization")) {
  22657. target_saw_proxy_authz = true;
  22658. }
  22659. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22660. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  22661. "nonce=\"abc\", algorithm=MD5");
  22662. });
  22663. target.listen();
  22664. // The proxy address is set to the target's port: the bypass MUST kick in;
  22665. // if it doesn't, the test still routes "via proxy" to the same server and
  22666. // the Proxy-Authorization assertion below catches the leak.
  22667. Client cli("evil.example", target.port());
  22668. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  22669. cli.set_proxy("127.0.0.1", target.port());
  22670. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22671. cli.set_no_proxy({"evil.example"});
  22672. auto res = cli.Get("/x");
  22673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22674. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22675. EXPECT_EQ(1, target_hits.load());
  22676. EXPECT_FALSE(target_saw_proxy_authz.load());
  22677. }
  22678. #endif
  22679. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  22680. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  22681. std::atomic<int> proxy_hits{0};
  22682. std::atomic<int> bypass_hits{0};
  22683. std::atomic<bool> proxy_saw_c_url{false};
  22684. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  22685. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  22686. proxy_hits++;
  22687. if (req.path.find("/start") != std::string::npos) {
  22688. res.status = 302;
  22689. res.set_header("Location", "http://127.0.0.1:" +
  22690. std::to_string(bypass_server.port()) +
  22691. "/middle");
  22692. return;
  22693. }
  22694. if (req.path.find("/end") != std::string::npos) {
  22695. proxy_saw_c_url = true;
  22696. res.set_content("c-via-proxy", "text/plain");
  22697. return;
  22698. }
  22699. res.set_content("unexpected", "text/plain");
  22700. });
  22701. // public.example's "advertised" port is arbitrary (the request never lands
  22702. // there — it goes through the proxy), but use a dynamic value to stay
  22703. // friendly with sharded parallel runs.
  22704. int public_port = bypass_server.port();
  22705. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  22706. bypass_hits++;
  22707. res.status = 302;
  22708. res.set_header("Location", "http://public.example:" +
  22709. std::to_string(public_port) + "/end");
  22710. });
  22711. proxy_mock.listen();
  22712. bypass_server.listen();
  22713. Client cli("public.example", public_port);
  22714. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22715. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22716. cli.set_no_proxy({"127.0.0.1"});
  22717. cli.set_follow_location(true);
  22718. auto res = cli.Get("/start");
  22719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22720. EXPECT_EQ(StatusCode::OK_200, res->status);
  22721. EXPECT_EQ("c-via-proxy", res->body);
  22722. EXPECT_GE(proxy_hits.load(), 2);
  22723. EXPECT_GE(bypass_hits.load(), 1);
  22724. EXPECT_TRUE(proxy_saw_c_url.load());
  22725. }
  22726. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  22727. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  22728. // request reconnects to the correct endpoint.
  22729. std::atomic<int> proxy_hits{0};
  22730. std::atomic<int> target_hits{0};
  22731. no_proxy_test::ScopedServer proxy_mock, target;
  22732. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  22733. proxy_hits++;
  22734. res.set_content("via-proxy", "text/plain");
  22735. });
  22736. target.svr().Get(".*", [&](const Request &, Response &res) {
  22737. target_hits++;
  22738. res.set_content("direct", "text/plain");
  22739. });
  22740. proxy_mock.listen();
  22741. target.listen();
  22742. Client cli("public.example", target.port());
  22743. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  22744. cli.set_proxy("127.0.0.1", proxy_mock.port());
  22745. cli.set_keep_alive(true);
  22746. auto res1 = cli.Get("/a");
  22747. ASSERT_TRUE(res1);
  22748. EXPECT_EQ("via-proxy", res1->body);
  22749. EXPECT_EQ(1, proxy_hits.load());
  22750. EXPECT_EQ(0, target_hits.load());
  22751. cli.set_no_proxy({"public.example"});
  22752. auto res2 = cli.Get("/b");
  22753. ASSERT_TRUE(res2);
  22754. EXPECT_EQ("direct", res2->body);
  22755. EXPECT_EQ(1, proxy_hits.load());
  22756. EXPECT_EQ(1, target_hits.load());
  22757. }
  22758. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  22759. namespace proxy_tunnel_test {
  22760. // SSLServer counterpart to no_proxy_test::ScopedServer.
  22761. class ScopedSSLServer {
  22762. public:
  22763. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  22764. port_ = svr_.bind_to_any_port("127.0.0.1");
  22765. }
  22766. ~ScopedSSLServer() {
  22767. svr_.stop();
  22768. if (th_.joinable()) { th_.join(); }
  22769. }
  22770. SSLServer &svr() { return svr_; }
  22771. int port() const { return port_; }
  22772. void listen() {
  22773. th_ = std::thread([this] { svr_.listen_after_bind(); });
  22774. svr_.wait_until_ready();
  22775. }
  22776. private:
  22777. SSLServer svr_;
  22778. std::thread th_;
  22779. int port_ = 0;
  22780. };
  22781. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  22782. class ScopedConnectProxy {
  22783. public:
  22784. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  22785. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  22786. if (listen_fd_ < 0) { return; }
  22787. int yes = 1;
  22788. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  22789. sockaddr_in a{};
  22790. a.sin_family = AF_INET;
  22791. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22792. a.sin_port = 0;
  22793. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  22794. return;
  22795. }
  22796. socklen_t alen = sizeof(a);
  22797. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  22798. 0) {
  22799. return;
  22800. }
  22801. port_ = ntohs(a.sin_port);
  22802. if (::listen(listen_fd_, 1) != 0) { return; }
  22803. th_ = std::thread([this] { run(); });
  22804. }
  22805. ~ScopedConnectProxy() {
  22806. stop_ = true;
  22807. if (listen_fd_ >= 0) {
  22808. ::shutdown(listen_fd_, SHUT_RDWR);
  22809. ::close(listen_fd_);
  22810. }
  22811. if (th_.joinable()) { th_.join(); }
  22812. }
  22813. int port() const { return port_; }
  22814. int connect_hits() const { return connect_hits_.load(); }
  22815. // Head of the last CONNECT request, as the proxy saw it on the wire.
  22816. std::string connect_request() const {
  22817. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22818. return connect_request_;
  22819. }
  22820. private:
  22821. void run() {
  22822. while (!stop_.load()) {
  22823. fd_set rfds;
  22824. FD_ZERO(&rfds);
  22825. FD_SET(listen_fd_, &rfds);
  22826. timeval tv{0, 100 * 1000};
  22827. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  22828. if (sel <= 0) { continue; }
  22829. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  22830. if (client_fd < 0) { continue; }
  22831. std::string req;
  22832. char buf[2048];
  22833. while (req.find("\r\n\r\n") == std::string::npos) {
  22834. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  22835. if (n <= 0) { break; }
  22836. req.append(buf, static_cast<size_t>(n));
  22837. }
  22838. if (req.compare(0, 7, "CONNECT") != 0) {
  22839. ::close(client_fd);
  22840. continue;
  22841. }
  22842. connect_hits_++;
  22843. {
  22844. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  22845. connect_request_ = req;
  22846. }
  22847. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  22848. ::send(client_fd, ok, std::strlen(ok), 0);
  22849. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  22850. sockaddr_in o{};
  22851. o.sin_family = AF_INET;
  22852. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  22853. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  22854. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  22855. 0) {
  22856. ::close(client_fd);
  22857. ::close(origin_fd);
  22858. continue;
  22859. }
  22860. auto forward = [](int from, int to) {
  22861. char b[8192];
  22862. for (;;) {
  22863. ssize_t n = ::recv(from, b, sizeof(b), 0);
  22864. if (n <= 0) { break; }
  22865. ssize_t off = 0;
  22866. while (off < n) {
  22867. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  22868. if (s <= 0) {
  22869. off = n;
  22870. break;
  22871. }
  22872. off += s;
  22873. }
  22874. }
  22875. ::shutdown(to, SHUT_WR);
  22876. };
  22877. std::thread t1([&] { forward(client_fd, origin_fd); });
  22878. std::thread t2([&] { forward(origin_fd, client_fd); });
  22879. t1.join();
  22880. t2.join();
  22881. ::close(client_fd);
  22882. ::close(origin_fd);
  22883. }
  22884. }
  22885. int forward_port_ = -1;
  22886. int listen_fd_ = -1;
  22887. int port_ = 0;
  22888. std::thread th_;
  22889. std::atomic<bool> stop_{false};
  22890. std::atomic<int> connect_hits_{0};
  22891. mutable std::mutex connect_request_mutex_;
  22892. std::string connect_request_;
  22893. };
  22894. // Sends one request through the CONNECT proxy to the TLS origin with a
  22895. // credential configured for each hop, and checks that each credential reaches
  22896. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22897. // origin's (every header in origin_headers) on the tunnelled request.
  22898. void CredentialsStayWithTheirHop(
  22899. const std::function<void(SSLClient &)> &set_credentials,
  22900. const std::string &scheme,
  22901. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22902. std::atomic<int> origin_hits{0};
  22903. std::atomic<bool> origin_saw_proxy_authz{false};
  22904. std::atomic<bool> origin_saw_headers{false};
  22905. ScopedSSLServer origin;
  22906. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22907. origin_hits++;
  22908. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22909. origin_saw_headers =
  22910. std::all_of(origin_headers.begin(), origin_headers.end(),
  22911. [&](const std::string &h) { return req.has_header(h); });
  22912. res.set_content("ok", "text/plain");
  22913. });
  22914. origin.listen();
  22915. ScopedConnectProxy proxy(origin.port());
  22916. ASSERT_NE(0, proxy.port());
  22917. // Pinned to 127.0.0.1 for the same reason as the test below.
  22918. SSLClient cli("127.0.0.1", origin.port());
  22919. cli.enable_server_certificate_verification(false);
  22920. cli.set_proxy("127.0.0.1", proxy.port());
  22921. set_credentials(cli);
  22922. auto res = cli.Get("/x");
  22923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22924. EXPECT_EQ(StatusCode::OK_200, res->status);
  22925. EXPECT_EQ(1, origin_hits.load());
  22926. EXPECT_EQ(1, proxy.connect_hits());
  22927. EXPECT_TRUE(origin_saw_headers.load());
  22928. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22929. << "Proxy-Authorization must not be sent inside the tunnel";
  22930. auto connect_req = proxy.connect_request();
  22931. EXPECT_NE(std::string::npos,
  22932. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22933. for (const auto &h : origin_headers) {
  22934. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22935. << h << " must not be sent to the proxy on CONNECT";
  22936. }
  22937. }
  22938. } // namespace proxy_tunnel_test
  22939. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22940. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22941. [](SSLClient &cli) {
  22942. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22943. cli.set_basic_auth("origin-user", "origin-pass");
  22944. },
  22945. "Basic");
  22946. }
  22947. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22948. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22949. [](SSLClient &cli) {
  22950. cli.set_proxy_bearer_token_auth("proxy-token");
  22951. cli.set_bearer_token_auth("origin-token");
  22952. },
  22953. "Bearer");
  22954. }
  22955. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22956. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22957. [](SSLClient &cli) {
  22958. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22959. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22960. {"Cookie", "sid=origin-session"},
  22961. {"X-Api-Key", "origin-key"}});
  22962. },
  22963. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22964. }
  22965. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22966. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22967. // retry; otherwise proxy creds would be sent to the origin.
  22968. std::atomic<int> origin_hits{0};
  22969. std::atomic<bool> origin_saw_proxy_authz{false};
  22970. proxy_tunnel_test::ScopedSSLServer origin;
  22971. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22972. origin_hits++;
  22973. if (req.has_header("Proxy-Authorization")) {
  22974. origin_saw_proxy_authz = true;
  22975. }
  22976. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22977. res.set_header("Proxy-Authenticate",
  22978. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22979. "algorithm=MD5");
  22980. });
  22981. origin.listen();
  22982. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22983. ASSERT_NE(0, proxy.port());
  22984. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22985. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22986. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22987. // and answer with its own status, making this test flaky.
  22988. SSLClient cli("127.0.0.1", origin.port());
  22989. cli.enable_server_certificate_verification(false);
  22990. cli.set_proxy("127.0.0.1", proxy.port());
  22991. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22992. auto res = cli.Get("/x");
  22993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22994. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22995. EXPECT_EQ(1, origin_hits.load());
  22996. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22997. EXPECT_EQ(1, proxy.connect_hits());
  22998. }
  22999. #endif